Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): render secure message link previews (#561)

Gustavo Yea5ed6fd0bd76
diff --git a/package.json b/package.json
index 723c6880e..b6cecd1e7 100644
--- a/package.json
+++ b/package.json
@@ -33,7 +33,7 @@
"db:migrate": "pnpm --filter @alook/web exec wrangler d1 migrations apply alook-app --local",
"db:reset": "rm -rf src/web/.wrangler/state && pnpm run db:migrate",
"test:all": "vitest run",
- "deploy:web": "pnpm db:migrate:remote && cd src/web && npx opennextjs-cloudflare build && npx opennextjs-cloudflare deploy",
+ "deploy:web": "pnpm --filter @alook/web preflight:link-preview-thumbnails && pnpm db:migrate:remote && cd src/web && npx opennextjs-cloudflare build && npx opennextjs-cloudflare deploy",
"deploy:ws-do": "cd src/ws-do && npx wrangler deploy",
"deploy:email": "cd src/email-worker && npx wrangler deploy",
"deploy:wake-worker": "cd src/wake-worker && npx wrangler deploy",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 546e610e3..726cbb998 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -421,6 +421,9 @@ importers:
katex:
specifier: ^0.18.4
version: 0.18.4
+ link-preview-js:
+ specifier: 5.0.0
+ version: 5.0.0
lucide-react:
specifier: ^1.31.0
version: 1.31.0([email protected])
@@ -4590,6 +4593,9 @@ packages:
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
+
resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}
@@ -4693,6 +4699,13 @@ packages:
resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==}
+ resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
+
+ resolution: {integrity: sha512-bQwNaDIBKID5ts/DsdhxrjqFXYfLw4ste+wMKqWA8DyKcS4qwsPP4Bk8ZNaTJjvpiX/qW3BT4sU7d6Bh5i+dag==}
+ engines: {node: '>= 6'}
+
resolution: {integrity: sha512-PvVJm3oGqrveUVW2Vt/eZGeiAIsJszYweUcYwcskg9e+IubNYKKD+rHHem7A6XVO22eDAL+inxNIGAzZ/VIWlA==}
peerDependencies:
@@ -4927,6 +4940,13 @@ packages:
resolution: {integrity: sha512-EL/iN9etCTzw/fBnp0/uj0f5BOOGvZut2mzsiiBZ/FdT6gFQCKRO/tmcKOxn5drWZ2Ndm/xBb1SI4zwWbGtmIw==}
+ resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}
+
+ resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}
+ engines: {node: '>= 6'}
+
resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
engines: {node: '>=4'}
@@ -5256,9 +5276,22 @@ packages:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
+
+ resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
+
+ resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
+ engines: {node: '>= 4'}
+
resolution: {integrity: sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==}
+ resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
+
resolution: {integrity: sha512-BTJ9aZYL3vCfZlZOBLy9v8TUqWGQ0pzFnygKwFZt5udj6viBoFIBviKPUoZLDCPn1FoXffv6McQFDenrm5Krfw==}
engines: {node: '>=20'}
@@ -5418,6 +5451,10 @@ packages:
resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==}
engines: {node: '>=8.6'}
+ resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
+ engines: {node: '>=0.12'}
+
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
@@ -6145,6 +6182,9 @@ packages:
resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
+ resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==}
+
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
engines: {node: '>= 0.8'}
@@ -6811,6 +6851,10 @@ packages:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
+ resolution: {integrity: sha512-+/R92+k6wwhkdJa7tSXp2WqLaRjyo2eTNbgxNyuZV9fKZ6zLcM9ZSd2ZdzsvrZwAvu4sk3vSfxEmj0xwfOVe7Q==}
+ engines: {node: '>=22'}
+
resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==}
@@ -7380,6 +7424,9 @@ packages:
resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
+
resolution: {integrity: sha512-MCnImG4Q5vPwhSXnov56nOuyyKn6LC+Qd7II1UiKc+ACRtug5iAtn0+CwXNxM38AC5lSowEY+oYEtZX2qMnUyw==}
@@ -7576,6 +7623,9 @@ packages:
resolution: {integrity: sha512-twN+njEipszzlMJd4ONUYgSfZPDxgHhT9Ahed5uTigpQn90FggW4SA/AIPq/6a149fTbE9qBEcSwE3FAEp6wQQ==}
+ resolution: {integrity: sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==}
+
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
@@ -8740,6 +8790,10 @@ packages:
resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
engines: {node: '>=20.18.1'}
+ resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==}
+ engines: {node: '>=22.19.0'}
+
resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}
@@ -13255,6 +13309,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
@@ -13355,6 +13411,26 @@ snapshots:
+ dependencies:
+ boolbase: 1.0.0
+ css-select: 5.2.2
+ css-what: 6.2.2
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+
+ dependencies:
+ cheerio-select: 2.1.0
+ dom-serializer: 2.0.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ htmlparser2: 8.0.2
+ parse5: 7.3.0
+ parse5-htmlparser2-tree-adapter: 7.1.0
+ tslib: 2.8.1
+
dependencies:
chevrotain: 12.0.0
@@ -13608,6 +13684,16 @@ snapshots:
+ dependencies:
+ boolbase: 1.0.0
+ css-what: 6.2.2
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ nth-check: 2.1.1
+
+
@@ -13931,10 +14017,28 @@ snapshots:
dependencies:
esutils: 2.0.3
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ entities: 4.5.0
+
+
+ dependencies:
+ domelementtype: 2.3.0
+
optionalDependencies:
'@types/trusted-types': 2.0.7
+ dependencies:
+ dom-serializer: 2.0.0
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+
dependencies:
type-fest: 5.8.0
@@ -14005,6 +14109,8 @@ snapshots:
ansi-colors: 4.1.3
strip-ansi: 6.0.1
+
@@ -15156,6 +15262,13 @@ snapshots:
+ dependencies:
+ domelementtype: 2.3.0
+ domhandler: 5.0.3
+ domutils: 3.2.2
+ entities: 4.5.0
+
dependencies:
depd: 2.0.0
@@ -15798,6 +15911,11 @@ snapshots:
+ dependencies:
+ cheerio: 1.0.0-rc.11
+ undici: 8.10.0
+
@@ -16678,6 +16796,10 @@ snapshots:
path-key: 4.0.0
unicorn-magic: 0.3.0
+ dependencies:
+ boolbase: 1.0.0
+
dependencies:
esm-env: 1.2.2
@@ -16974,6 +17096,11 @@ snapshots:
+ dependencies:
+ domhandler: 5.0.3
+ parse5: 7.3.0
+
dependencies:
entities: 6.0.1
@@ -18605,6 +18732,8 @@ snapshots:
+
dependencies:
pathe: 2.0.3
diff --git a/src/shared/src/lib/rate-limits.ts b/src/shared/src/lib/rate-limits.ts
index 4ea0f8d7c..1b4f37ef7 100644
--- a/src/shared/src/lib/rate-limits.ts
+++ b/src/shared/src/lib/rate-limits.ts
@@ -23,6 +23,17 @@ export const RATE_LIMITS = {
* any single channel/DM without throttling normal chat bursts.
*/
"community:msgSend": { windowMs: 10_000, max: 30 },
+ /**
+ * Authenticated link-preview lookups. Cache hits are cheap but still count:
+ * the boundary accepts a user-controlled public URL and must stay bounded
+ * even when KV is cold or unavailable.
+ */
+ "community:linkPreview": { windowMs: 60_000, max: 60 },
+ /**
+ * Authenticated same-origin thumbnail cache misses. The digest-only route
+ * cannot choose an origin, but decoding/transcoding is still bounded work.
+ */
+ "community:linkPreviewThumbnail": { windowMs: 60_000, max: 120 },
/**
* OTP send (better-auth `/email-otp/send-verification-otp`). Prevents
* cost/abuse from someone spamming another user's inbox. Window/max are
diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.ts
index 5a107ffae..3542f13e4 100644
--- a/src/web/cloudflare-env.d.ts
+++ b/src/web/cloudflare-env.d.ts
@@ -1,6 +1,6 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --env-interface=CloudflareEnv ./cloudflare-env.d.ts` (hash: 50fe13e080f1b562dfa5be61100ab886)
-// Runtime types generated with [email protected] 2026-04-09 nodejs_compat
+// Generated by Wrangler by running `wrangler types --env-interface=CloudflareEnv ./cloudflare-env.d.ts` (hash: a27a7b391b3db90b6ddb2cd1ea69e00b)
+// Runtime types generated with [email protected] 2026-04-09 global_fetch_strictly_public,nodejs_compat
interface __BaseEnv_CloudflareEnv {
CACHE_KV: KVNamespace;
NEXT_INC_CACHE_R2_BUCKET: R2Bucket;
@@ -10,15 +10,18 @@ interface __BaseEnv_CloudflareEnv {
NEXT_TAG_CACHE_D1: D1Database;
DB: D1Database;
WAKE_QUEUE: Queue;
+ IMAGES: ImagesBinding;
ASSETS: Fetcher;
RUNTIME_MODEL_OPTIONS: "{\"claude\":[\"claude-opus-4-6\",\"claude-sonnet-4-6\",\"claude-haiku-4-5\"],\"codex\":[\"gpt-5.4\",\"gpt-5.3-codex\"]}";
MIN_CLI_VERSION: "0.0.159";
BETTER_AUTH_SECRET: string;
BETTER_AUTH_URL: string;
+ ENCRYPTION_KEY: string;
GITHUB_CLIENT_ID: string;
GITHUB_CLIENT_SECRET: string;
GOOGLE_CLIENT_ID: string;
GOOGLE_CLIENT_SECRET: string;
+ DEVICE_CLIENT_IDS: string;
NEXT_CACHE_DO_QUEUE: DurableObjectNamespace<import("./custom-worker").DOQueueHandler>;
WORKER_SELF_REFERENCE: Service<typeof import("./custom-worker").default>;
WS_DO_WORKER: Fetcher /* alook-ws-do */;
@@ -37,7 +40,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "DEVICE_CLIENT_IDS">> {}
}
// Begin runtime types
@@ -59,26 +62,26 @@ and limitations under the License.
// noinspection JSUnusedGlobalSymbols
declare var onmessage: never;
/**
- * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API.
+ * The **`DOMException`** interface represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web API. This is how error conditions are described in web APIs.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)
*/
declare class DOMException extends Error {
constructor(message?: string, name?: string);
/**
- * The **`message`** read-only property of the a message or description associated with the given error name.
+ * The **`message`** read-only property of the DOMException interface returns a string representing a message or description associated with the given error name.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message)
*/
readonly message: string;
/**
- * The **`name`** read-only property of the one of the strings associated with an error name.
+ * The **`name`** read-only property of the DOMException interface returns a string that contains one of the strings associated with an error name.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name)
*/
readonly name: string;
/**
- * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match.
+ * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or 0 if none match.
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)
@@ -136,61 +139,61 @@ interface Console {
*/
clear(): void;
/**
- * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called.
+ * The **`console.count()`** static method logs the number of times that this particular call to count() has been called.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static)
*/
count(label?: string): void;
/**
- * The **`console.countReset()`** static method resets counter used with console/count_static.
+ * The **`console.countReset()`** static method resets counter used with console.count().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static)
*/
countReset(label?: string): void;
/**
- * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level.
+ * The **`console.debug()`** static method outputs a message to the console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the Debug or Verbose log level.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static)
*/
debug(...data: any[]): void;
/**
- * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object.
+ * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. In browser consoles, the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static)
*/
dir(item?: any, options?: any): void;
/**
- * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element.
+ * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static)
*/
dirxml(...data: any[]): void;
/**
- * The **`console.error()`** static method outputs a message to the console at the 'error' log level.
+ * The **`console.error()`** static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)
*/
error(...data: any[]): void;
/**
- * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called.
+ * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console.groupEnd() is called.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static)
*/
group(...data: any[]): void;
/**
- * The **`console.groupCollapsed()`** static method creates a new inline group in the console.
+ * The **`console.groupCollapsed()`** static method creates a new inline group in the console. Unlike console.group(), however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static)
*/
groupCollapsed(...data: any[]): void;
/**
- * The **`console.groupEnd()`** static method exits the current inline group in the console.
+ * The **`console.groupEnd()`** static method exits the current inline group in the console. See Using groups in the console in the console documentation for details and examples.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static)
*/
groupEnd(): void;
/**
- * The **`console.info()`** static method outputs a message to the console at the 'info' log level.
+ * The **`console.info()`** static method outputs a message to the console at the "info" log level. The message is only displayed to the user if the console is configured to display info output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as a small "i" icon next to it.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static)
*/
@@ -208,23 +211,24 @@ interface Console {
*/
table(tabularData?: any, properties?: string[]): void;
/**
- * The **`console.time()`** static method starts a timer you can use to track how long an operation takes.
+ * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static)
*/
time(label?: string): void;
/**
- * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static.
+ * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console.time().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static)
*/
timeEnd(label?: string): void;
/**
- * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static.
+ * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console.time().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static)
*/
timeLog(label?: string, ...data: any[]): void;
+ /* The **`console.timeStamp()`** static method adds a single marker to the browser's Performance tool (Firefox bug 1387528, Chrome). This lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events. */
timeStamp(label?: string): void;
/**
* The **`console.trace()`** static method outputs a stack trace to the console.
@@ -233,7 +237,7 @@ interface Console {
*/
trace(...data: any[]): void;
/**
- * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level.
+ * The **`console.warn()`** static method outputs a warning message to the console at the "warning" log level. The message is only displayed to the user if the console is configured to display warning output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as yellow colors and a warning icon.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)
*/
@@ -399,7 +403,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
declare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
/**
- * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order.
+ * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
*/
@@ -444,6 +448,7 @@ declare const crypto: Crypto;
* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
*/
declare const caches: CacheStorage;
+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scheduler) */
declare const scheduler: Scheduler;
/**
* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
@@ -465,6 +470,7 @@ interface ExecutionContext<Props = unknown> {
cache?: CacheContext;
readonly access?: CloudflareAccessContext;
tracing: Tracing;
+ abort(reason?: any): void;
}
type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext<Props>) => Response | Promise<Response>;
type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
@@ -668,26 +674,26 @@ interface AnalyticsEngineDataPoint {
blobs?: ((ArrayBuffer | string) | null)[];
}
/**
- * The **`Event`** interface represents an event which takes place on an `EventTarget`.
+ * The **`Event`** interface represents an event which takes place on an EventTarget.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)
*/
declare class Event {
constructor(type: string, init?: EventInit);
/**
- * The **`type`** read-only property of the Event interface returns a string containing the event's type.
+ * The **`type`** read-only property of the Event interface returns a string containing the event's type. It is set when the event is constructed and is the name commonly used to refer to the specific event, such as click, load, or error.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)
*/
get type(): string;
/**
- * The **`eventPhase`** read-only property of the being evaluated.
+ * The **`eventPhase`** read-only property of the Event interface indicates which phase of the event flow is currently being evaluated.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)
*/
get eventPhase(): number;
/**
- * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM.
+ * The read-only **`composed`** property of the Event interface returns a boolean value which indicates whether or not the event will propagate across the shadow DOM boundary into the standard DOM.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)
*/
@@ -724,13 +730,13 @@ declare class Event {
*/
get currentTarget(): EventTarget | undefined;
/**
- * The read-only **`target`** property of the dispatched.
+ * The read-only **`target`** property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)
*/
get target(): EventTarget | undefined;
/**
- * The deprecated **`Event.srcElement`** is an alias for the Event.target property.
+ * The deprecated **`Event.srcElement`** is an alias for the Event.target property. Use Event.target instead.
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)
@@ -743,45 +749,45 @@ declare class Event {
*/
get timeStamp(): number;
/**
- * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents.
+ * The **`isTrusted`** read-only property of the Event interface is a boolean value that is true when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and false when the event was dispatched via EventTarget.dispatchEvent(). The only exception is the click event, which initializes the isTrusted property to false in user agents.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)
*/
get isTrusted(): boolean;
/**
- * The **`cancelBubble`** property of the Event interface is deprecated.
+ * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
*/
get cancelBubble(): boolean;
/**
- * The **`cancelBubble`** property of the Event interface is deprecated.
+ * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
*/
set cancelBubble(value: boolean);
/**
- * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added.
+ * The **`stopImmediatePropagation()`** method of the Event interface prevents other listeners of the same event from being called.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)
*/
stopImmediatePropagation(): void;
/**
- * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
+ * The **`preventDefault()`** method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)
*/
preventDefault(): void;
/**
- * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.
+ * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method. It also does not prevent propagation to other event-handlers of the current element. If you want to stop those, see stopImmediatePropagation().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)
*/
stopPropagation(): void;
/**
- * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked.
+ * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. This does not include nodes in shadow trees if the shadow root was created with its ShadowRoot.mode closed.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)
*/
@@ -802,7 +808,7 @@ interface EventListenerObject<EventType extends Event = Event> {
}
type EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;
/**
- * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them.
+ * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)
*/
@@ -815,13 +821,13 @@ declare class EventTarget<EventMap extends Record<string, Event> = Record<string
*/
addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
/**
- * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target.
+ * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)
*/
removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
/**
- * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order.
+ * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
*/
@@ -853,7 +859,7 @@ declare class AbortController {
*/
get signal(): AbortSignal;
/**
- * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed.
+ * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. This is able to abort fetch requests, the consumption of any response bodies, or streams.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)
*/
@@ -866,7 +872,7 @@ declare class AbortController {
*/
declare abstract class AbortSignal extends EventTarget {
/**
- * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event).
+ * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static)
*/
@@ -878,13 +884,13 @@ declare abstract class AbortSignal extends EventTarget {
*/
static timeout(delay: number): AbortSignal;
/**
- * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal.
+ * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. The returned abort signal is aborted when any of the input iterable abort signals are aborted. The abort reason will be set to the reason of the first signal that is aborted. If any of the given abort signals are already aborted then so will be the returned AbortSignal.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static)
*/
static any(signals: AbortSignal[]): AbortSignal;
/**
- * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`).
+ * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (true) or not (false).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)
*/
@@ -900,12 +906,17 @@ declare abstract class AbortSignal extends EventTarget {
/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */
set onabort(value: any | null);
/**
- * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing.
+ * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted)
*/
throwIfAborted(): void;
}
+/**
+ * The **`Scheduler`** interface of the Prioritized Task Scheduling API provides methods for scheduling prioritized tasks.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Scheduler)
+ */
interface Scheduler {
wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;
}
@@ -913,20 +924,20 @@ interface SchedulerWaitOptions {
signal?: AbortSignal;
}
/**
- * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle.
+ * The **`ExtendableEvent`** interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)
*/
declare abstract class ExtendableEvent extends Event {
/**
- * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing.
+ * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil)
*/
waitUntil(promise: Promise<any>): void;
}
/**
- * The **`CustomEvent`** interface represents events initialized by an application for any purpose.
+ * The **`CustomEvent`** interface can be used to attach custom data to an event generated by an application.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent)
*/
@@ -965,7 +976,7 @@ declare class Blob {
*/
get type(): string;
/**
- * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called.
+ * The **`slice()`** method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice)
*/
@@ -983,13 +994,13 @@ declare class Blob {
*/
bytes(): Promise<Uint8Array>;
/**
- * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8.
+ * The **`text()`** method of the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text)
*/
text(): Promise<string>;
/**
- * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`.
+ * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream)
*/
@@ -1006,13 +1017,13 @@ interface BlobOptions {
declare class File extends Blob {
constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);
/**
- * The **`name`** read-only property of the File interface returns the name of the file represented by a File object.
+ * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)
*/
get name(): string;
/**
- * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight).
+ * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified)
*/
@@ -1029,7 +1040,7 @@ interface FileOptions {
*/
declare abstract class CacheStorage {
/**
- * The **`open()`** method of the the Cache object matching the `cacheName`.
+ * The **`open()`** method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open)
*/
@@ -1062,14 +1073,14 @@ interface CacheQueryOptions {
*/
declare abstract class Crypto {
/**
- * The **`Crypto.subtle`** read-only property returns a cryptographic operations.
+ * The **`Crypto.subtle`** read-only property returns a SubtleCrypto which can then be used to perform low-level cryptographic operations.
* Available only in secure contexts.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)
*/
get subtle(): SubtleCrypto;
/**
- * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values.
+ * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues)
*/
@@ -1097,7 +1108,7 @@ declare abstract class SubtleCrypto {
*/
encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
/**
- * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data.
+ * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. It takes as arguments a key to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext"). It returns a Promise which will be fulfilled with the decrypted data (also known as "plaintext").
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt)
*/
@@ -1115,7 +1126,7 @@ declare abstract class SubtleCrypto {
*/
verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;
/**
- * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function.
+ * The **`digest()`** method of the SubtleCrypto interface generates a digest of the given data, using the specified hash function. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest)
*/
@@ -1133,7 +1144,7 @@ declare abstract class SubtleCrypto {
*/
deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
/**
- * The **`deriveBits()`** method of the key.
+ * The **`deriveBits()`** method of the SubtleCrypto interface can be used to derive an array of bits from a base key.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits)
*/
@@ -1151,13 +1162,13 @@ declare abstract class SubtleCrypto {
*/
exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;
/**
- * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key.
+ * The **`wrapKey()`** method of the SubtleCrypto interface "wraps" a key. This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey)
*/
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;
/**
- * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key.
+ * The **`unwrapKey()`** method of the SubtleCrypto interface "unwraps" a key. This means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). It decrypts the key and then imports it, returning a CryptoKey object that can be used in the Web Crypto API.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey)
*/
@@ -1165,20 +1176,20 @@ declare abstract class SubtleCrypto {
timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;
}
/**
- * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey.
+ * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey(), deriveKey(), importKey(), or unwrapKey().
* Available only in secure contexts.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)
*/
declare abstract class CryptoKey {
/**
- * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object.
+ * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. It can have the following values:
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type)
*/
readonly type: string;
/**
- * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`.
+ * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable)
*/
@@ -1300,7 +1311,7 @@ declare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView>
get bytesWritten(): number | bigint;
}
/**
- * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc.
+ * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, or GBK. A decoder takes an array of bytes as input and returns a JavaScript string.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)
*/
@@ -1317,20 +1328,20 @@ declare class TextDecoder {
get ignoreBOM(): boolean;
}
/**
- * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes.
+ * The **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)
*/
declare class TextEncoder {
constructor();
/**
- * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.
+ * The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)
*/
encode(input?: string): Uint8Array;
/**
- * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding.
+ * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding. This is potentially more performant than the encode() method — especially when the target buffer is a view into a Wasm heap.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)
*/
@@ -1401,31 +1412,31 @@ interface ErrorEventErrorEventInit {
declare class MessageEvent extends Event {
constructor(type: string, initializer: MessageEventInit);
/**
- * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event.
+ * The **`data`** read-only property of the MessageEvent interface represents the data sent by the message emitter.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)
*/
readonly data: any;
/**
- * The **`origin`** read-only property of the origin of the message emitter.
+ * The **`origin`** read-only property of the MessageEvent interface is a string representing the origin of the message emitter.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin)
*/
readonly origin: string | null;
/**
- * The **`lastEventId`** read-only property of the unique ID for the event.
+ * The **`lastEventId`** read-only property of the MessageEvent interface is a string representing a unique ID for the event.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId)
*/
readonly lastEventId: string;
/**
- * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter.
+ * The **`source`** read-only property of the MessageEvent interface is a MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)
*/
readonly source: MessagePort | null;
/**
- * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order.
+ * The **`ports`** read-only property of the MessageEvent interface is an array of MessagePort objects containing all MessagePort objects sent with the message, in order.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports)
*/
@@ -1435,99 +1446,96 @@ interface MessageEventInit {
data: ArrayBuffer | string;
}
/**
- * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected.
+ * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. These events are particularly useful for telemetry and debugging purposes.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent)
*/
declare abstract class PromiseRejectionEvent extends Event {
/**
- * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected.
+ * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript Promise which was rejected. You can examine the event's PromiseRejectionEvent.reason property to learn why the promise was rejected.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise)
*/
readonly promise: Promise<any>;
/**
- * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject().
+ * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). This in theory provides information about why the promise was rejected.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason)
*/
readonly reason: any;
}
/**
- * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods.
+ * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the fetch(), XMLHttpRequest.send() or navigator.sendBeacon() methods. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)
*/
declare class FormData {
constructor();
/**
- * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist.
+ * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
*/
append(name: string, value: string | Blob): void;
/**
- * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist.
+ * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
*/
append(name: string, value: string): void;
/**
- * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist.
+ * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
*/
append(name: string, value: Blob, filename?: string): void;
/**
- * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object.
+ * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a FormData object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete)
*/
delete(name: string): void;
/**
- * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object.
+ * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)
*/
get(name: string): (File | string) | null;
/**
- * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object.
+ * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a FormData object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll)
*/
getAll(name: string): (File | string)[];
/**
- * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key.
+ * The **`has()`** method of the FormData interface returns whether a FormData object contains a certain key.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has)
*/
has(name: string): boolean;
/**
- * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist.
+ * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
*/
set(name: string, value: string | Blob): void;
/**
- * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist.
+ * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
*/
set(name: string, value: string): void;
/**
- * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist.
+ * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
*/
set(name: string, value: Blob, filename?: string): void;
- /* Returns an array of key, value pairs for every entry in the list. */
entries(): IterableIterator<[
key: string,
value: File | string
]>;
- /* Returns a list of keys in the list. */
keys(): IterableIterator<string>;
- /* Returns a list of values in the list. */
values(): IterableIterator<(File | string)>;
forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;
[Symbol.iterator](): IterableIterator<[
@@ -1606,19 +1614,19 @@ interface DocumentEnd {
append(content: string, options?: ContentOptions): DocumentEnd;
}
/**
- * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope.
+ * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)
*/
declare abstract class FetchEvent extends ExtendableEvent {
/**
- * The **`request`** read-only property of the the event handler.
+ * The **`request`** read-only property of the FetchEvent interface returns the Request that triggered the event handler.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request)
*/
readonly request: Request;
/**
- * The **`respondWith()`** method of allows you to provide a promise for a Response yourself.
+ * The **`respondWith()`** method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith)
*/
@@ -1627,58 +1635,55 @@ declare abstract class FetchEvent extends ExtendableEvent {
}
type HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;
/**
- * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers.
+ * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)
*/
declare class Headers {
constructor(init?: HeadersInit);
/**
- * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name.
+ * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get)
*/
get(name: string): string | null;
getAll(name: string): string[];
/**
- * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response.
+ * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. This allows Headers objects to handle having multiple Set-Cookie headers, which wasn't possible prior to its implementation.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie)
*/
getSetCookie(): string[];
/**
- * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header.
+ * The **`has()`** method of the Headers interface returns a boolean stating whether a Headers object contains a certain header.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has)
*/
has(name: string): boolean;
/**
- * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.
+ * The **`set()`** method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set)
*/
set(name: string, value: string): void;
/**
- * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.
+ * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append)
*/
append(name: string, value: string): void;
/**
- * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object.
+ * The **`delete()`** method of the Headers interface deletes a header from the current Headers object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete)
*/
delete(name: string): void;
forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;
- /* Returns an iterator allowing to go through all key/value pairs contained in this object. */
entries(): IterableIterator<[
key: string,
value: string
]>;
- /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */
keys(): IterableIterator<string>;
- /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<[
key: string,
@@ -1741,7 +1746,7 @@ interface Response extends Body {
*/
statusText: string;
/**
- * The **`headers`** read-only property of the with the response.
+ * The **`headers`** read-only property of the Response interface contains the Headers object associated with the response.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers)
*/
@@ -1759,7 +1764,7 @@ interface Response extends Body {
*/
redirected: boolean;
/**
- * The **`url`** read-only property of the Response interface contains the URL of the response.
+ * The **`url`** read-only property of the Response interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url)
*/
@@ -1767,7 +1772,7 @@ interface Response extends Body {
webSocket: WebSocket | null;
cf: any | undefined;
/**
- * The **`type`** read-only property of the Response interface contains the type of the response.
+ * The **`type`** read-only property of the Response interface contains the type of the response. The type determines whether scripts are able to access the response body and headers.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type)
*/
@@ -1798,13 +1803,13 @@ declare var Request: {
*/
interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {
/**
- * The **`clone()`** method of the Request interface creates a copy of the current `Request` object.
+ * The **`clone()`** method of the Request interface creates a copy of the current Request object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone)
*/
clone(): Request<CfHostMetadata, Cf>;
/**
- * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request.
+ * The **`method`** read-only property of the Request interface contains the request's method (GET, POST, etc.)
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)
*/
@@ -1816,7 +1821,7 @@ interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> e
*/
url: string;
/**
- * The **`headers`** read-only property of the with the request.
+ * The **`headers`** read-only property of the Request interface contains the Headers object associated with the request.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)
*/
@@ -1842,13 +1847,13 @@ interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> e
*/
integrity: string;
/**
- * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete.
+ * The **`keepalive`** read-only property of the Request interface contains the request's keepalive setting (true or false), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)
*/
keepalive: boolean;
/**
- * The **`cache`** read-only property of the Request interface contains the cache mode of the request.
+ * The **`cache`** read-only property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache)
*/
@@ -2237,7 +2242,7 @@ type ReadableStreamReadResult<R = any> = {
value?: undefined;
};
/**
- * The `ReadableStream` interface of the Streams API represents a readable stream of byte data.
+ * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
*/
@@ -2255,13 +2260,13 @@ interface ReadableStream<R = any> {
*/
cancel(reason?: any): Promise<void>;
/**
- * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it.
+ * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
*/
getReader(): ReadableStreamDefaultReader<R>;
/**
- * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it.
+ * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
*/
@@ -2273,13 +2278,13 @@ interface ReadableStream<R = any> {
*/
pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
/**
- * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
+ * The **`pipeTo()`** method of the ReadableStream interface pipes the current ReadableStream to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo)
*/
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
/**
- * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances.
+ * The **`tee()`** method of the ReadableStream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee)
*/
@@ -2291,7 +2296,7 @@ interface ReadableStream<R = any> {
[Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;
}
/**
- * The `ReadableStream` interface of the Streams API represents a readable stream of byte data.
+ * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
*/
@@ -2323,7 +2328,7 @@ declare class ReadableStreamDefaultReader<R = any> {
releaseLock(): void;
}
/**
- * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source.
+ * The **`ReadableStreamBYOBReader`** interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader)
*/
@@ -2332,13 +2337,13 @@ declare class ReadableStreamBYOBReader {
get closed(): Promise<void>;
cancel(reason?: any): Promise<void>;
/**
- * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream.
+ * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read)
*/
read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;
/**
- * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream.
+ * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock)
*/
@@ -2357,7 +2362,7 @@ interface ReadableStreamGetReaderOptions {
mode: "byob";
}
/**
- * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues).
+ * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a "pull request" for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest)
*/
@@ -2383,13 +2388,13 @@ declare abstract class ReadableStreamBYOBRequest {
get atLeast(): number | null;
}
/**
- * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue.
+ * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. Default controllers are for streams that are not byte streams.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController)
*/
declare abstract class ReadableStreamDefaultController<R = any> {
/**
- * The **`desiredSize`** read-only property of the required to fill the stream's internal queue.
+ * The **`desiredSize`** read-only property of the ReadableStreamDefaultController interface returns the desired size required to fill the stream's internal queue.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize)
*/
@@ -2401,32 +2406,32 @@ declare abstract class ReadableStreamDefaultController<R = any> {
*/
close(): void;
/**
- * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue.
+ * The **`enqueue()`** method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue)
*/
enqueue(chunk?: R): void;
/**
- * The **`error()`** method of the with the associated stream to error.
+ * The **`error()`** method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error)
*/
error(reason: any): void;
}
/**
- * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream.
+ * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. It allows control of the state and internal queue of a ReadableStream with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController)
*/
declare abstract class ReadableByteStreamController {
/**
- * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests.
+ * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or null if there are no pending requests.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest)
*/
get byobRequest(): ReadableStreamBYOBRequest | null;
/**
- * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'.
+ * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its "desired size".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize)
*/
@@ -2438,7 +2443,7 @@ declare abstract class ReadableByteStreamController {
*/
close(): void;
/**
- * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues).
+ * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is transferred into the stream's internal queues).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue)
*/
@@ -2451,7 +2456,7 @@ declare abstract class ReadableByteStreamController {
error(reason: any): void;
}
/**
- * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state.
+ * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)
*/
@@ -2463,7 +2468,7 @@ declare abstract class WritableStreamDefaultController {
*/
get signal(): AbortSignal;
/**
- * The **`error()`** method of the with the associated stream to error.
+ * The **`error()`** method of the WritableStreamDefaultController interface causes any future interactions with the associated stream to error.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error)
*/
@@ -2488,7 +2493,7 @@ declare abstract class TransformStreamDefaultController<O = any> {
*/
enqueue(chunk?: O): void;
/**
- * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream.
+ * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error)
*/
@@ -2510,14 +2515,14 @@ interface ReadableWritablePair<R = any, W = any> {
writable: WritableStream<W>;
}
/**
- * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink.
+ * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)
*/
declare class WritableStream<W = any> {
constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);
/**
- * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer.
+ * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the WritableStream is locked to a writer.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked)
*/
@@ -2529,83 +2534,83 @@ declare class WritableStream<W = any> {
*/
abort(reason?: any): Promise<void>;
/**
- * The **`close()`** method of the WritableStream interface closes the associated stream.
+ * The **`close()`** method of the WritableStream interface closes the associated stream. All chunks written before this method is called are sent before the returned promise is fulfilled.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close)
*/
close(): Promise<void>;
/**
- * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance.
+ * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter)
*/
getWriter(): WritableStreamDefaultWriter<W>;
}
/**
- * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink.
+ * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the WritableStream ensuring that no other streams can write to the underlying sink.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)
*/
declare class WritableStreamDefaultWriter<W = any> {
constructor(stream: WritableStream);
/**
- * The **`closed`** read-only property of the the stream errors or the writer's lock is released.
+ * The **`closed`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed)
*/
get closed(): Promise<void>;
/**
- * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.
+ * The **`ready`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready)
*/
get ready(): Promise<void>;
/**
- * The **`desiredSize`** read-only property of the to fill the stream's internal queue.
+ * The **`desiredSize`** read-only property of the WritableStreamDefaultWriter interface returns the desired size required to fill the stream's internal queue.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize)
*/
get desiredSize(): number | null;
/**
- * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
+ * The **`abort()`** method of the WritableStreamDefaultWriter interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort)
*/
abort(reason?: any): Promise<void>;
/**
- * The **`close()`** method of the stream.
+ * The **`close()`** method of the WritableStreamDefaultWriter interface closes the associated writable stream.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close)
*/
close(): Promise<void>;
/**
- * The **`write()`** method of the operation.
+ * The **`write()`** method of the WritableStreamDefaultWriter interface writes a passed chunk of data to a WritableStream and its underlying sink, then returns a Promise that resolves to indicate the success or failure of the write operation.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write)
*/
write(chunk?: W): Promise<void>;
/**
- * The **`releaseLock()`** method of the corresponding stream.
+ * The **`releaseLock()`** method of the WritableStreamDefaultWriter interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock)
*/
releaseLock(): void;
}
/**
- * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept.
+ * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream)
*/
declare class TransformStream<I = any, O = any> {
constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
/**
- * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`.
+ * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this TransformStream. This stream emits the transformed output data.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable)
*/
get readable(): ReadableStream<O>;
/**
- * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`.
+ * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this TransformStream. This stream accepts input data that will be transformed and emitted to the readable stream.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable)
*/
@@ -2624,7 +2629,7 @@ interface ReadableStreamValuesOptions {
preventCancel?: boolean;
}
/**
- * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data.
+ * The **`CompressionStream`** interface of the Compression Streams API compresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream)
*/
@@ -2632,7 +2637,7 @@ declare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBuffe
constructor(format: "gzip" | "deflate" | "deflate-raw");
}
/**
- * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data.
+ * The **`DecompressionStream`** interface of the Compression Streams API decompresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream)
*/
@@ -2640,7 +2645,7 @@ declare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBuf
constructor(format: "gzip" | "deflate" | "deflate-raw");
}
/**
- * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding.
+ * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. It is the streaming equivalent of TextEncoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream)
*/
@@ -2649,7 +2654,7 @@ declare class TextEncoderStream extends TransformStream<string, Uint8Array> {
get encoding(): string;
}
/**
- * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings.
+ * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. It is the streaming equivalent of TextDecoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream)
*/
@@ -2798,6 +2803,12 @@ interface TraceLog {
readonly timestamp: number;
readonly level: string;
readonly message: any;
+ readonly errorInfo?: (TraceLogErrorInfo | null)[];
+}
+interface TraceLogErrorInfo {
+ name: string;
+ message: string;
+ stack?: string;
}
interface TraceException {
readonly timestamp: number;
@@ -2818,7 +2829,7 @@ interface UnsafeTraceMetrics {
fromTrace(item: TraceItem): TraceMetrics;
}
/**
- * The **`URL`** interface is used to parse, construct, normalize, and encode URL.
+ * The **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)
*/
@@ -2843,121 +2854,121 @@ declare class URL {
*/
set href(value: string);
/**
- * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`.
+ * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
*/
get protocol(): string;
/**
- * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`.
+ * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
*/
set protocol(value: string);
/**
- * The **`username`** property of the URL interface is a string containing the username component of the URL.
+ * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
*/
get username(): string;
/**
- * The **`username`** property of the URL interface is a string containing the username component of the URL.
+ * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
*/
set username(value: string);
/**
- * The **`password`** property of the URL interface is a string containing the password component of the URL.
+ * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
*/
get password(): string;
/**
- * The **`password`** property of the URL interface is a string containing the password component of the URL.
+ * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
*/
set password(value: string);
/**
- * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL.
+ * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
*/
get host(): string;
/**
- * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL.
+ * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
*/
set host(value: string);
/**
- * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL.
+ * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
*/
get hostname(): string;
/**
- * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL.
+ * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
*/
set hostname(value: string);
/**
- * The **`port`** property of the URL interface is a string containing the port number of the URL.
+ * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
*/
get port(): string;
/**
- * The **`port`** property of the URL interface is a string containing the port number of the URL.
+ * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
*/
set port(value: string);
/**
- * The **`pathname`** property of the URL interface represents a location in a hierarchical structure.
+ * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
*/
get pathname(): string;
/**
- * The **`pathname`** property of the URL interface represents a location in a hierarchical structure.
+ * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
*/
set pathname(value: string);
/**
- * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL.
+ * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
*/
get search(): string;
/**
- * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL.
+ * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
*/
set search(value: string);
/**
- * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL.
+ * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
*/
get hash(): string;
/**
- * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL.
+ * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
*/
set hash(value: string);
/**
- * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL.
+ * The **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)
*/
get searchParams(): URLSearchParams;
/**
- * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None.
+ * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as URL.toString().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON)
*/
@@ -2977,13 +2988,13 @@ declare class URL {
*/
static parse(url: string, base?: string): URL | null;
/**
- * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter.
+ * The **`createObjectURL()`** static method of the URL interface creates a string containing a blob URL pointing to the object given in the parameter.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)
*/
static createObjectURL(object: File | Blob): string;
/**
- * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer.
+ * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling URL.createObjectURL().
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)
*/
@@ -3033,25 +3044,22 @@ declare class URLSearchParams {
*/
has(name: string, value?: string): boolean;
/**
- * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value.
+ * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)
*/
set(name: string, value: string): void;
/**
- * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`.
+ * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns undefined. Key/value pairs are sorted by the values of the UTF-16 code units of the keys. This method uses a stable sorting algorithm (i.e., the relative order between key/value pairs with equal keys will be preserved).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort)
*/
sort(): void;
- /* Returns an array of key, value pairs for every entry in the search params. */
entries(): IterableIterator<[
key: string,
value: string
]>;
- /* Returns a list of keys in the search params. */
keys(): IterableIterator<string>;
- /* Returns a list of values in the search params. */
values(): IterableIterator<string>;
forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;
/*function toString() { [native code] }*/
@@ -3061,18 +3069,78 @@ declare class URLSearchParams {
value: string
]>;
}
+/**
+ * The **`URLPattern`** interface of the URL Pattern API matches URLs or parts of URLs against a pattern. The pattern can contain capturing groups that extract parts of the matched URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern)
+ */
declare class URLPattern {
constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions);
+ /**
+ * The **`protocol`** read-only property of the URLPattern interface is a string containing the pattern used to match the protocol part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/protocol)
+ */
get protocol(): string;
+ /**
+ * The **`username`** read-only property of the URLPattern interface is a string containing the pattern used to match the username part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/username)
+ */
get username(): string;
+ /**
+ * The **`password`** read-only property of the URLPattern interface is a string containing the pattern used to match the password part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/password)
+ */
get password(): string;
+ /**
+ * The **`hostname`** read-only property of the URLPattern interface is a string containing the pattern used to match the hostname part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hostname)
+ */
get hostname(): string;
+ /**
+ * The **`port`** read-only property of the URLPattern interface is a string containing the pattern used to match the port part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/port)
+ */
get port(): string;
+ /**
+ * The **`pathname`** read-only property of the URLPattern interface is a string containing the pattern used to match the pathname part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/pathname)
+ */
get pathname(): string;
+ /**
+ * The **`search`** read-only property of the URLPattern interface is a string containing the pattern used to match the search part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/search)
+ */
get search(): string;
+ /**
+ * The **`hash`** read-only property of the URLPattern interface is a string containing the pattern used to match the fragment part of a URL.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hash)
+ */
get hash(): string;
+ /**
+ * The **`hasRegExpGroups`** read-only property of the URLPattern interface is a boolean indicating whether or not any of the URLPattern components contain regular expression capturing groups.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hasRegExpGroups)
+ */
get hasRegExpGroups(): boolean;
+ /**
+ * The **`test()`** method of the URLPattern interface takes a URL string or object of URL parts, and returns a boolean indicating if the given input matches the current pattern.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/test)
+ */
test(input?: (string | URLPatternInit), baseURL?: string): boolean;
+ /**
+ * The **`exec()`** method of the URLPattern interface takes a URL or object of URL parts, and returns either an object containing the results of matching the URL to the pattern, or null if the URL does not match the pattern.
+ *
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/exec)
+ */
exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null;
}
interface URLPatternInit {
@@ -3105,7 +3173,7 @@ interface URLPatternOptions {
ignoreCase?: boolean;
}
/**
- * A `CloseEvent` is sent to clients using WebSockets when the connection is closed.
+ * A **`CloseEvent`** is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)
*/
@@ -3124,7 +3192,7 @@ declare class CloseEvent extends Event {
*/
readonly reason: string;
/**
- * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly.
+ * The **`wasClean`** read-only property of the CloseEvent interface returns true if the connection closed cleanly.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)
*/
@@ -3142,7 +3210,7 @@ type WebSocketEventMap = {
error: ErrorEvent;
};
/**
- * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
+ * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
*/
@@ -3159,20 +3227,20 @@ declare var WebSocket: {
readonly CLOSED: number;
};
/**
- * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
+ * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
*/
interface WebSocket extends EventTarget<WebSocketEventMap> {
accept(options?: WebSocketAcceptOptions): void;
/**
- * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data.
+ * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data. If the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically. The browser will throw an exception if you call send() when the connection is in the CONNECTING state. If you call send() when the connection is in the CLOSING or CLOSED states, the browser will silently discard the data.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)
*/
send(message: (ArrayBuffer | ArrayBufferView) | string): void;
/**
- * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing.
+ * The **`WebSocket.close()`** method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)
*/
@@ -3192,13 +3260,13 @@ interface WebSocket extends EventTarget<WebSocketEventMap> {
*/
url: string | null;
/**
- * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established.
+ * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object, or the empty string if no connection is established.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)
*/
protocol: string | null;
/**
- * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server.
+ * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)
*/
@@ -3285,25 +3353,25 @@ interface SocketInfo {
declare class EventSource extends EventTarget {
constructor(url: string, init?: EventSourceEventSourceInit);
/**
- * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None.
+ * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
*/
close(): void;
/**
- * The **`url`** read-only property of the URL of the source.
+ * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
*/
get url(): string;
/**
- * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set.
+ * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
*/
get withCredentials(): boolean;
/**
- * The **`readyState`** read-only property of the connection.
+ * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
*/
@@ -3338,18 +3406,26 @@ interface ContainerExecOptions {
cwd?: string;
env?: Record<string, string>;
user?: string;
+ signal?: AbortSignal;
+ pty?: boolean | ContainerExecPtyOptions;
stdin?: ReadableStream | "pipe";
stdout?: "pipe" | "ignore";
stderr?: "pipe" | "ignore" | "combined";
}
+interface ContainerExecPtyOptions {
+ cols?: number;
+ rows?: number;
+}
interface ExecProcess {
readonly stdin: WritableStream | null;
readonly stdout: ReadableStream | null;
readonly stderr: ReadableStream | null;
readonly pid: number;
+ readonly isPty: boolean;
readonly exitCode: Promise<number>;
output(): Promise<ExecOutput>;
kill(signal?: number): void;
+ resize(cols: number, rows: number): void;
}
interface Container {
get running(): boolean;
@@ -3385,16 +3461,30 @@ interface ContainerSnapshot {
size: number;
name?: string;
}
+interface ContainerSnapshotRestoreParams {
+ id: string;
+}
interface ContainerSnapshotOptions {
name?: string;
}
-interface ContainerStartupOptions {
+type ContainerStartupOptions = {
entrypoint?: string[];
enableInternet: boolean;
env?: Record<string, string>;
+ instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;
labels?: Record<string, string>;
directorySnapshots?: ContainerDirectorySnapshotRestoreParams[];
- containerSnapshot?: ContainerSnapshot;
+} & ({
+ image: string;
+ containerSnapshot?: never;
+} | {
+ image?: never;
+ containerSnapshot?: ContainerSnapshotRestoreParams;
+});
+interface ContainerStartResources {
+ vcpu: number;
+ memoryMib: number;
+ diskMb: number;
}
/**
* The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.
@@ -3403,19 +3493,19 @@ interface ContainerStartupOptions {
*/
declare abstract class MessagePort extends EventTarget {
/**
- * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts.
+ * The **`postMessage()`** method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage)
*/
postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void;
/**
- * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active.
+ * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close)
*/
close(): void;
/**
- * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port.
+ * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using onmessage.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start)
*/
@@ -3431,13 +3521,13 @@ declare abstract class MessagePort extends EventTarget {
declare class MessageChannel {
constructor();
/**
- * The **`port1`** read-only property of the the port attached to the context that originated the channel.
+ * The **`port1`** read-only property of the MessageChannel interface returns the first port of the message channel — the port attached to the context that originated the channel.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1)
*/
readonly port1: MessagePort;
/**
- * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to.
+ * The **`port2`** read-only property of the MessageChannel interface returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2)
*/
@@ -3527,7 +3617,7 @@ declare abstract class Performance {
/* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */
now(): number;
/**
- * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object.
+ * The **`toJSON()`** method of the Performance interface is a serializer; it returns a JSON representation of the Performance object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON)
*/
@@ -3536,11 +3626,13 @@ declare abstract class Performance {
interface Tracing {
enterSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
startActiveSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
+ startSpan(name: string): Span;
Span: typeof Span;
}
declare abstract class Span {
get isTraced(): boolean;
- setAttribute(key: string, value?: (boolean | number | string)): void;
+ setAttribute(key: string, value: boolean | number | string): this;
+ setAttributes(attributes: Record<string, boolean | number | string | undefined>): this;
end(): void;
}
/**
@@ -4180,6 +4272,13 @@ type AiSearchListItemsParams = {
source?: string;
/** JSON-encoded Vectorize filter for metadata filtering. */
metadata_filter?: string;
+ /** Filter items by their unique ID. Returns at most one item. */
+ item_id?: string;
+ /**
+ * Filter items by their exact key (object key / filename). Keys are unique
+ * per source, so combine with `source` to disambiguate across data sources.
+ */
+ key?: string;
};
type AiSearchListItemsResponse = {
result: AiSearchItemInfo[];
@@ -10918,10 +11017,29 @@ type BrowserRunLinksOptions = BrowserRunCommonOptions & {
/** When true, exclude links pointing to external domains. @default false */
excludeExternalLinks?: boolean;
};
+type BrowserRunSnapshotFormat = 'content' | 'screenshot' | 'markdown' | 'accessibilityTree';
type BrowserRunSnapshotOptions = BrowserRunCommonOptions & {
+ /** Which representations of the page to return. At least two distinct formats
+ * are required; request a single format from its dedicated action instead.
+ * @default ["content","screenshot"]
+ */
+ formats?: BrowserRunSnapshotFormat[];
/** @see https://pptr.dev/api/puppeteer.screenshotoptions */
screenshotOptions?: Omit<BrowserRunPuppeteerScreenshotOptions, 'encoding'>;
};
+/** Options for the `accessibilityTree` quick action. */
+type BrowserRunAccessibilityTreeOptions = BrowserRunCommonOptions & {
+ /** When true, prune nodes that carry no semantic meaning, such as generic
+ * containers. Defaults to true, or to false when `root` is set so that the
+ * requested subtree is returned as-is.
+ */
+ interestingOnly?: boolean;
+ /** CSS selector limiting the tree to the matching element's subtree.
+ * A selector that matches nothing yields `accessibilityTree: null` with
+ * HTTP 200; a malformed selector is an error.
+ */
+ root?: string;
+};
interface BrowserRunJsonBaseOptions {
/** Custom AI models to try in order. Max 3. Falls back to next on error. */
custom_ai?: Array<{
@@ -10954,6 +11072,58 @@ type BrowserRunResponseMeta = {
/** Page title */
title: string;
};
+/**
+ * A node in the page's accessibility tree, as exposed to assistive technology.
+ * `role` is the only field always present; the rest are populated when the
+ * underlying element defines them.
+ * @see https://pptr.dev/api/puppeteer.serializedaxnode
+ */
+interface BrowserRunSerializedAXNode {
+ /** The ARIA role, e.g. `"button"`, `"heading"`, `"RootWebArea"`. */
+ role: string;
+ /** The `aria-autocomplete` value. */
+ autocomplete?: string;
+ /** Checked state of a checkbox, radio, or menu item. */
+ checked?: boolean | 'mixed';
+ /** Accessible description, typically from `aria-describedby` or `title`. */
+ description?: string;
+ disabled?: boolean;
+ expanded?: boolean;
+ /** Whether the element currently holds keyboard focus. */
+ focused?: boolean;
+ /** The kind of popup the element triggers, e.g. `"menu"`, `"dialog"`. */
+ haspopup?: string;
+ /** The `aria-invalid` value. */
+ invalid?: string;
+ /** Keyboard shortcuts bound to the element, from `aria-keyshortcuts`. */
+ keyshortcuts?: string;
+ /** Hierarchical level, e.g. the heading level of an `<h2>`. */
+ level?: number;
+ /** Whether the element is a modal dialog. */
+ modal?: boolean;
+ /** Whether a text input accepts multiple lines. */
+ multiline?: boolean;
+ /** Whether more than one option can be selected. */
+ multiselectable?: boolean;
+ /** Accessible name, e.g. a button's label or an image's alt text. */
+ name?: string;
+ orientation?: string;
+ /** Pressed state of a toggle button. */
+ pressed?: boolean | 'mixed';
+ readonly?: boolean;
+ required?: boolean;
+ /** Author-supplied role description, from `aria-roledescription`. */
+ roledescription?: string;
+ selected?: boolean;
+ /** Current value of an input or range element. */
+ value?: string | number;
+ valuemax?: number;
+ valuemin?: number;
+ /** Human-readable form of `value`, from `aria-valuetext`. */
+ valuetext?: string;
+ /** Child nodes. Absent for leaf nodes. */
+ children?: BrowserRunSerializedAXNode[];
+}
/** Success response for `content` action. */
type BrowserRunContentSuccessResponse = {
success: true;
@@ -10997,14 +11167,31 @@ type BrowserRunScrapeSuccessResponse = {
}>;
}>;
};
-/** Success response for `snapshot` action. */
+/** Success response for `snapshot` action. Each field is present only when the
+ * corresponding entry was requested in `formats`.
+ */
type BrowserRunSnapshotSuccessResponse = {
success: true;
result: {
/** HTML content of the page. */
- content: string;
+ content?: string;
/** Base64-encoded screenshot image. */
- screenshot: string;
+ screenshot?: string;
+ /** Markdown content. Prefixed with YAML frontmatter (e.g. `title`) when the
+ * page provides that metadata.
+ */
+ markdown?: string;
+ /** Root of the page's accessibility tree. */
+ accessibilityTree?: BrowserRunSerializedAXNode;
+ };
+ meta: BrowserRunResponseMeta;
+};
+/** Success response for `accessibilityTree` action. */
+type BrowserRunAccessibilityTreeSuccessResponse = {
+ success: true;
+ result: {
+ /** Root of the accessibility tree, or `null` when `root` matched no element. */
+ accessibilityTree: BrowserRunSerializedAXNode | null;
};
meta: BrowserRunResponseMeta;
};
@@ -11128,9 +11315,10 @@ declare abstract class BrowserRun {
*/
quickAction(action: 'links', options: BrowserRunLinksOptions): Promise<Response>;
/**
- * Get both the HTML content and a base64-encoded screenshot of a web page.
+ * Get several representations of a web page in one request.
* @param action - Must be `'snapshot'`.
- * @param options - Snapshot options including screenshot settings (encoding is always base64).
+ * @param options - Snapshot options including the `formats` to return and
+ * screenshot settings (encoding is always base64).
* @returns A `Response` containing one of:
*
* **Success (HTTP 200):**
@@ -11178,6 +11366,26 @@ declare abstract class BrowserRun {
* - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
*/
quickAction(action: 'markdown', options: BrowserRunMarkdownOptions): Promise<Response>;
+ /**
+ * Get the accessibility tree of a web page.
+ * @param action - Must be `'accessibilityTree'`.
+ * @param options - Options to scope the tree to a subtree and to control
+ * whether semantically uninteresting nodes are pruned.
+ * @returns A `Response` containing one of:
+ *
+ * **Success (HTTP 200):**
+ * - `BrowserRunAccessibilityTreeSuccessResponse` JSON with `Content-Type: application/json`
+ * - `result.accessibilityTree` is `null` when `root` matched no element
+ *
+ * **Error:**
+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
+ * - HTTP 422 for a malformed `root` selector
+ * - HTTP 500 with code `2017` or `2018` when the tree could not be built
+ *
+ * **Headers:**
+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
+ */
+ quickAction(action: 'accessibilityTree', options: BrowserRunAccessibilityTreeOptions): Promise<Response>;
}
/**
* In addition to the properties you can set in the RequestInit dict
@@ -12468,6 +12676,15 @@ interface Hyperdrive {
* for your database.
*/
readonly host: string;
+ /*
+ * A synthetic IPv4 address (in the reserved 240.0.0.0/4 range) that, like the
+ * host field, is only valid within the context of the currently running
+ * Worker and, when passed into the `connect()` function from the
+ * "cloudflare:sockets" module, will connect to the Hyperdrive instance for
+ * your database. This is provided for database drivers that require the host
+ * to be an IP literal rather than a hostname.
+ */
+ readonly ip: string;
/*
* The port that must be paired the the host field when connecting.
*/
@@ -12500,6 +12717,27 @@ type ImageInfoResponse = {
width: number;
height: number;
};
+/**
+ * Parameters for rasterizing text into an image.
+ */
+type TextRasterize = {
+ /** The text content to render */
+ content: string;
+ /** rasterization options for the text **/
+ options: TextOptions;
+};
+type TextOptions = {
+ /** Font configuration */
+ font: {
+ /** URL to a font file in TrueType (.ttf), OpenType (.otf), WOFF (.woff), or WOFF2 (.woff2) format */
+ url: string;
+ };
+ /** Font size in points (pt) */
+ size?: number;
+ /** Text color in CSS format: hex (#RRGGBB or #RRGGBBAA), rgb(r,g,b), rgba(r,g,b,a), or named colors */
+ color?: string;
+};
+type ImageSource = ReadableStream<Uint8Array> | TextRasterize;
type ImageTransform = {
width?: number;
height?: number;
@@ -12589,6 +12827,9 @@ interface ImageUploadOptions {
requireSignedURLs?: boolean;
metadata?: Record<string, unknown>;
creator?: string;
+ /**
+ * If 'base64', the input data will be decoded from base64 before processing
+ */
encoding?: 'base64';
}
interface ImageUpdateOptions {
@@ -12596,11 +12837,40 @@ interface ImageUpdateOptions {
metadata?: Record<string, unknown>;
creator?: string;
}
+type ImageMetadataFilterOperators = {
+ eq?: string | number | boolean;
+ in?: string[] | number[];
+ gt?: number;
+ gte?: number;
+ lt?: number;
+ lte?: number;
+};
+type ImageMetadataFilterValue = string | number | boolean | ImageMetadataFilterOperators;
+interface ImageListFilter {
+ metadata?: Record<string, ImageMetadataFilterValue>;
+}
interface ImageListOptions {
limit?: number;
cursor?: string;
sortOrder?: 'asc' | 'desc';
creator?: string;
+ filter?: ImageListFilter;
+}
+interface ImageSignedUrlOptions {
+ variant: string;
+ expiresIn?: number;
+ keyName?: string;
+}
+interface ImageDirectUploadOptions {
+ id?: string;
+ requireSignedURLs?: boolean;
+ metadata?: Record<string, unknown>;
+ creator?: string;
+ expiresIn?: number;
+}
+interface ImageDirectUploadResult {
+ id: string;
+ uploadURL: string;
}
interface ImageList {
images: ImageMetadata[];
@@ -12618,6 +12888,13 @@ interface ImageHandle {
* @returns ReadableStream of image bytes, or null if not found
*/
bytes(): Promise<ReadableStream<Uint8Array> | null>;
+ /**
+ * Generate a signed delivery URL for this hosted image.
+ * @param options Signing configuration
+ * @returns A signed image delivery URL
+ * @throws {@link ImagesError} if signing fails
+ */
+ signedUrl(options: ImageSignedUrlOptions): Promise<string>;
/**
* Update hosted image metadata
* @param options Properties to update
@@ -12653,6 +12930,14 @@ interface HostedImagesBinding {
* @throws {@link ImagesError} if list fails
*/
list(options?: ImageListOptions): Promise<ImageList>;
+ /**
+ * Create a Direct Creator Upload link, letting an end user upload an
+ * image straight to Cloudflare without exposing an API token
+ * @param options Upload link configuration
+ * @returns The new image ID and the upload URL to hand to the end user
+ * @throws {@link ImagesError} if creation fails
+ */
+ createDirectUpload(options?: ImageDirectUploadOptions): Promise<ImageDirectUploadResult>;
}
interface ImagesBinding {
/**
@@ -12667,6 +12952,13 @@ interface ImagesBinding {
* @returns A transform handle
*/
input(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): ImageTransformer;
+ /**
+ * Begin applying a series of transformations to text
+ * @param content string to be rendered
+ * @param options font, optional color and size to use in rendering text
+ * @returns A transform handle
+ */
+ text(content: string, options: TextOptions): ImageTransformer;
/**
* Access hosted images CRUD operations
*/
@@ -12696,11 +12988,15 @@ interface ImageTransformer {
type ImageTransformationOutputOptions = {
encoding?: 'base64';
};
+type ImageTransformationResponseOptions = {
+ headers?: HeadersInit;
+};
interface ImageTransformationResult {
/**
* The image as a response, ready to store in cache or return to users
+ * @param options Options that apply to the returned response, e.g. additional headers
*/
- response(): Response;
+ response(options?: ImageTransformationResponseOptions): Response;
/**
* The content type of the returned image
*/
@@ -13154,6 +13450,26 @@ declare namespace CloudflareWorkersModule {
timeout?: WorkflowTimeoutDuration | number;
sensitive?: WorkflowStepSensitivity;
};
+ // Internal discriminators used only for `WorkflowStep.do` overload
+ // resolution. They mirror `WorkflowStepConfig` but pin `retries.delay` to a
+ // single kind so the callback context can be narrowed based on the shape of
+ // the config argument (rather than on an inferred type parameter, which is
+ // lost when the caller supplies an explicit return-type argument). Not
+ // exported: they must not widen the public type surface.
+ type WorkflowStepConfigWithStaticDelay = Omit<WorkflowStepConfig, 'retries'> & {
+ retries?: {
+ limit: number;
+ delay: WorkflowDelayDuration | number;
+ backoff?: WorkflowBackoff;
+ };
+ };
+ type WorkflowStepConfigWithDelayFunction = Omit<WorkflowStepConfig, 'retries'> & {
+ retries: {
+ limit: number;
+ delay: WorkflowDelayFunction;
+ backoff?: WorkflowBackoff;
+ };
+ };
export type WorkflowStepRollbackConfig = Pick<WorkflowStepConfig, 'retries' | 'timeout'>;
export type WorkflowCronSchedule = {
/** Cron expression that triggered this event. */
@@ -13191,23 +13507,35 @@ declare namespace CloudflareWorkersModule {
sensitive?: WorkflowStepSensitivity;
};
};
- export type WorkflowRollbackContext<T = unknown> = {
- ctx: WorkflowStepContext;
+ // The rollback handler receives the step context, so it mirrors the same
+ // delay discriminant as the step callback: when the step was configured with
+ // a dynamic delay function the resolved `config.retries.delay` is omitted,
+ // otherwise it is present. `Delay` is threaded from the `WorkflowStep.do`
+ // overload that matched the step config.
+ export type WorkflowRollbackContext<T = unknown, Delay = WorkflowDelayDuration | number> = {
+ ctx: WorkflowStepContext<Delay>;
error: Error;
output: T | undefined;
/** @deprecated Use `ctx.step.name` and `ctx.step.count` instead. */
stepName: string;
};
- export type WorkflowRollbackHandler<T = unknown> = (ctx: WorkflowRollbackContext<T>) => Promise<void>;
- export type WorkflowStepRollbackOptions<T = unknown> = {
- rollback: WorkflowRollbackHandler<T>;
+ export type WorkflowRollbackHandler<T = unknown, Delay = WorkflowDelayDuration | number> = (ctx: WorkflowRollbackContext<T, Delay>) => Promise<void>;
+ export type WorkflowStepRollbackOptions<T = unknown, Delay = WorkflowDelayDuration | number> = {
+ rollback: WorkflowRollbackHandler<T, Delay>;
rollbackConfig?: WorkflowStepRollbackConfig;
};
export abstract class WorkflowStep {
do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
- do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(name: string, config: C, callback: (ctx: WorkflowStepContext<C['retries'] extends {
- delay: infer D;
- } ? D : WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
+ // The config overloads discriminate on the shape of `config.retries.delay`
+ // so the callback context reflects whether the resolved delay is present
+ // (static delay) or omitted (dynamic delay function). Each has a single
+ // type parameter, so an explicit return-type argument (`do<T>(...)`) still
+ // resolves here. ORDERING IS LOAD-BEARING: the broad `WorkflowStepConfig`
+ // fallback MUST remain last, otherwise it shadows the discriminating
+ // overloads and narrowing is silently lost.
+ do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithDelayFunction, callback: (ctx: WorkflowStepContext<WorkflowDelayFunction>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayFunction>): Promise<T>;
+ do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithStaticDelay, callback: (ctx: WorkflowStepContext<WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayDuration | number>): Promise<T>;
+ do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;
sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;
waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {
@@ -13982,11 +14310,12 @@ type MarkdownDocument = {
name: string;
blob: Blob;
};
+type OutputFormat = 'markdown' | 'text';
type ConversionResponse = {
id: string;
name: string;
mimeType: string;
- format: 'markdown';
+ format: OutputFormat;
tokens: number;
data: string;
} | {
@@ -14003,7 +14332,11 @@ type EmbeddedImageConversionOptions = ImageConversionOptions & {
convert?: boolean;
maxConvertedImages?: number;
};
+type ConversionOutputOptions = {
+ format?: OutputFormat;
+};
type ConversionOptions = {
+ output?: ConversionOutputOptions;
html?: {
images?: EmbeddedImageConversionOptions & {
convertOGImage?: boolean;
@@ -14152,11 +14485,22 @@ declare namespace TailStream {
readonly message: string;
readonly stack?: string;
}
- interface Log {
+ interface TailStreamErrorInfo {
+ readonly name: string;
+ readonly message: string;
+ readonly stack?: string;
+ }
+ type Log = {
readonly type: "log";
readonly level: "debug" | "error" | "info" | "log" | "warn";
+ readonly errorInfo?: readonly (TailStreamErrorInfo | null)[];
+ } & ({
readonly message: object;
- }
+ readonly truncated?: false;
+ } | {
+ readonly message: string;
+ readonly truncated: true;
+ });
interface DroppedEventsDiagnostic {
readonly diagnosticsType: "droppedEvents";
readonly count: number;
@@ -14634,10 +14978,31 @@ declare abstract class Workflow<PARAMS = unknown> {
* @returns A promise that resolves with a list of handles for the created instances.
*/
public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;
+ /**
+ * Delete a batch of Workflow instances and their stored state.
+ * `deleteBatch` is limited to 100 instances at a time. Duplicate IDs are deleted once.
+ * The result contains one entry for each input position; IDs that do not exist are returned as per-instance errors.
+ * @param instanceIds IDs of the Workflow instances to delete
+ * @returns A promise that resolves with the successfully deleted instances and any per-instance errors.
+ */
+ public deleteBatch(instanceIds: string[]): Promise<WorkflowBatchDeleteResult>;
}
+type WorkflowBatchDeleteResult = {
+ deleted: {
+ id: string;
+ }[];
+ errors: {
+ id: string;
+ code: number;
+ message: string;
+ }[];
+};
type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
type WorkflowRetentionDuration = WorkflowSleepDuration;
+/** Geographic regions supported when creating a Workflow instance.
+ * Location hints are best-effort placement preferences. */
+type WorkflowInstanceLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me';
interface WorkflowInstanceCreateOptions<PARAMS = unknown> {
/**
* An id for your Workflow instance. Must be unique within the Workflow.
@@ -14655,6 +15020,9 @@ interface WorkflowInstanceCreateOptions<PARAMS = unknown> {
successRetention?: WorkflowRetentionDuration;
errorRetention?: WorkflowRetentionDuration;
};
+ /** A best-effort geographic placement preference for the Workflow instance.
+ * See `WorkflowInstanceLocationHint` for supported regions. */
+ locationHint?: WorkflowInstanceLocationHint;
}
type InstanceStatus = {
status: 'queued' // means that instance is waiting to be started (see concurrency limits)
@@ -14721,6 +15089,10 @@ declare abstract class WorkflowInstance {
* @param options Options for the restart, including an optional step to restart from.
*/
public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;
+ /**
+ * Delete the instance and its stored state.
+ */
+ public delete(): Promise<void>;
/**
* Returns the current status of the instance.
*/
diff --git a/src/web/package.json b/src/web/package.json
index 3f7ab4b7b..200beea10 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -7,10 +7,11 @@
"build": "tsx scripts/validate-blog-assets.ts && next build",
"validate:blog": "tsx scripts/validate-blog-assets.ts",
"preflight:bug-reports": "tsx scripts/preflight-bug-reports.ts",
+ "preflight:link-preview-thumbnails": "tsx scripts/preflight-link-preview-thumbnails.ts",
"start": "next start",
"lint": "eslint src/",
- "deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
- "upload": "opennextjs-cloudflare build && opennextjs-cloudflare upload",
+ "deploy": "pnpm preflight:link-preview-thumbnails && opennextjs-cloudflare build && opennextjs-cloudflare deploy",
+ "upload": "pnpm preflight:link-preview-thumbnails && opennextjs-cloudflare build && opennextjs-cloudflare upload",
"preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
"cf-typegen": "wrangler types --env-interface CloudflareEnv ./cloudflare-env.d.ts",
"test": "vitest run --config vitest.workspace.config.ts",
@@ -72,6 +73,7 @@
"idb-keyval": "^6.3.0",
"input-otp": "^1.4.2",
"katex": "^0.18.4",
+ "link-preview-js": "5.0.0",
"lucide-react": "^1.31.0",
"mdast-util-find-and-replace": "^3.0.2",
"mdast-util-from-markdown": "^2.0.3",
diff --git a/src/web/scripts/preflight-link-preview-thumbnails.test.ts b/src/web/scripts/preflight-link-preview-thumbnails.test.ts
new file mode 100644
index 000000000..ea18e3d8a
--- /dev/null
+++ b/src/web/scripts/preflight-link-preview-thumbnails.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it, vi } from "vitest"
+import { verifyLinkPreviewThumbnailLifecycle } from "./preflight-link-preview-thumbnails"
+
+const ACCOUNT = "0123456789abcdef0123456789abcdef"
+const BUCKET = "alook-community-media"
+const TOKEN = "CF_PRIVATE_PREFLIGHT_TOKEN"
+const URL = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}/r2/buckets/${BUCKET}/lifecycle`
+
+function lifecycleRule(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "delete-link-preview-thumbnails-after-seven-days",
+ enabled: true,
+ conditions: { prefix: "link-preview-thumbnails/v1/" },
+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_800 } },
+ ...overrides,
+ }
+}
+
+describe("link-preview thumbnail R2 lifecycle preflight", () => {
+ it("passes one exact seven-day prefix rule without mutating Cloudflare", async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(Response.json({
+ success: true,
+ result: { rules: [lifecycleRule(), { enabled: true, conditions: { prefix: "other/" } }] },
+ }))
+
+ await expect(verifyLinkPreviewThumbnailLifecycle({
+ accountId: ACCOUNT,
+ bucketName: BUCKET,
+ apiToken: TOKEN,
+ fetchImpl,
+ })).resolves.toEqual({ ok: true, sevenDayLifecycle: true })
+ expect(fetchImpl).toHaveBeenCalledWith(URL, {
+ method: "GET",
+ headers: { authorization: `Bearer ${TOKEN}` },
+ })
+ })
+
+ it.each([
+ ["missing", []],
+ ["disabled", [lifecycleRule({ enabled: false })]],
+ ["wrong prefix", [lifecycleRule({ conditions: { prefix: "link-preview-thumbnails/" } })]],
+ ["wrong age", [lifecycleRule({ deleteObjectsTransition: { condition: { type: "Age", maxAge: 604_801 } } })]],
+ ["duplicate", [lifecycleRule(), lifecycleRule()]],
+ ])("fails closed when the required lifecycle is %s", async (_label, rules) => {
+ const fetchImpl = vi.fn().mockResolvedValue(Response.json({ success: true, result: { rules } }))
+ await expect(verifyLinkPreviewThumbnailLifecycle({
+ accountId: ACCOUNT,
+ bucketName: BUCKET,
+ apiToken: TOKEN,
+ fetchImpl,
+ })).resolves.toEqual({ ok: false, sevenDayLifecycle: false })
+ })
+
+ it("rejects unsafe inputs and transport failures without leaking credentials", async () => {
+ const fetchImpl = vi.fn()
+ await expect(verifyLinkPreviewThumbnailLifecycle({
+ accountId: "../account",
+ bucketName: BUCKET,
+ apiToken: TOKEN,
+ fetchImpl,
+ })).resolves.toMatchObject({ ok: false })
+ expect(fetchImpl).not.toHaveBeenCalled()
+
+ const logs: string[] = []
+ await expect(verifyLinkPreviewThumbnailLifecycle({
+ accountId: ACCOUNT,
+ bucketName: BUCKET,
+ apiToken: TOKEN,
+ fetchImpl: vi.fn().mockRejectedValue(new Error(TOKEN)),
+ log: (message) => logs.push(message),
+ })).resolves.toMatchObject({ ok: false })
+ expect(JSON.stringify(logs)).not.toContain(TOKEN)
+ })
+})
diff --git a/src/web/scripts/preflight-link-preview-thumbnails.ts b/src/web/scripts/preflight-link-preview-thumbnails.ts
new file mode 100644
index 000000000..32df1163b
--- /dev/null
+++ b/src/web/scripts/preflight-link-preview-thumbnails.ts
@@ -0,0 +1,75 @@
+import { pathToFileURL } from "node:url"
+
+const THUMBNAIL_PREFIX = "link-preview-thumbnails/v1/"
+const SEVEN_DAYS_SECONDS = 7 * 24 * 60 * 60
+
+type CloudflareEnvelope = { success?: unknown; result?: unknown }
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null
+}
+
+export async function verifyLinkPreviewThumbnailLifecycle(args: {
+ accountId: string
+ bucketName: string
+ apiToken: string
+ fetchImpl?: typeof fetch
+ log?: (message: string) => void
+}): Promise<{ ok: boolean; sevenDayLifecycle: boolean }> {
+ const fail = () => ({ ok: false, sevenDayLifecycle: false })
+ if (!/^[0-9a-f]{32}$/.test(args.accountId)
+ || !/^[a-z0-9](?:[a-z0-9.-]{1,61}[a-z0-9])?$/.test(args.bucketName)
+ || args.apiToken.trim().length === 0) {
+ return fail()
+ }
+
+ try {
+ const fetchImpl = args.fetchImpl ?? fetch
+ const url = `https://api.cloudflare.com/client/v4/accounts/${args.accountId}/r2/buckets/${args.bucketName}/lifecycle`
+ const response = await fetchImpl(url, {
+ method: "GET",
+ headers: { authorization: `Bearer ${args.apiToken}` },
+ })
+ if (!response.ok) return fail()
+ const envelope = await response.json() as CloudflareEnvelope
+ const lifecycle = envelope.success === true ? record(envelope.result) : null
+ const rules = Array.isArray(lifecycle?.rules) ? lifecycle.rules : []
+ const matches = rules.filter((value) => {
+ const rule = record(value)
+ const conditions = record(rule?.conditions)
+ const transition = record(rule?.deleteObjectsTransition)
+ const condition = record(transition?.condition)
+ return rule?.enabled === true
+ && conditions?.prefix === THUMBNAIL_PREFIX
+ && condition?.type === "Age"
+ && condition?.maxAge === SEVEN_DAYS_SECONDS
+ })
+ const sevenDayLifecycle = matches.length === 1
+ return { ok: sevenDayLifecycle, sevenDayLifecycle }
+ } catch {
+ args.log?.("link-preview thumbnail R2 preflight failed closed")
+ return fail()
+ }
+}
+
+async function main(): Promise<void> {
+ const result = await verifyLinkPreviewThumbnailLifecycle({
+ accountId: process.env.CLOUDFLARE_ACCOUNT_ID ?? "",
+ bucketName: process.env.COMMUNITY_MEDIA_BUCKET_NAME ?? "alook-community-media",
+ apiToken: process.env.CLOUDFLARE_API_TOKEN ?? "",
+ log: (message) => process.stderr.write(`${message}\n`),
+ })
+ process.stdout.write(`${JSON.stringify(result)}\n`)
+ if (!result.ok) process.exitCode = 1
+}
+
+const invokedPath = process.argv[1]
+if (invokedPath && import.meta.url === pathToFileURL(invokedPath).href) {
+ void main().catch(() => {
+ process.stderr.write("link-preview thumbnail R2 preflight failed closed\n")
+ process.stdout.write(`${JSON.stringify({ ok: false, sevenDayLifecycle: false })}\n`)
+ process.exitCode = 1
+ })
+}
diff --git a/src/web/src/app/api/community/link-preview/route.test.ts b/src/web/src/app/api/community/link-preview/route.test.ts
new file mode 100644
index 000000000..b04140cb8
--- /dev/null
+++ b/src/web/src/app/api/community/link-preview/route.test.ts
@@ -0,0 +1,332 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest, NextResponse } from "next/server"
+
+const mockFetchLinkPreview = vi.fn()
+const mockCheckRateLimit = vi.fn()
+const mockKvGet = vi.fn()
+const mockKvPut = vi.fn()
+const mockR2Put = vi.fn()
+const mockWaitUntil = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ ctx: { waitUntil: mockWaitUntil } })),
+}))
+
+vi.mock("@/lib/community/link-preview-fetch", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/link-preview-fetch")>(
+ "@/lib/community/link-preview-fetch",
+ )
+ return {
+ ...actual,
+ fetchLinkPreview: (...args: unknown[]) => mockFetchLinkPreview(...args),
+ }
+})
+
+vi.mock("@/lib/rate-limit", () => ({
+ checkRateLimit: (...args: unknown[]) => mockCheckRateLimit(...args),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: (...args: any[]) => unknown) => (req: NextRequest) => handler(req, {
+ env: {
+ CACHE_KV: { get: mockKvGet, put: mockKvPut },
+ COMMUNITY_MEDIA: { put: mockR2Put },
+ },
+ userId: "user_1",
+ email: "[email protected]",
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => ({
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number, headers?: HeadersInit) =>
+ NextResponse.json({ error: message }, { status, headers }),
+}))
+
+import { POST } from "./route"
+
+function request(body: unknown): NextRequest {
+ return new NextRequest("http://localhost/api/community/link-preview", {
+ method: "POST",
+ body: JSON.stringify(body),
+ })
+}
+
+function rawRequest(body: BodyInit, headers?: HeadersInit): NextRequest {
+ return new NextRequest("http://localhost/api/community/link-preview", {
+ method: "POST",
+ body,
+ headers,
+ })
+}
+
+describe("POST /api/community/link-preview", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockCheckRateLimit.mockResolvedValue({ allowed: true })
+ mockKvGet.mockResolvedValue(null)
+ mockKvPut.mockResolvedValue(undefined)
+ mockR2Put.mockResolvedValue(undefined)
+ mockFetchLinkPreview.mockResolvedValue({
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Example",
+ })
+ })
+
+ it("rate-limits before rejecting an invalid target", async () => {
+ const response = await POST(request({ url: "http://127.0.0.1/private" }))
+
+ expect(response.status).toBe(400)
+ expect(mockCheckRateLimit).toHaveBeenCalledWith(
+ expect.anything(),
+ "community:linkPreview",
+ "user_1",
+ )
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+
+ it("rejects an oversized declared body after applying the rate limit", async () => {
+ const response = await POST(rawRequest("{}", { "content-length": "4097" }))
+
+ expect(response.status).toBe(413)
+ expect(mockCheckRateLimit).toHaveBeenCalledOnce()
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+
+ it("streams and rejects an oversized body when content-length is absent", async () => {
+ const req = rawRequest("x".repeat(4097), { "content-type": "application/json" })
+ expect(req.headers.get("content-length")).toBeNull()
+
+ const response = await POST(req)
+
+ expect(response.status).toBe(413)
+ expect(mockCheckRateLimit).toHaveBeenCalledOnce()
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+
+ it("rejects malformed JSON only after applying the rate limit", async () => {
+ const response = await POST(rawRequest("{"))
+
+ expect(response.status).toBe(400)
+ expect(mockCheckRateLimit).toHaveBeenCalledOnce()
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+
+ it("rejects a request with no body only after applying the rate limit", async () => {
+ const req = new NextRequest("http://localhost/api/community/link-preview", { method: "POST" })
+
+ const response = await POST(req)
+
+ expect(response.status).toBe(400)
+ expect(mockCheckRateLimit).toHaveBeenCalledOnce()
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+
+ it("returns a valid cached preview without fetching the origin", async () => {
+ mockKvGet.mockResolvedValue(JSON.stringify({
+ preview: { url: "https://example.com/", hostname: "example.com", title: "Cached" },
+ staleTimeSeconds: 21_600,
+ }))
+
+ const response = await POST(request({ url: "https://example.com/#fragment" }))
+ expect(await response.json()).toEqual({
+ preview: { url: "https://example.com/", hostname: "example.com", title: "Cached" },
+ staleTimeSeconds: 21_600,
+ })
+ expect(mockCheckRateLimit).toHaveBeenCalledWith(
+ expect.anything(),
+ "community:linkPreview",
+ "user_1",
+ )
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+
+ it("returns a cached negative preview without fetching the origin", async () => {
+ mockKvGet.mockResolvedValue(JSON.stringify({ preview: null, staleTimeSeconds: 300 }))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect(await response.json()).toEqual({ preview: null, staleTimeSeconds: 300 })
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ expect(mockKvPut).not.toHaveBeenCalled()
+ })
+
+ it("returns a valid degraded cached preview with its exact digest path", async () => {
+ const thumbnailUrl = "/api/community/link-preview/thumbnail/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7"
+ mockKvGet.mockResolvedValue(JSON.stringify({
+ preview: {
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Cached",
+ thumbnailUrl,
+ },
+ staleTimeSeconds: 300,
+ }))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect(await response.json()).toEqual({
+ preview: {
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Cached",
+ thumbnailUrl,
+ },
+ staleTimeSeconds: 300,
+ })
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["an unsupported TTL", "/api/community/link-preview/thumbnail/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7", 123],
+ ["an upstream image URL", "https://images.example.com/og.jpg", 21_600],
+ ["a mismatched digest path", `/api/community/link-preview/thumbnail/${"a".repeat(64)}`, 21_600],
+ ])("treats a cached preview with %s as a miss", async (_label, thumbnailUrl, staleTimeSeconds) => {
+ mockKvGet.mockResolvedValue(JSON.stringify({
+ preview: {
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Unsafe cache entry",
+ thumbnailUrl,
+ },
+ staleTimeSeconds,
+ }))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect((await response.json()).preview.title).toBe("Example")
+ expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
+ })
+
+ it("treats a malformed cache entry as a miss", async () => {
+ mockKvGet.mockResolvedValue("not-json")
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect((await response.json()).preview.title).toBe("Example")
+ expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
+ })
+
+ it("treats a cached primitive preview as a miss", async () => {
+ mockKvGet.mockResolvedValue(JSON.stringify({
+ preview: "not-an-object",
+ staleTimeSeconds: 21_600,
+ }))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect((await response.json()).preview.title).toBe("Example")
+ expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
+ })
+
+ it("degrades a KV read failure to a bounded origin fetch", async () => {
+ mockKvGet.mockRejectedValue(new Error("KV unavailable"))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect((await response.json()).preview.title).toBe("Example")
+ expect(mockFetchLinkPreview).toHaveBeenCalledOnce()
+ })
+
+ it("fetches a cache miss and schedules the sanitized result for KV", async () => {
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect(await response.json()).toMatchObject({ preview: { title: "Example" } })
+ expect(mockFetchLinkPreview).toHaveBeenCalledWith("https://example.com/")
+ expect(mockKvPut).toHaveBeenCalledWith(
+ expect.stringMatching(/^link-preview:v2:[a-f0-9]{64}$/),
+ JSON.stringify({
+ preview: { url: "https://example.com/", hostname: "example.com", title: "Example" },
+ staleTimeSeconds: 21_600,
+ }),
+ { expirationTtl: 21_600 },
+ )
+ expect(mockWaitUntil).toHaveBeenCalledWith(expect.any(Promise))
+ })
+
+ it("negative-caches a bounded origin failure and degrades to no card", async () => {
+ mockFetchLinkPreview.mockRejectedValue(new Error("timeout"))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect(await response.json()).toEqual({ preview: null, staleTimeSeconds: 300 })
+ expect(mockKvPut).toHaveBeenCalledWith(
+ expect.any(String),
+ JSON.stringify({ preview: null, staleTimeSeconds: 300 }),
+ { expirationTtl: 300 },
+ )
+ })
+
+ it("swallows a background KV write failure", async () => {
+ mockKvPut.mockRejectedValue(new Error("KV unavailable"))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+ const backgroundWrite = mockWaitUntil.mock.calls[0]?.[0] as Promise<void>
+
+ expect((await response.json()).preview.title).toBe("Example")
+ await expect(backgroundWrite).resolves.toBeUndefined()
+ })
+
+ it("awaits a private R2 manifest before returning only a same-origin thumbnail path", async () => {
+ mockFetchLinkPreview.mockResolvedValue({
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Example",
+ thumbnailSource: "https://images.example.com/og.png",
+ })
+
+ const response = await POST(request({ url: "https://example.com/" }))
+ const body = await response.json()
+
+ expect(body).toEqual({
+ preview: {
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Example",
+ thumbnailUrl: "/api/community/link-preview/thumbnail/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7",
+ },
+ staleTimeSeconds: 21_600,
+ })
+ expect(JSON.stringify(body)).not.toContain("images.example.com")
+ expect(mockR2Put).toHaveBeenCalledWith(
+ "link-preview-thumbnails/v1/0f115db062b7c0dd030b16878c99dea5c354b49dc37b38eb8846179c7783e9d7/manifest.json",
+ expect.stringContaining('"sourceUrl":"https://images.example.com/og.png"'),
+ expect.objectContaining({ httpMetadata: { contentType: "application/json" } }),
+ )
+ expect(mockR2Put.mock.invocationCallOrder[0]).toBeLessThan(mockKvPut.mock.invocationCallOrder[0]!)
+ })
+
+ it("omits a thumbnail and uses the recovery TTL when the manifest write fails", async () => {
+ mockFetchLinkPreview.mockResolvedValue({
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Example",
+ thumbnailSource: "https://images.example.com/og.png",
+ })
+ mockR2Put.mockRejectedValue(new Error("R2 unavailable"))
+
+ const response = await POST(request({ url: "https://example.com/" }))
+
+ expect(await response.json()).toEqual({
+ preview: { url: "https://example.com/", hostname: "example.com", title: "Example" },
+ staleTimeSeconds: 300,
+ })
+ expect(mockKvPut).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.stringContaining('"staleTimeSeconds":300'),
+ { expirationTtl: 300 },
+ )
+ })
+
+ it("enforces the authenticated preview rate limit", async () => {
+ mockCheckRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 17 })
+
+ const response = await POST(rawRequest("not-json"))
+
+ expect(response.status).toBe(429)
+ expect(response.headers.get("retry-after")).toBe("17")
+ expect(mockKvGet).not.toHaveBeenCalled()
+ expect(mockFetchLinkPreview).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/link-preview/route.ts b/src/web/src/app/api/community/link-preview/route.ts
new file mode 100644
index 000000000..bbc83d7e7
--- /dev/null
+++ b/src/web/src/app/api/community/link-preview/route.ts
@@ -0,0 +1,164 @@
+import { NextRequest } from "next/server"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeError, writeJSON } from "@/lib/middleware/helpers"
+import { checkRateLimit } from "@/lib/rate-limit"
+import { fetchLinkPreview, normalizePublicPreviewUrl } from "@/lib/community/link-preview-fetch"
+import {
+ linkPreviewPageDigest,
+ linkPreviewThumbnailUrl,
+ writeLinkPreviewThumbnailManifest,
+} from "@/lib/community/link-preview-thumbnail"
+import type { LinkPreview } from "@/lib/community/link-preview"
+
+const POSITIVE_TTL_SECONDS = 6 * 60 * 60
+const NEGATIVE_TTL_SECONDS = 5 * 60
+const MAX_REQUEST_BODY_BYTES = 4 * 1024
+
+type CacheEntry = {
+ preview: LinkPreview | null
+ staleTimeSeconds: typeof POSITIVE_TTL_SECONDS | typeof NEGATIVE_TTL_SECONDS
+}
+
+class RequestBodyTooLargeError extends Error {}
+
+async function readBoundedJson(req: NextRequest): Promise<unknown> {
+ const declaredLength = req.headers.get("content-length")
+ if (declaredLength && /^\d+$/.test(declaredLength) && Number(declaredLength) > MAX_REQUEST_BODY_BYTES) {
+ await req.body?.cancel().catch(() => {})
+ throw new RequestBodyTooLargeError("request body too large")
+ }
+ if (!req.body) throw new Error("invalid request body")
+
+ const reader = req.body.getReader()
+ const decoder = new TextDecoder()
+ let body = ""
+ let total = 0
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+ total += value.byteLength
+ if (total > MAX_REQUEST_BODY_BYTES) {
+ await reader.cancel()
+ throw new RequestBodyTooLargeError("request body too large")
+ }
+ body += decoder.decode(value, { stream: true })
+ }
+ } finally {
+ reader.releaseLock()
+ }
+ return JSON.parse(body + decoder.decode())
+}
+
+function isLinkPreview(value: unknown, expectedDigest: string): value is LinkPreview {
+ if (!value || typeof value !== "object") return false
+ const item = value as Record<string, unknown>
+ return typeof item.url === "string"
+ && typeof item.hostname === "string"
+ && typeof item.title === "string"
+ && (item.description === undefined || typeof item.description === "string")
+ && (item.siteName === undefined || typeof item.siteName === "string")
+ && (item.thumbnailUrl === undefined
+ || item.thumbnailUrl === linkPreviewThumbnailUrl(expectedDigest))
+}
+
+function parseCacheEntry(raw: string, expectedDigest: string): CacheEntry | null {
+ try {
+ const value = JSON.parse(raw) as { preview?: unknown; staleTimeSeconds?: unknown }
+ if (value.preview === null && value.staleTimeSeconds === NEGATIVE_TTL_SECONDS) {
+ return { preview: null, staleTimeSeconds: NEGATIVE_TTL_SECONDS }
+ }
+ if (isLinkPreview(value.preview, expectedDigest)
+ && (value.staleTimeSeconds === POSITIVE_TTL_SECONDS
+ || value.staleTimeSeconds === NEGATIVE_TTL_SECONDS)) {
+ return { preview: value.preview, staleTimeSeconds: value.staleTimeSeconds }
+ }
+ } catch {
+ // Treat a stale/malformed cache entry as a miss.
+ }
+ return null
+}
+
+function cacheKey(pageDigest: string): string {
+ return `link-preview:v2:${pageDigest}`
+}
+
+/**
+ * Independent, authenticated URL-unfurl boundary. It is deliberately not part
+ * of message list/send: text paints first, and a slow/failed origin only makes
+ * this optional card disappear.
+ */
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const rateLimit = await checkRateLimit(ctx.env, "community:linkPreview", ctx.userId)
+ if (!rateLimit.allowed) {
+ return writeError("rate limited", 429, { "Retry-After": String(rateLimit.retryAfterSec) })
+ }
+
+ let raw: unknown
+ try {
+ raw = await readBoundedJson(req)
+ } catch (error) {
+ if (error instanceof RequestBodyTooLargeError) return writeError("request body too large", 413)
+ return writeError("invalid request body", 400)
+ }
+ const requestedUrl = typeof (raw as { url?: unknown } | null)?.url === "string"
+ ? (raw as { url: string }).url
+ : ""
+
+ let normalized: string
+ try {
+ normalized = normalizePublicPreviewUrl(requestedUrl).href
+ } catch {
+ return writeError("invalid preview URL", 400)
+ }
+
+ const pageDigest = await linkPreviewPageDigest(normalized)
+ const key = cacheKey(pageDigest)
+ const kv = ctx.env.CACHE_KV ?? null
+ if (kv) {
+ try {
+ const cached = await kv.get(key)
+ if (cached) {
+ const entry = parseCacheEntry(cached, pageDigest)
+ if (entry) return writeJSON(entry)
+ }
+ } catch {
+ // KV is memoization only; a cache outage degrades to the bounded fetch.
+ }
+ }
+
+ let entry: CacheEntry
+ try {
+ const fetched = await fetchLinkPreview(normalized)
+ const { thumbnailSource, ...preview } = fetched
+ let staleTimeSeconds: CacheEntry["staleTimeSeconds"] = POSITIVE_TTL_SECONDS
+ if (thumbnailSource) {
+ try {
+ await writeLinkPreviewThumbnailManifest({
+ bucket: ctx.env.COMMUNITY_MEDIA,
+ pageDigest,
+ sourceUrl: thumbnailSource,
+ })
+ preview.thumbnailUrl = linkPreviewThumbnailUrl(pageDigest)
+ } catch {
+ // A capability is exposed only after its strongly-consistent manifest
+ // exists. Retry this degraded text-only preview after the negative TTL.
+ staleTimeSeconds = NEGATIVE_TTL_SECONDS
+ }
+ }
+ entry = { preview, staleTimeSeconds }
+ } catch {
+ entry = { preview: null, staleTimeSeconds: NEGATIVE_TTL_SECONDS }
+ }
+
+ if (kv) {
+ const write = kv.put(key, JSON.stringify(entry), {
+ expirationTtl: entry.staleTimeSeconds,
+ }).catch(() => {
+ // A cache write failure must never turn a valid message link into an error.
+ })
+ getCloudflareContext().ctx.waitUntil(write)
+ }
+ return writeJSON(entry)
+})
diff --git a/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.test.ts b/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.test.ts
new file mode 100644
index 000000000..1d30b0e21
--- /dev/null
+++ b/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.test.ts
@@ -0,0 +1,348 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const DIGEST = "a".repeat(64)
+const SOURCE = "https://images.example.com/og.jpg"
+let sourceDigest = ""
+const mockR2Get = vi.fn()
+const mockR2Put = vi.fn()
+const mockKvGet = vi.fn()
+const mockKvPut = vi.fn()
+const mockCheckRateLimit = vi.fn()
+const mockWaitUntil = vi.fn()
+const mockImagesInfo = vi.fn()
+const mockImagesInput = vi.fn()
+const mockImagesTransform = vi.fn()
+const mockImagesOutput = vi.fn()
+let includeKv = true
+let includeImages = true
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ ctx: { waitUntil: mockWaitUntil } })),
+}))
+
+vi.mock("@/lib/rate-limit", () => ({
+ checkRateLimit: (...args: unknown[]) => mockCheckRateLimit(...args),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: (...args: any[]) => unknown) => (req: NextRequest, context?: { params?: Record<string, string> }) => {
+ const env: Record<string, unknown> = {
+ COMMUNITY_MEDIA: { get: mockR2Get, put: mockR2Put },
+ }
+ if (includeKv) env.CACHE_KV = { get: mockKvGet, put: mockKvPut }
+ if (includeImages) {
+ env.IMAGES = {
+ info: mockImagesInfo,
+ input: mockImagesInput,
+ }
+ }
+ return handler(req, {
+ env,
+ userId: "user_1",
+ email: "[email protected]",
+ params: context?.params,
+ })
+ },
+}))
+
+import { GET } from "./route"
+
+function stream(bytes: Uint8Array, cancel?: () => void): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(bytes)
+ controller.close()
+ },
+ cancel,
+ })
+}
+
+function manifestObject(overrides: Record<string, unknown> = {}) {
+ const value = JSON.stringify({
+ version: 1,
+ pageDigest: DIGEST,
+ sourceUrl: SOURCE,
+ sourceDigest,
+ expiresAt: Date.now() + 60_000,
+ ...overrides,
+ })
+ return {
+ size: value.length,
+ body: stream(new TextEncoder().encode(value)),
+ text: vi.fn().mockResolvedValue(value),
+ }
+}
+
+function cachedObject(overrides: Record<string, unknown> = {}) {
+ return {
+ size: 3,
+ body: stream(new Uint8Array([4, 5, 6])),
+ httpMetadata: { contentType: "image/webp" },
+ customMetadata: { sourceDigest, expiresAt: String(Date.now() + 60_000) },
+ ...overrides,
+ }
+}
+
+function request(digest = DIGEST, query = ""): Promise<Response> {
+ return GET(
+ new NextRequest(`http://localhost/api/community/link-preview/thumbnail/${digest}${query}`),
+ { params: { digest } },
+ )
+}
+
+describe("GET /api/community/link-preview/thumbnail/[digest]", () => {
+ beforeEach(async () => {
+ vi.clearAllMocks()
+ includeKv = true
+ includeImages = true
+ mockCheckRateLimit.mockResolvedValue({ allowed: true })
+ mockKvGet.mockResolvedValue(null)
+ mockKvPut.mockResolvedValue(undefined)
+ mockR2Put.mockResolvedValue(undefined)
+ mockR2Get.mockImplementation((key: string) => {
+ if (key.endsWith("manifest.json")) return Promise.resolve(manifestObject())
+ return Promise.resolve(null)
+ })
+ mockImagesInfo.mockResolvedValue({ format: "image/jpeg", fileSize: 3, width: 1200, height: 630 })
+ mockImagesTransform.mockReturnThis()
+ mockImagesOutput.mockResolvedValue({
+ contentType: () => "image/webp",
+ image: () => stream(new Uint8Array([7, 8, 9])),
+ })
+ mockImagesInput.mockReturnValue({
+ transform: (...args: unknown[]) => {
+ mockImagesTransform(...args)
+ return { output: (...values: unknown[]) => mockImagesOutput(...values) }
+ },
+ })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), {
+ headers: { "content-type": "image/jpeg" },
+ })))
+
+ // The fixture source digest must exactly match the production SHA-256.
+ const digestBytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(SOURCE))
+ sourceDigest = Array.from(new Uint8Array(digestBytes), (byte) => byte.toString(16).padStart(2, "0")).join("")
+ expect(sourceDigest).toHaveLength(64)
+ mockR2Get.mockImplementation((key: string) => {
+ if (key.endsWith("manifest.json")) return Promise.resolve(manifestObject({ sourceDigest }))
+ return Promise.resolve(null)
+ })
+ })
+
+ it("rejects an invalid digest before R2, rate limiting, or any outbound fetch", async () => {
+ const response = await request("../source")
+
+ expect(response.status).toBe(404)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(mockR2Get).not.toHaveBeenCalled()
+ expect(mockCheckRateLimit).not.toHaveBeenCalled()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["missing", null],
+ ["expired", manifestObject({ expiresAt: 1 })],
+ ["mismatched", manifestObject({ pageDigest: "c".repeat(64) })],
+ ])("returns the same no-store 404 for a %s manifest with zero outbound work", async (_label, object) => {
+ mockR2Get.mockResolvedValueOnce(object)
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(mockCheckRateLimit).not.toHaveBeenCalled()
+ expect(fetch).not.toHaveBeenCalled()
+ expect(mockImagesInfo).not.toHaveBeenCalled()
+ })
+
+ it("returns the same no-store 404 when the manifest read fails", async () => {
+ mockR2Get.mockRejectedValueOnce(new Error("R2 unavailable"))
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(mockCheckRateLimit).not.toHaveBeenCalled()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it("serves a valid R2 WebP hit without rate limiting, network, or Images work", async () => {
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(cachedObject({ customMetadata: { sourceDigest, expiresAt: String(Date.now() + 60_000) } }))
+
+ const response = await request()
+
+ expect(response.status).toBe(200)
+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array([4, 5, 6]))
+ expect(response.headers.get("content-type")).toBe("image/webp")
+ expect(response.headers.get("cache-control")).toBe("private, max-age=21600, immutable")
+ expect(response.headers.get("content-disposition")).toBe("inline")
+ expect(response.headers.get("x-content-type-options")).toBe("nosniff")
+ expect(response.headers.get("cross-origin-resource-policy")).toBe("same-origin")
+ expect(response.headers.get("referrer-policy")).toBe("no-referrer")
+ expect(mockCheckRateLimit).not.toHaveBeenCalled()
+ expect(fetch).not.toHaveBeenCalled()
+ expect(mockImagesInfo).not.toHaveBeenCalled()
+ })
+
+ it("uses a valid manifest source only, ignores query inputs, and stores the fixed transformed WebP", async () => {
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(null)
+
+ const response = await request(DIGEST, "?url=https://127.0.0.1/&width=9999&format=svg")
+
+ expect(response.status).toBe(200)
+ expect(fetch).toHaveBeenCalledWith(SOURCE, expect.objectContaining({ redirect: "manual", credentials: "omit" }))
+ expect(mockCheckRateLimit).toHaveBeenCalledWith(expect.anything(), "community:linkPreviewThumbnail", "user_1")
+ expect(mockImagesTransform).toHaveBeenCalledWith({ width: 640, height: 360, fit: "cover" })
+ expect(mockImagesOutput).toHaveBeenCalledWith({ format: "image/webp", quality: 78, anim: false })
+ expect(mockR2Put).toHaveBeenCalledWith(
+ `link-preview-thumbnails/v1/${DIGEST}/thumbnail.webp`,
+ new Uint8Array([7, 8, 9]),
+ expect.objectContaining({
+ httpMetadata: expect.objectContaining({ contentType: "image/webp" }),
+ customMetadata: expect.objectContaining({ sourceDigest }),
+ }),
+ )
+ expect(JSON.stringify(await response.arrayBuffer())).not.toContain("images.example.com")
+ })
+
+ it("refreshes a stale or source-mismatched object after canceling its body", async () => {
+ const cancel = vi.fn()
+ const stale = cachedObject({
+ body: stream(new Uint8Array([1]), cancel),
+ customMetadata: { sourceDigest: "c".repeat(64), expiresAt: "1" },
+ })
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(stale)
+
+ const response = await request()
+
+ expect(response.status).toBe(200)
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(fetch).toHaveBeenCalledOnce()
+ expect(mockR2Put).toHaveBeenCalledOnce()
+ })
+
+ it("continues after a stale object's body refuses cancellation", async () => {
+ const cancel = vi.fn().mockRejectedValue(new Error("already closed"))
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(cachedObject({
+ body: { cancel },
+ customMetadata: { sourceDigest: "c".repeat(64), expiresAt: "1" },
+ }))
+
+ const response = await request()
+
+ expect(response.status).toBe(200)
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(fetch).toHaveBeenCalledOnce()
+ })
+
+ it("returns the same no-store 404 when the cached-object read fails", async () => {
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockRejectedValueOnce(new Error("R2 unavailable"))
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(mockCheckRateLimit).not.toHaveBeenCalled()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it("honors the five-minute negative cache before rate limiting or outbound work", async () => {
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(null)
+ mockKvGet.mockResolvedValue("1")
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(mockCheckRateLimit).not.toHaveBeenCalled()
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it("rate-limits before cache-miss network and transform work", async () => {
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(null)
+ mockCheckRateLimit.mockResolvedValue({ allowed: false, retryAfterSec: 10 })
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(fetch).not.toHaveBeenCalled()
+ expect(mockImagesInfo).not.toHaveBeenCalled()
+ })
+
+ it("fails closed without optional KV or an Images binding", async () => {
+ includeKv = false
+ includeImages = false
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(null)
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(mockCheckRateLimit).toHaveBeenCalledOnce()
+ expect(fetch).not.toHaveBeenCalled()
+ expect(mockKvGet).not.toHaveBeenCalled()
+ expect(mockKvPut).not.toHaveBeenCalled()
+ expect(mockWaitUntil).not.toHaveBeenCalled()
+ })
+
+ it("treats negative-cache reads and writes as best-effort", async () => {
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(null)
+ mockKvGet.mockRejectedValueOnce(new Error("KV read unavailable"))
+ vi.mocked(fetch).mockRejectedValueOnce(new Error("origin unavailable"))
+ mockKvPut.mockRejectedValueOnce(new Error("KV write unavailable"))
+
+ const response = await request()
+ const backgroundWrite = mockWaitUntil.mock.calls[0]?.[0] as Promise<void>
+
+ expect(response.status).toBe(404)
+ expect(mockCheckRateLimit).toHaveBeenCalledOnce()
+ expect(mockWaitUntil).toHaveBeenCalledOnce()
+ await expect(backgroundWrite).resolves.toBeUndefined()
+ })
+
+ it("folds upstream, transform, and R2 write failures into an image-only 404 and negative cache", async () => {
+ for (const fail of [
+ () => vi.mocked(fetch).mockRejectedValueOnce(new Error("origin unavailable")),
+ () => mockImagesInfo.mockRejectedValueOnce(new Error("decode failed")),
+ () => mockR2Put.mockRejectedValueOnce(new Error("R2 unavailable")),
+ ]) {
+ mockR2Get
+ .mockResolvedValueOnce(manifestObject({ sourceDigest }))
+ .mockResolvedValueOnce(null)
+ fail()
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(mockKvPut).toHaveBeenLastCalledWith(
+ `link-preview-thumbnail-negative:v1:${DIGEST}:${sourceDigest}`,
+ "1",
+ { expirationTtl: 300 },
+ )
+ expect(mockWaitUntil).toHaveBeenLastCalledWith(expect.any(Promise))
+ vi.mocked(fetch).mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), {
+ headers: { "content-type": "image/jpeg" },
+ }))
+ mockImagesInfo.mockResolvedValue({ format: "image/jpeg", fileSize: 3, width: 1200, height: 630 })
+ mockR2Put.mockResolvedValue(undefined)
+ }
+ })
+})
diff --git a/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.ts b/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.ts
new file mode 100644
index 000000000..d453917da
--- /dev/null
+++ b/src/web/src/app/api/community/link-preview/thumbnail/[digest]/route.ts
@@ -0,0 +1,103 @@
+import { NextResponse, type NextRequest } from "next/server"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { withAuth } from "@/lib/middleware/auth"
+import { checkRateLimit } from "@/lib/rate-limit"
+import {
+ fetchAndTransformLinkPreviewThumbnail,
+ isFreshLinkPreviewThumbnailObject,
+ isLinkPreviewThumbnailDigest,
+ linkPreviewThumbnailNegativeKey,
+ linkPreviewThumbnailObjectKey,
+ linkPreviewThumbnailObjectMetadata,
+ readLinkPreviewThumbnailManifest,
+} from "@/lib/community/link-preview-thumbnail"
+
+const NEGATIVE_TTL_SECONDS = 5 * 60
+const PRIVATE_THUMBNAIL_CACHE = "private, max-age=21600, immutable"
+
+function notFound(): NextResponse {
+ return NextResponse.json({ error: "thumbnail not found" }, {
+ status: 404,
+ headers: {
+ "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff",
+ },
+ })
+}
+
+function thumbnailResponse(body: BodyInit): Response {
+ return new Response(body, {
+ headers: {
+ "Content-Type": "image/webp",
+ "Content-Disposition": "inline",
+ "Cache-Control": PRIVATE_THUMBNAIL_CACHE,
+ "X-Content-Type-Options": "nosniff",
+ "Cross-Origin-Resource-Policy": "same-origin",
+ "Referrer-Policy": "no-referrer",
+ },
+ })
+}
+
+export const GET = withAuth(async (_req: NextRequest, ctx) => {
+ const pageDigest = ctx.params?.digest
+ if (!isLinkPreviewThumbnailDigest(pageDigest)) return notFound()
+
+ let manifest
+ try {
+ manifest = await readLinkPreviewThumbnailManifest({
+ bucket: ctx.env.COMMUNITY_MEDIA,
+ pageDigest,
+ })
+ } catch {
+ return notFound()
+ }
+ if (!manifest) return notFound()
+
+ const objectKey = linkPreviewThumbnailObjectKey(pageDigest)
+ try {
+ const cached = await ctx.env.COMMUNITY_MEDIA.get(objectKey)
+ if (cached && isFreshLinkPreviewThumbnailObject(cached, manifest)) {
+ return thumbnailResponse(cached.body)
+ }
+ await cached?.body.cancel().catch(() => {})
+ } catch {
+ return notFound()
+ }
+
+ const kv = ctx.env.CACHE_KV ?? null
+ const negativeKey = linkPreviewThumbnailNegativeKey(pageDigest, manifest.sourceDigest)
+ if (kv) {
+ try {
+ if (await kv.get(negativeKey)) return notFound()
+ } catch {
+ // Negative caching is best-effort; all expensive work remains bounded.
+ }
+ }
+
+ const rateLimit = await checkRateLimit(ctx.env, "community:linkPreviewThumbnail", ctx.userId)
+ if (!rateLimit.allowed) return notFound()
+
+ try {
+ const images = ctx.env.IMAGES
+ if (!images) throw new Error("Images binding unavailable")
+ const bytes = await fetchAndTransformLinkPreviewThumbnail(manifest.sourceUrl, images)
+ await ctx.env.COMMUNITY_MEDIA.put(
+ objectKey,
+ bytes,
+ linkPreviewThumbnailObjectMetadata(manifest),
+ )
+ return thumbnailResponse(bytes.slice().buffer as ArrayBuffer)
+ } catch {
+ if (kv) {
+ const write = kv.put(negativeKey, "1", { expirationTtl: NEGATIVE_TTL_SECONDS }).catch(() => {
+ // A negative-cache outage must not turn an image-only miss into a 500.
+ })
+ getCloudflareContext().ctx.waitUntil(write)
+ }
+ return notFound()
+ }
+})
+
+export const LINK_PREVIEW_THUMBNAIL_RESPONSE_HEADERS = {
+ cacheControl: PRIVATE_THUMBNAIL_CACHE,
+} as const
diff --git a/src/web/src/components/community/messages/link-preview-card.test.ts b/src/web/src/components/community/messages/link-preview-card.test.ts
new file mode 100644
index 000000000..a1290fe35
--- /dev/null
+++ b/src/web/src/components/community/messages/link-preview-card.test.ts
@@ -0,0 +1,99 @@
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { act, create, type ReactTestRenderer } from "react-test-renderer"
+import { describe, expect, it } from "vitest"
+import { tid } from "@/lib/community/testids"
+import { LinkPreviewCardView, linkPreviewStaleTime } from "./link-preview-card"
+
+describe("LinkPreviewCardView", () => {
+ it("renders a safe thumbnail in the shared Card as one external link without metadata", () => {
+ const html = renderToStaticMarkup(createElement(LinkPreviewCardView, {
+ preview: {
+ url: "https://github.com/alookai/alook/pull/511",
+ hostname: "github.com",
+ siteName: "GitHub",
+ title: "Pull Request #511",
+ description: "Rooms for people and agents.",
+ thumbnailUrl: "/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ },
+ }))
+
+ expect(html).toContain('href="https://github.com/alookai/alook/pull/511"')
+ expect(html).toContain(`data-testid="${tid.linkPreviewCard}"`)
+ expect(html).toContain('target="_blank"')
+ expect(html).toContain('rel="noopener noreferrer"')
+ expect(html).toContain('aria-label="Open link preview: Pull Request #511"')
+ expect(html).toContain('data-slot="card"')
+ expect(html).toContain('class="pb-2"')
+ expect(html).toContain("w-full max-w-96")
+ expect(html).toContain("pointer-events-none absolute top-2 right-2")
+ expect(html).toContain('aria-hidden="true"')
+ expect(html).not.toContain(">GitHub<")
+ expect(html).not.toContain("Rooms for people and agents.")
+ })
+
+ it("keeps positive previews fresh for 6h but retries negative results after 5m", () => {
+ expect(linkPreviewStaleTime({ preview: {
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Example",
+ } })).toBe(6 * 60 * 60 * 1_000)
+ expect(linkPreviewStaleTime({ preview: null })).toBe(5 * 60 * 1_000)
+ expect(linkPreviewStaleTime(undefined)).toBe(5 * 60 * 1_000)
+ expect(linkPreviewStaleTime({ preview: {
+ url: "https://example.com/",
+ hostname: "example.com",
+ title: "Recoverable image",
+ }, staleTimeSeconds: 300 })).toBe(5 * 60 * 1_000)
+ })
+
+ it("does not create a redundant text card when there is no safe thumbnail", () => {
+ const html = renderToStaticMarkup(createElement(LinkPreviewCardView, {
+ preview: {
+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ hostname: "www.youtube.com",
+ siteName: "YouTube",
+ title: "A YouTube video",
+ },
+ }))
+
+ expect(html).toBe("")
+ })
+
+ it("renders only the same-origin thumbnail path and never the upstream image URL", () => {
+ const html = renderToStaticMarkup(createElement(LinkPreviewCardView, {
+ preview: {
+ url: "https://github.com/alookai/alook/pull/511",
+ hostname: "github.com",
+ title: "Pull Request #511",
+ thumbnailUrl: "/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ },
+ }))
+
+ expect(html).toContain(`data-testid="${tid.linkPreviewThumbnail}"`)
+ expect(html).toContain('src="/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"')
+ expect(html).toContain('width="640"')
+ expect(html).toContain('height="360"')
+ expect(html).not.toContain("avatars.githubusercontent.com")
+ })
+
+ it("removes the whole redundant card after an image load failure", () => {
+ let renderer: ReactTestRenderer
+ act(() => {
+ renderer = create(createElement(LinkPreviewCardView, { preview: {
+ url: "https://example.com/story",
+ hostname: "example.com",
+ title: "Story",
+ thumbnailUrl: "/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ } }))
+ })
+
+ const image = renderer!.root.findByType("img")
+ act(() => image.props.onError())
+ expect(renderer!.root.findAllByType("img")).toHaveLength(0)
+ expect(renderer!.root.findAllByType("a")).toHaveLength(0)
+ expect(renderer!.root.findAll(
+ (node) => node.type === "div" && node.props.className === "pb-2",
+ )).toHaveLength(0)
+ })
+})
diff --git a/src/web/src/components/community/messages/link-preview-card.tsx b/src/web/src/components/community/messages/link-preview-card.tsx
new file mode 100644
index 000000000..929690e0a
--- /dev/null
+++ b/src/web/src/components/community/messages/link-preview-card.tsx
@@ -0,0 +1,117 @@
+"use client"
+
+import { memo, useEffect, useRef, useState } from "react"
+import { ExternalLink } from "lucide-react"
+import { useQuery } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import { tid } from "@/lib/community/testids"
+import type { LinkPreview } from "@/lib/community/link-preview"
+import { Card } from "@/components/ui/card"
+
+type LinkPreviewResponse = {
+ preview: LinkPreview | null
+ staleTimeSeconds?: number
+}
+
+const POSITIVE_STALE_TIME_MS = 6 * 60 * 60 * 1_000
+const NEGATIVE_STALE_TIME_MS = 5 * 60 * 1_000
+
+export function linkPreviewStaleTime(data: LinkPreviewResponse | undefined): number {
+ if (data?.staleTimeSeconds === 6 * 60 * 60) return POSITIVE_STALE_TIME_MS
+ if (data?.staleTimeSeconds === 5 * 60) return NEGATIVE_STALE_TIME_MS
+ return data?.preview ? POSITIVE_STALE_TIME_MS : NEGATIVE_STALE_TIME_MS
+}
+
+function LinkPreviewThumbnail({ src, onError }: { src: string; onError?: () => void }) {
+ const [failed, setFailed] = useState(false)
+ if (failed) return null
+ return (
+ <img
+ data-testid={tid.linkPreviewThumbnail}
+ src={src}
+ alt=""
+ width={640}
+ height={360}
+ loading="lazy"
+ decoding="async"
+ referrerPolicy="no-referrer"
+ className="aspect-video w-full bg-muted object-cover"
+ onError={() => {
+ setFailed(true)
+ onError?.()
+ }}
+ />
+ )
+}
+
+export function LinkPreviewCardView({ preview }: { preview: LinkPreview }) {
+ const [failed, setFailed] = useState(false)
+ if (!preview.thumbnailUrl || failed) return null
+
+ return (
+ <div className="pb-2">
+ <a
+ data-testid={tid.linkPreviewCard}
+ href={preview.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="group block w-full max-w-96 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={`Open link preview: ${preview.title}`}
+ >
+ <Card className="relative gap-0 py-0 transition-shadow group-hover:ring-foreground/20">
+ <LinkPreviewThumbnail src={preview.thumbnailUrl} onError={() => setFailed(true)} />
+ <span className="pointer-events-none absolute top-2 right-2 flex size-7 items-center justify-center rounded-full bg-background/80 text-foreground shadow-sm backdrop-blur-sm">
+ <ExternalLink aria-hidden="true" className="size-3.5" />
+ </span>
+ </Card>
+ </a>
+ </div>
+ )
+}
+
+function LinkPreviewCardImpl({ url }: { url: string }) {
+ const sentinelRef = useRef<HTMLSpanElement>(null)
+ const [nearViewport, setNearViewport] = useState(false)
+
+ useEffect(() => {
+ const node = sentinelRef.current
+ if (!node || typeof IntersectionObserver === "undefined") {
+ setNearViewport(true)
+ return
+ }
+ const observer = new IntersectionObserver(([entry]) => {
+ if (!entry?.isIntersecting) return
+ setNearViewport(true)
+ observer.disconnect()
+ }, { rootMargin: "240px 0px" })
+ observer.observe(node)
+ return () => observer.disconnect()
+ }, [])
+
+ const query = useQuery({
+ queryKey: communityKeys.linkPreview(url),
+ queryFn: () => apiFetch<LinkPreviewResponse>("/api/community/link-preview", {
+ method: "POST",
+ body: JSON.stringify({ url }),
+ }),
+ enabled: nearViewport,
+ staleTime: (query) => linkPreviewStaleTime(query.state.data),
+ gcTime: 24 * 60 * 60 * 1_000,
+ retry: false,
+ })
+
+ const preview = query.data?.preview
+ if (!preview) {
+ return (
+ <span
+ ref={sentinelRef}
+ className="pointer-events-none absolute size-px overflow-hidden opacity-0"
+ aria-hidden="true"
+ />
+ )
+ }
+ return <LinkPreviewCardView preview={preview} />
+}
+
+export const LinkPreviewCard = memo(LinkPreviewCardImpl)
diff --git a/src/web/src/components/community/messages/message-body.test.ts b/src/web/src/components/community/messages/message-body.test.ts
index fd1df2567..16a119330 100644
--- a/src/web/src/components/community/messages/message-body.test.ts
+++ b/src/web/src/components/community/messages/message-body.test.ts
@@ -1,7 +1,118 @@
import { describe, it, expect, vi } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { MessageBody } from "./message-body"
+import { communityKeys } from "@/lib/query-keys"
+import { tid } from "@/lib/community/testids"
+import type { LinkPreview } from "@/lib/community/link-preview"
+
+const PREVIEW_URL = "https://example.com/story"
+
+function renderLinkPreviewMessage(preview?: LinkPreview | null) {
+ class MockIntersectionObserver {
+ observe = vi.fn()
+ disconnect = vi.fn()
+ }
+ vi.stubGlobal("IntersectionObserver", MockIntersectionObserver)
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ if (preview !== undefined) {
+ client.setQueryData(communityKeys.linkPreview(PREVIEW_URL), { preview })
+ }
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client },
+ React.createElement(MessageBody, { text: PREVIEW_URL }),
+ ),
+ )
+ })
+ return {
+ renderer: renderer!,
+ cleanup() {
+ act(() => renderer!.unmount())
+ client.clear()
+ vi.unstubAllGlobals()
+ },
+ }
+}
+
+function previewSpacing(renderer: TestRenderer.ReactTestRenderer) {
+ return renderer.root.findAll(
+ (node) => node.type === "div" && node.props.className === "pb-2",
+ )
+}
+
+describe("MessageBody — link preview spacing", () => {
+ it("keeps a pending preview sentinel out of message layout", () => {
+ const rendered = renderLinkPreviewMessage()
+ try {
+ expect(previewSpacing(rendered.renderer)).toHaveLength(0)
+ const sentinel = rendered.renderer.root.findByType("span")
+ expect(sentinel.props.className).toContain("absolute")
+ } finally {
+ rendered.cleanup()
+ }
+ })
+
+ it("does not reserve preview spacing when the result has no safe thumbnail", () => {
+ const rendered = renderLinkPreviewMessage({
+ url: PREVIEW_URL,
+ hostname: "example.com",
+ title: "No image",
+ })
+ try {
+ expect(previewSpacing(rendered.renderer)).toHaveLength(0)
+ expect(rendered.renderer.root.findAllByProps({
+ "data-testid": tid.linkPreviewCard,
+ })).toHaveLength(0)
+ } finally {
+ rendered.cleanup()
+ }
+ })
+
+ it("gives bottom spacing only to a successfully rendered preview card", () => {
+ const rendered = renderLinkPreviewMessage({
+ url: PREVIEW_URL,
+ hostname: "example.com",
+ title: "With image",
+ thumbnailUrl: "/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ })
+ try {
+ expect(previewSpacing(rendered.renderer)).toHaveLength(1)
+ expect(rendered.renderer.root.findAllByProps({
+ "data-testid": tid.linkPreviewCard,
+ })).toHaveLength(1)
+ } finally {
+ rendered.cleanup()
+ }
+ })
+
+ it("removes preview spacing together with a thumbnail that fails to load", () => {
+ const rendered = renderLinkPreviewMessage({
+ url: PREVIEW_URL,
+ hostname: "example.com",
+ title: "Broken image",
+ thumbnailUrl: "/api/community/link-preview/thumbnail/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ })
+ try {
+ const image = rendered.renderer.root.findByProps({
+ "data-testid": tid.linkPreviewThumbnail,
+ })
+ act(() => image.props.onError())
+ expect(previewSpacing(rendered.renderer)).toHaveLength(0)
+ expect(rendered.renderer.root.findAllByProps({
+ "data-testid": tid.linkPreviewCard,
+ })).toHaveLength(0)
+ } finally {
+ rendered.cleanup()
+ }
+ })
+})
describe("MessageBody — theme contrast", () => {
it("pins body copy to the semantic foreground token", () => {
diff --git a/src/web/src/components/community/messages/message-body.tsx b/src/web/src/components/community/messages/message-body.tsx
index d0cbb772e..bdf563d9b 100644
--- a/src/web/src/components/community/messages/message-body.tsx
+++ b/src/web/src/components/community/messages/message-body.tsx
@@ -14,6 +14,8 @@ import {
buildMdComponents,
} from "./message-markdown"
import { CommunityInviteCard } from "../social/community-invite-card"
+import { LinkPreviewCard } from "./link-preview-card"
+import { extractLinkPreviewUrl } from "@/lib/community/link-preview"
import type { MessagePerspective } from "@/components/community/messages/message-presentation-types"
import type { OpenProfile } from "@/components/community/social/profile-types"
@@ -96,12 +98,18 @@ function MessageBodyImpl({
text,
onOpenProfile,
perspective = "neutral",
+ enableLinkPreview = true,
}: {
text: string
onOpenProfile?: OpenProfile
perspective?: MessagePerspective
+ enableLinkPreview?: boolean
}) {
const inviteTokens = useMemo(() => extractInviteTokens(text), [text])
+ const previewUrl = useMemo(
+ () => enableLinkPreview ? extractLinkPreviewUrl(text) : null,
+ [enableLinkPreview, text],
+ )
const components = useMemo(
() => buildMdComponents(onOpenProfile),
[onOpenProfile],
@@ -149,6 +157,7 @@ function MessageBodyImpl({
))}
</div>
)}
+ {previewUrl && <LinkPreviewCard url={previewUrl} />}
</div>
)
}
diff --git a/src/web/src/components/community/messages/message-share-dialog.test.ts b/src/web/src/components/community/messages/message-share-dialog.test.ts
index 7af9f6ec9..f088f7d45 100644
--- a/src/web/src/components/community/messages/message-share-dialog.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.test.ts
@@ -12,7 +12,11 @@ vi.mock("html-to-image", () => ({ toBlob: vi.fn() }))
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
vi.mock("next/image", () => ({ default: "img" }))
vi.mock("../avatar", () => ({ Avatar: "mock-avatar" }))
-vi.mock("./message-body", () => ({ MessageBody: ({ text }: { text: string }) => text }))
+vi.mock("./message-body", () => ({
+ MessageBody: (props: { text: string; enableLinkPreview?: boolean }) => (
+ React.createElement("mock-message-body", props)
+ ),
+}))
vi.mock("@/components/ui/button", () => ({ Button: "button" }))
vi.mock("@/components/ui/dialog", () => {
const Passthrough = ({ children }: { children?: React.ReactNode }) => children
@@ -104,6 +108,23 @@ describe("MessageShareDialog message context", () => {
expect(text).toEqual(expect.arrayContaining(["👍", "2", "🎉", "11"]))
})
+ it("matches the live message link-preview suppression when a richer embed exists", () => {
+ const withEmbed = renderMessage(message({
+ content: "https://example.com/story",
+ embeds: [{ title: "Story" }],
+ }))
+ const embeddedBody = withEmbed.root.find(
+ (node) => node.type === "mock-message-body",
+ )
+ expect(embeddedBody.props.enableLinkPreview).toBe(false)
+
+ const withoutEmbed = renderMessage(message({ content: "https://example.com/story" }))
+ const plainBody = withoutEmbed.root.find(
+ (node) => node.type === "mock-message-body",
+ )
+ expect(plainBody.props.enableLinkPreview).toBe(true)
+ })
+
it("renders attached originals at their intrinsic ratio and omits files", () => {
const renderer = renderMessage(message({
attachments: [
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index 5442755c3..bcc56013a 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -298,7 +298,11 @@ export function MessageShareDialog({ m, open, onClose }: {
onMouseUp={() => onBodyMouseUp(msg.id)}
className="max-h-164 overflow-hidden line-clamp-32 [&_mark[data-hl]]:rounded-xs [&_mark[data-hl]]:bg-[rgba(255,208,92,0.5)] [&_mark[data-hl]]:p-[0_1px] [&_mark[data-hl]]:[box-decoration-break:clone] [&_mark[data-hl]]:[-webkit-box-decoration-break:clone] [&_mark[data-hl]]:text-inherit"
>
- <MessageBody text={msg.content} perspective="neutral" />
+ <MessageBody
+ text={msg.content}
+ perspective="neutral"
+ enableLinkPreview={!msg.embeds?.length}
+ />
</div>
)}
{msg.attachments?.some((attachment) => attachment.kind === "image") && (
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index 2673a277a..a702684fd 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -373,6 +373,7 @@ function MessageImpl({
<MessageBody
text={m.content}
onOpenProfile={onOpenProfile}
+ enableLinkPreview={!m.embeds?.length}
perspective={
viewerUserId
? m.authorId === viewerUserId ? "sender" : "recipient"
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index eddb187ce..e803b1154 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -13,6 +13,7 @@ declare namespace Cloudflare {
DB: D1Database
EMAIL_BUCKET: R2Bucket
COMMUNITY_MEDIA: R2Bucket
+ IMAGES: ImagesBinding
BUG_REPORTS: R2Bucket
WS_DO_WORKER: Fetcher
EMAIL_WORKER: Fetcher
diff --git a/src/web/src/lib/community/link-preview-fetch.test.ts b/src/web/src/lib/community/link-preview-fetch.test.ts
new file mode 100644
index 000000000..dc301c7f2
--- /dev/null
+++ b/src/web/src/lib/community/link-preview-fetch.test.ts
@@ -0,0 +1,512 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import {
+ LINK_PREVIEW_LIMITS,
+ fetchLinkPreview,
+ normalizePublicPreviewUrl,
+} from "./link-preview-fetch"
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe("normalizePublicPreviewUrl", () => {
+ it("canonicalizes public HTTP(S) URLs and removes fragments", () => {
+ expect(normalizePublicPreviewUrl("HTTPS://Example.COM/path?q=1#private").href)
+ .toBe("https://example.com/path?q=1")
+ })
+
+ it.each([
+ ["https://8.8.8.8/path#private", "https://8.8.8.8/path"],
+ ["https://[2606:4700:4700::1111]/dns#private", "https://[2606:4700:4700::1111]/dns"],
+ ])("accepts a globally routable literal address: %s", (input, expected) => {
+ expect(normalizePublicPreviewUrl(input).href).toBe(expected)
+ })
+
+ it.each([
+ "http://localhost/",
+ "http://service.internal/",
+ "http://127.0.0.1/",
+ "http://10.0.0.1/",
+ "http://100.64.0.1/",
+ "http://169.254.169.254/",
+ "http://172.16.0.1/",
+ "http://192.168.0.1/",
+ "http://192.0.0.1/",
+ "http://192.0.2.1/",
+ "http://192.88.99.1/",
+ "http://198.18.0.1/",
+ "http://198.51.100.1/",
+ "http://203.0.113.1/",
+ "http://224.0.0.1/",
+ "http://[::1]/",
+ "http://[fc00::1]/",
+ "http://[fe80::1]/",
+ "http://[2001:db8::1]/",
+ "http://[2001::1]/",
+ "http://[2001:2::1]/",
+ "http://[2001:d::1]/",
+ "http://[2001:10::1]/",
+ "http://[2002::1]/",
+ "http://[::ffff:127.0.0.1]/",
+ "http://127.1/",
+ "http://2130706433/",
+ "http://0x7f000001/",
+ "http://0177.0.0.1/",
+ ])("rejects non-public targets: %s", (url) => {
+ expect(() => normalizePublicPreviewUrl(url)).toThrow("non-public preview host")
+ })
+
+ it.each([
+ "file:///etc/passwd",
+ "https://user:[email protected]/",
+ "https://example.com:8443/",
+ ])("rejects unsupported URL authority/protocol shapes: %s", (url) => {
+ expect(() => normalizePublicPreviewUrl(url)).toThrow()
+ })
+
+ it.each([
+ "",
+ "not a URL",
+ `https://example.com/${"x".repeat(2_048)}`,
+ ])("rejects an empty, malformed, or oversized URL: %s", (url) => {
+ expect(() => normalizePublicPreviewUrl(url)).toThrow("invalid preview URL")
+ })
+})
+
+describe("fetchLinkPreview", () => {
+ it("uses bounded YouTube oEmbed metadata instead of scanning oversized HTML", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ title: "A YouTube video",
+ provider_name: "YouTube",
+ author_name: "Example creator",
+ }), { headers: { "content-type": "application/json; charset=utf-8" } }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://www.youtube.com/watch?v=dQw4w9WgXcQ#chapter")).resolves.toEqual({
+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ hostname: "www.youtube.com",
+ title: "A YouTube video",
+ siteName: "YouTube",
+ description: "Example creator",
+ })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://www.youtube.com/oembed?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ&format=json",
+ )
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ method: "GET",
+ redirect: "error",
+ referrerPolicy: "no-referrer",
+ })
+ })
+
+ it("keeps a validated YouTube thumbnail URL internal to the server result", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ title: "A YouTube video",
+ provider_name: "YouTube",
+ thumbnail_url: "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
+ }), { headers: { "content-type": "application/json" } })))
+
+ await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ")).resolves.toMatchObject({
+ title: "A YouTube video",
+ thumbnailSource: "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
+ })
+ })
+
+ it.each([
+ "https://youtu.be/dQw4w9WgXcQ?t=5",
+ "https://m.youtube.com/shorts/dQw4w9WgXcQ",
+ "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",
+ ])("extracts a legal video id from an explicit supported shape: %s", async (url) => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ title: "Supported video shape",
+ provider_name: "YouTube",
+ }), { headers: { "content-type": "application/json" } }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview(url)).resolves.toMatchObject({ title: "Supported video shape" })
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://www.youtube.com/oembed?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdQw4w9WgXcQ&format=json",
+ )
+ })
+
+ it("caps YouTube oEmbed bodies and cancels the oversized stream", async () => {
+ const cancel = vi.fn()
+ const oversized = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array(LINK_PREVIEW_LIMITS.maxOEmbedBytes + 1))
+ },
+ cancel,
+ })
+ const fetchMock = vi.fn().mockResolvedValue(new Response(oversized, {
+ headers: { "content-type": "application/json" },
+ }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
+ .rejects.toThrow("preview response is too large")
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("rejects a bodyless YouTube oEmbed response", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, {
+ headers: { "content-type": "application/json" },
+ })))
+
+ await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
+ .rejects.toThrow("preview response has no body")
+ })
+
+ it("rejects YouTube oEmbed JSON without a meaningful title", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ provider_name: "YouTube",
+ author_name: "Example creator",
+ }), { headers: { "content-type": "application/json" } })))
+
+ await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
+ .rejects.toThrow("YouTube oEmbed metadata missing")
+ })
+
+ it.each([
+ "https://youtube.example.org/watch?v=dQw4w9WgXcQ",
+ "https://notyoutube.com/watch?v=dQw4w9WgXcQ",
+ "https://www.youtube.com/",
+ "https://www.youtube.com/@alookai",
+ "https://www.youtube.com/watch?v=too-short",
+ ])("does not use oEmbed for a non-video YouTube shape: %s", async (url) => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(
+ "<html><head><meta property='og:title' content='Generic HTML'></head></html>",
+ { headers: { "content-type": "text/html" } },
+ ))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview(url)).resolves.toMatchObject({ title: "Generic HTML" })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(new URL(url).href)
+ })
+
+ it("does not follow an oEmbed redirect, including one toward a private target", async () => {
+ const cancel = vi.fn()
+ const redirectBody = new ReadableStream<Uint8Array>({ cancel })
+ const fetchMock = vi.fn().mockResolvedValue(new Response(redirectBody, {
+ status: 302,
+ headers: { location: "http://127.0.0.1/metadata" },
+ }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://www.youtube.com/watch?v=dQw4w9WgXcQ"))
+ .rejects.toThrow("YouTube oEmbed rejected request")
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("rejects and cancels an oEmbed response with the wrong MIME type", async () => {
+ const cancel = vi.fn()
+ const body = new ReadableStream<Uint8Array>({ cancel })
+ const fetchMock = vi.fn().mockResolvedValue(new Response(body, {
+ headers: { "content-type": "text/html" },
+ }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ"))
+ .rejects.toThrow("YouTube oEmbed response is not JSON")
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("sanitizes and caps malicious oEmbed text without returning remote HTML or media", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ title: `Safe\u202E<script>${"x".repeat(200)}`,
+ provider_name: `You\u0007Tube${"y".repeat(100)}`,
+ author_name: `Creator\u202E${"z".repeat(100)}`,
+ html: "<iframe src='https://attacker.invalid'></iframe>",
+ thumbnail_url: "https://attacker.invalid/image.png",
+ }), { headers: { "content-type": "application/json" } })))
+
+ const preview = await fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ")
+
+ expect(preview.title).toHaveLength(160)
+ expect(preview.siteName).toHaveLength(80)
+ expect(preview.description).toHaveLength(80)
+ expect(`${preview.title}${preview.siteName}${preview.description}`).not.toMatch(/[\u0007\u202E]/)
+ expect(preview).not.toHaveProperty("html")
+ expect(preview).not.toHaveProperty("thumbnail_url")
+ })
+
+ it("applies the single total timeout while waiting for YouTube oEmbed", async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true })
+ })))
+
+ const preview = fetchLinkPreview("https://youtu.be/dQw4w9WgXcQ")
+ const rejected = expect(preview).rejects.toThrow("aborted")
+ await vi.advanceTimersByTimeAsync(LINK_PREVIEW_LIMITS.timeoutMs)
+
+ await rejected
+ })
+
+ it("follows bounded manual redirects, revalidates them, and sanitizes metadata", async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(null, {
+ status: 302,
+ headers: { location: "https://www.example.com/final" },
+ }))
+ .mockResolvedValueOnce(new Response(
+ "<html><head>"
+ + "<meta property='og:site_name' content=' Example Site '>"
+ + "<meta property='og:title' content='Safe\u202E title'>"
+ + "<meta name='description' content=' A useful description '>"
+ + "</head><body>ignored</body></html>",
+ { headers: { "content-type": "text/html; charset=utf-8" } },
+ ))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://example.com/start#fragment")).resolves.toEqual({
+ url: "https://example.com/start",
+ hostname: "example.com",
+ title: "Safe title",
+ description: "A useful description",
+ siteName: "Example Site",
+ })
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ method: "GET",
+ redirect: "manual",
+ referrerPolicy: "no-referrer",
+ })
+ })
+
+ it("rejects a redirect that moves to a private target before fetching it", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, {
+ status: 302,
+ headers: { location: "http://127.0.0.1/admin" },
+ }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://example.com/start"))
+ .rejects.toThrow("non-public preview host")
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it("rejects and cancels a redirect without a location", async () => {
+ const cancel = vi.fn()
+ const body = new ReadableStream<Uint8Array>({ cancel })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, { status: 302 })))
+
+ await expect(fetchLinkPreview("https://example.com/start"))
+ .rejects.toThrow("invalid preview redirect")
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("revalidates every redirect hop before the next fetch", async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(null, {
+ status: 302,
+ headers: { location: "https://example.org/second" },
+ }))
+ .mockResolvedValueOnce(new Response(null, {
+ status: 302,
+ headers: { location: "http://127.0.0.1/admin" },
+ }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://example.com/start"))
+ .rejects.toThrow("non-public preview host")
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it("caps redirect chains and cancels every unused redirect body", async () => {
+ const cancel = vi.fn()
+ const redirectBody = () => new ReadableStream<Uint8Array>({ cancel })
+ const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(redirectBody(), {
+ status: 302,
+ headers: { location: "https://example.com/again" },
+ })))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchLinkPreview("https://example.com/start"))
+ .rejects.toThrow("too many preview redirects")
+ expect(fetchMock).toHaveBeenCalledTimes(LINK_PREVIEW_LIMITS.maxRedirects + 1)
+ expect(cancel).toHaveBeenCalledTimes(LINK_PREVIEW_LIMITS.maxRedirects + 1)
+ })
+
+ it("parses the bounded head of a large page instead of rejecting its body size", async () => {
+ const head = "<html><head><meta property='og:title' content='Large page'></head>"
+ const oversized = head + "x".repeat(LINK_PREVIEW_LIMITS.maxHtmlBytes * 2)
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(oversized, {
+ headers: {
+ "content-type": "text/html",
+ "content-length": String(oversized.length),
+ },
+ })))
+
+ await expect(fetchLinkPreview("https://github.com/alookai/alook/pull/1"))
+ .resolves.toMatchObject({ title: "Large page", hostname: "github.com" })
+ })
+
+ it("stops a chunked response without content-length at the actual byte ceiling", async () => {
+ const encoder = new TextEncoder()
+ const cancel = vi.fn()
+ const first = encoder.encode("<html><head><meta property='og:title' content='Chunked page'>")
+ const fill = encoder.encode("x".repeat(16 * 1024))
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(first)
+ },
+ pull(controller) {
+ controller.enqueue(fill)
+ },
+ cancel,
+ })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, {
+ headers: { "content-type": "text/html" },
+ })))
+
+ await expect(fetchLinkPreview("https://example.com/chunked"))
+ .resolves.toMatchObject({ title: "Chunked page" })
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("uses one timeout budget while waiting for response headers", async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true })
+ })))
+
+ const preview = fetchLinkPreview("https://example.com/slow-headers")
+ const rejected = expect(preview).rejects.toThrow("aborted")
+ await vi.advanceTimersByTimeAsync(LINK_PREVIEW_LIMITS.timeoutMs)
+
+ await rejected
+ })
+
+ it("uses the same timeout budget while a streamed body stalls", async () => {
+ vi.useFakeTimers()
+ const encoder = new TextEncoder()
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => Promise.resolve(new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(encoder.encode("<html><head><meta property='og:title' content='Slow'>"))
+ init?.signal?.addEventListener("abort", () => controller.error(new Error("aborted")), { once: true })
+ },
+ }),
+ { headers: { "content-type": "text/html" } },
+ ))))
+
+ const preview = fetchLinkPreview("https://example.com/slow-body")
+ const rejected = expect(preview).rejects.toThrow("aborted")
+ await vi.advanceTimersByTimeAsync(LINK_PREVIEW_LIMITS.timeoutMs)
+
+ await rejected
+ })
+
+ it("rejects a bodyless HTML response", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, {
+ headers: { "content-type": "text/html" },
+ })))
+
+ await expect(fetchLinkPreview("https://example.com/bodyless"))
+ .rejects.toThrow("preview response has no body")
+ })
+
+ it("rejects and cancels a non-success HTML response", async () => {
+ const cancel = vi.fn()
+ const body = new ReadableStream<Uint8Array>({ cancel })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, { status: 503 })))
+
+ await expect(fetchLinkPreview("https://example.com/unavailable"))
+ .rejects.toThrow("preview origin rejected request")
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("rejects non-HTML responses", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", {
+ headers: { "content-type": "application/json" },
+ })))
+
+ await expect(fetchLinkPreview("https://example.com/data"))
+ .rejects.toThrow("preview response is not HTML")
+ })
+
+ it("falls back to Twitter Card metadata when Open Graph tags are absent", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
+ "<html><head>"
+ + "<meta name='twitter:title' content='Twitter-only title'>"
+ + "<meta name='twitter:description' content='Twitter-only description'>"
+ + "</head></html>",
+ { headers: { "content-type": "text/html" } },
+ )))
+
+ await expect(fetchLinkPreview("https://example.com/twitter-only")).resolves.toMatchObject({
+ title: "Twitter-only title",
+ description: "Twitter-only description",
+ })
+ })
+
+ it("selects the first public HTTPS Open Graph image resolved against the final page", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
+ "<html><head>"
+ + "<meta property='og:title' content='With image'>"
+ + "<meta property='og:image' content='/assets/card.png#fragment'>"
+ + "</head></html>",
+ { headers: { "content-type": "text/html" } },
+ )))
+
+ await expect(fetchLinkPreview("https://example.com/post")).resolves.toMatchObject({
+ title: "With image",
+ thumbnailSource: "https://example.com/assets/card.png",
+ })
+ })
+
+ it("falls back to a Twitter image without exposing insecure or private candidates", async () => {
+ const html = (image: string) => "<html><head>"
+ + "<meta name='twitter:title' content='Twitter-only'>"
+ + `<meta name='twitter:image' content='${image}'>`
+ + "</head></html>"
+
+ for (const [image, expected] of [
+ ["https://cdn.example.org/card.webp", "https://cdn.example.org/card.webp"],
+ ["http://cdn.example.org/card.webp", undefined],
+ ["https://127.0.0.1/card.webp", undefined],
+ ] as const) {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(html(image), {
+ headers: { "content-type": "text/html" },
+ })))
+ const preview = await fetchLinkPreview("https://example.com/twitter-image")
+ expect(preview.thumbnailSource).toBe(expected)
+ }
+ })
+
+ it("removes controls and bidi markers and caps every returned field", async () => {
+ const title = `T\u202E${"a".repeat(200)}`
+ const description = `D\u0007${"b".repeat(400)}`
+ const siteName = `S${"c".repeat(100)}`
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
+ `<html><head><meta property='og:title' content='${title}'>`
+ + `<meta property='og:description' content='${description}'>`
+ + `<meta property='og:site_name' content='${siteName}'></head></html>`,
+ { headers: { "content-type": "text/html" } },
+ )))
+
+ const preview = await fetchLinkPreview("https://example.com/capped")
+
+ expect(preview.title).toHaveLength(160)
+ expect(preview.description).toHaveLength(320)
+ expect(preview.siteName).toHaveLength(80)
+ expect(`${preview.title}${preview.description}${preview.siteName}`).not.toMatch(/[\u0007\u202E]/)
+ })
+
+ it("rejects an HTML page with no meaningful preview metadata", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
+ "<html><head></head><body>Untitled</body></html>",
+ { headers: { "content-type": "text/html" } },
+ )))
+
+ await expect(fetchLinkPreview("https://example.com/untitled"))
+ .rejects.toThrow("preview metadata missing")
+ })
+})
diff --git a/src/web/src/lib/community/link-preview-fetch.ts b/src/web/src/lib/community/link-preview-fetch.ts
new file mode 100644
index 000000000..c5277de14
--- /dev/null
+++ b/src/web/src/lib/community/link-preview-fetch.ts
@@ -0,0 +1,359 @@
+import { isIP } from "node:net"
+import { getPreviewFromContent } from "link-preview-js/mobile"
+import type { LinkPreview } from "./link-preview"
+
+export type FetchedLinkPreview = LinkPreview & { thumbnailSource?: string }
+
+const MAX_URL_LENGTH = 2_048
+const MAX_HTML_BYTES = 128 * 1024
+const MAX_OEMBED_BYTES = 16 * 1024
+const MAX_REDIRECTS = 3
+const TOTAL_TIMEOUT_MS = 3_000
+const YOUTUBE_VIDEO_ID_RE = /^[A-Za-z0-9_-]{11}$/
+const YOUTUBE_HOSTS = new Set([
+ "youtube.com",
+ "www.youtube.com",
+ "m.youtube.com",
+ "music.youtube.com",
+])
+const YOUTUBE_NOCOOKIE_HOSTS = new Set([
+ "youtube-nocookie.com",
+ "www.youtube-nocookie.com",
+])
+const CONTROL_AND_BIDI_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g
+const SPECIAL_HOST_SUFFIXES = [
+ ".localhost",
+ ".local",
+ ".internal",
+ ".home.arpa",
+ ".test",
+ ".invalid",
+ ".example",
+ ".onion",
+]
+
+function ipv4Bytes(hostname: string): number[] | null {
+ /* istanbul ignore next -- caller only invokes this after isIP(hostname) === 4 */
+ if (isIP(hostname) !== 4) return null
+ const bytes = hostname.split(".").map(Number)
+ return bytes.length === 4 && bytes.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255)
+ ? bytes
+ : null
+}
+
+function ipv6Words(hostname: string): number[] | null {
+ const host = hostname.replace(/^\[|\]$/g, "")
+ /* istanbul ignore next -- caller only invokes this after isIP(host) === 6 */
+ if (isIP(host) !== 6) return null
+ const [leftRaw, rightRaw] = host.split("::")
+ const left = leftRaw ? leftRaw.split(":") : []
+ const right = rightRaw ? rightRaw.split(":") : []
+ const missing = 8 - left.length - right.length
+ /* istanbul ignore next -- isIP(host) === 6 guarantees a valid eight-word expansion */
+ if (missing < 0 || (!host.includes("::") && missing !== 0)) return null
+ const parts = [...left, ...Array.from({ length: missing }, () => "0"), ...right]
+ const words = parts.map((part) => Number.parseInt(part || "0", 16))
+ return words.length === 8 && words.every((word) => Number.isInteger(word) && word >= 0 && word <= 0xffff)
+ ? words
+ : null
+}
+
+function isPublicIpv4(bytes: number[]): boolean {
+ const [a, b, c] = bytes
+ if (a === 0 || a === 10 || a === 127 || a >= 224) return false
+ if (a === 100 && b >= 64 && b <= 127) return false
+ if (a === 169 && b === 254) return false
+ if (a === 172 && b >= 16 && b <= 31) return false
+ if (a === 192 && b === 168) return false
+ if (a === 192 && b === 0 && (c === 0 || c === 2)) return false
+ if (a === 192 && b === 88 && c === 99) return false
+ if (a === 198 && (b === 18 || b === 19)) return false
+ if (a === 198 && b === 51 && c === 100) return false
+ if (a === 203 && b === 0 && c === 113) return false
+ return true
+}
+
+function isPublicIpv6(words: number[]): boolean {
+ // IPv4-mapped IPv6 must inherit the embedded IPv4 decision.
+ if (words.slice(0, 5).every((word) => word === 0) && words[5] === 0xffff) {
+ return isPublicIpv4([
+ words[6] >> 8,
+ words[6] & 0xff,
+ words[7] >> 8,
+ words[7] & 0xff,
+ ])
+ }
+
+ // Only globally-routable unicast (2000::/3), excluding special-use ranges.
+ if ((words[0] & 0xe000) !== 0x2000) return false
+ if (words[0] === 0x2001) {
+ const second = words[1]
+ if (second === 0x0000 || second === 0x0002 || second === 0x000d || second === 0x0db8) return false
+ if ((second & 0xfff0) === 0x0010) return false
+ }
+ // 6to4 can tunnel to an embedded private IPv4 destination.
+ if (words[0] === 0x2002) return false
+ return true
+}
+
+function isSpecialHostname(hostname: string): boolean {
+ const host = hostname.toLowerCase().replace(/\.$/, "")
+ if (host === "localhost") return true
+ return SPECIAL_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))
+}
+
+/** Parse, canonicalize, and reject targets outside the public HTTP(S) web. */
+export function normalizePublicPreviewUrl(input: string): URL {
+ if (!input || input.length > MAX_URL_LENGTH) throw new Error("invalid preview URL")
+ let url: URL
+ try {
+ url = new URL(input)
+ } catch {
+ throw new Error("invalid preview URL")
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("unsupported preview protocol")
+ if (url.username || url.password || url.port) throw new Error("unsupported preview authority")
+ if (!url.hostname || isSpecialHostname(url.hostname)) throw new Error("non-public preview host")
+
+ const host = url.hostname.replace(/^\[|\]$/g, "")
+ const ipVersion = isIP(host)
+ if (ipVersion === 4 && !isPublicIpv4(ipv4Bytes(host)!)) throw new Error("non-public preview host")
+ if (ipVersion === 6 && !isPublicIpv6(ipv6Words(host)!)) throw new Error("non-public preview host")
+
+ url.hash = ""
+ return url
+}
+
+function cleanText(value: unknown, maxLength: number): string | undefined {
+ if (typeof value !== "string") return undefined
+ const cleaned = value
+ .replace(CONTROL_AND_BIDI_RE, "")
+ .replace(/\s+/g, " ")
+ .trim()
+ if (!cleaned) return undefined
+ return Array.from(cleaned).slice(0, maxLength).join("")
+}
+
+function cleanThumbnailSource(value: unknown, base: URL): string | undefined {
+ if (typeof value !== "string" || !value) return undefined
+ try {
+ const source = normalizePublicPreviewUrl(new URL(value, base).href)
+ return source.protocol === "https:" ? source.href : undefined
+ } catch {
+ return undefined
+ }
+}
+
+function youtubeVideoId(url: URL): string | null {
+ const host = url.hostname.toLowerCase()
+ let candidate: string | null = null
+ if (host === "youtu.be" && /^\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) {
+ candidate = url.pathname.split("/")[1] ?? null
+ } else if (YOUTUBE_HOSTS.has(host) && url.pathname === "/watch") {
+ candidate = url.searchParams.get("v")
+ } else if (YOUTUBE_HOSTS.has(host) && /^\/(?:shorts|embed|live)\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) {
+ candidate = url.pathname.split("/")[2] ?? null
+ } else if (YOUTUBE_NOCOOKIE_HOSTS.has(host) && /^\/embed\/[A-Za-z0-9_-]+\/?$/.test(url.pathname)) {
+ candidate = url.pathname.split("/")[2] ?? null
+ }
+ return candidate && YOUTUBE_VIDEO_ID_RE.test(candidate) ? candidate : null
+}
+
+async function readBoundedText(response: Response, maxBytes: number): Promise<string> {
+ if (!response.body) throw new Error("preview response has no body")
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let text = ""
+ let total = 0
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+ const remaining = maxBytes - total
+ if (value.byteLength > remaining) {
+ await reader.cancel()
+ throw new Error("preview response is too large")
+ }
+ total += value.byteLength
+ text += decoder.decode(value, { stream: true })
+ }
+ } finally {
+ reader.releaseLock()
+ }
+ return text + decoder.decode()
+}
+
+async function fetchYouTubeOEmbed(original: URL, videoId: string, signal: AbortSignal): Promise<FetchedLinkPreview> {
+ // The destination is fixed rather than derived from user input. The source
+ // URL is only an encoded oEmbed parameter, so it cannot steer the fetch.
+ const endpoint = new URL("https://www.youtube.com/oembed")
+ endpoint.searchParams.set("url", `https://www.youtube.com/watch?v=${videoId}`)
+ endpoint.searchParams.set("format", "json")
+ const response = await fetch(endpoint.href, {
+ method: "GET",
+ redirect: "error",
+ signal,
+ headers: { Accept: "application/json" },
+ referrerPolicy: "no-referrer",
+ })
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {})
+ throw new Error("YouTube oEmbed rejected request")
+ }
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
+ if (!/^application\/(?:[\w.+-]+\+)?json(?:;|$)/.test(contentType)) {
+ await response.body?.cancel().catch(() => {})
+ throw new Error("YouTube oEmbed response is not JSON")
+ }
+
+ const record = JSON.parse(await readBoundedText(response, MAX_OEMBED_BYTES)) as Record<string, unknown>
+ const title = cleanText(record.title, 160)
+ if (!title) throw new Error("YouTube oEmbed metadata missing")
+ const siteName = cleanText(record.provider_name, 80) ?? "YouTube"
+ const authorName = cleanText(record.author_name, 80)
+ const thumbnailSource = cleanThumbnailSource(record.thumbnail_url, original)
+ return {
+ url: original.href,
+ hostname: original.hostname,
+ title,
+ siteName,
+ ...(authorName ? { description: authorName } : {}),
+ ...(thumbnailSource ? { thumbnailSource } : {}),
+ }
+}
+
+async function readBoundedHtml(response: Response): Promise<string> {
+ if (!response.body) throw new Error("preview response has no body")
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let html = ""
+ let total = 0
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+
+ const remaining = MAX_HTML_BYTES - total
+ const chunk = value.byteLength > remaining ? value.subarray(0, remaining) : value
+ total += chunk.byteLength
+ html += decoder.decode(chunk, { stream: true })
+
+ // Metadata belongs in <head>. Stop as soon as it is complete, and also
+ // stop at the byte ceiling instead of rejecting otherwise-valid pages
+ // whose full body is large (GitHub PR pages routinely exceed the cap).
+ if (/<\/head\s*>/i.test(html) || total === MAX_HTML_BYTES) {
+ await reader.cancel()
+ break
+ }
+ }
+ } finally {
+ reader.releaseLock()
+ }
+ return html + decoder.decode()
+}
+
+function isRedirect(status: number): boolean {
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
+}
+
+async function fetchHtml(start: URL, signal: AbortSignal): Promise<{ html: string; finalUrl: URL; contentType: string }> {
+ let current = start
+ for (let redirects = 0; ; redirects += 1) {
+ const response = await fetch(current.href, {
+ method: "GET",
+ redirect: "manual",
+ signal,
+ headers: {
+ Accept: "text/html,application/xhtml+xml",
+ "User-Agent": "Alook-Link-Preview/1.0",
+ },
+ referrerPolicy: "no-referrer",
+ })
+
+ if (isRedirect(response.status)) {
+ await response.body?.cancel().catch(() => {})
+ if (redirects === MAX_REDIRECTS) throw new Error("too many preview redirects")
+ const location = response.headers.get("location")
+ if (!location) throw new Error("invalid preview redirect")
+ current = normalizePublicPreviewUrl(new URL(location, current).href)
+ continue
+ }
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {})
+ throw new Error("preview origin rejected request")
+ }
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? ""
+ if (!/^text\/html(?:;|$)|^application\/xhtml\+xml(?:;|$)/.test(contentType)) {
+ await response.body?.cancel().catch(() => {})
+ throw new Error("preview response is not HTML")
+ }
+ return { html: await readBoundedHtml(response), finalUrl: current, contentType }
+ }
+}
+
+/**
+ * Fetch one public page within a single hard budget and return sanitized text
+ * plus an internal, revalidated image candidate. The caller must never expose
+ * thumbnailSource; it is only input to the same-origin thumbnail manifest.
+ */
+export async function fetchLinkPreview(input: string): Promise<FetchedLinkPreview> {
+ const original = normalizePublicPreviewUrl(input)
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), TOTAL_TIMEOUT_MS)
+ try {
+ const youtubeId = youtubeVideoId(original)
+ if (youtubeId) {
+ return await fetchYouTubeOEmbed(original, youtubeId, controller.signal)
+ }
+ const { html, finalUrl, contentType } = await fetchHtml(original, controller.signal)
+ const parsed = await getPreviewFromContent({
+ url: finalUrl.href,
+ data: html,
+ headers: { "content-type": contentType },
+ }, {
+ imagesPropertyType: "og",
+ // link-preview-js covers Open Graph + ordinary title/description but
+ // not pages that expose Twitter Card tags only. Fill only its gaps.
+ onResponse: (response, doc) => ({
+ ...response,
+ title: response.title
+ || doc("meta[name='twitter:title'],meta[property='twitter:title']").first().attr("content")
+ || "",
+ description: response.description
+ || doc("meta[name='twitter:description'],meta[property='twitter:description']").first().attr("content"),
+ images: response.images.length > 0
+ ? response.images
+ : [doc("meta[name='twitter:image'],meta[property='twitter:image']").first().attr("content")]
+ .filter((value): value is string => Boolean(value)),
+ }),
+ })
+ const record = parsed as Record<string, unknown>
+ const parsedTitle = cleanText(record.title, 160)
+ const description = cleanText(record.description, 320)
+ const siteName = cleanText(record.siteName, 80)
+ const thumbnailSource = Array.isArray(record.images)
+ ? cleanThumbnailSource(record.images[0], finalUrl)
+ : undefined
+ if (!parsedTitle && !description) throw new Error("preview metadata missing")
+ const title = parsedTitle ?? siteName ?? original.hostname
+ return {
+ url: original.href,
+ hostname: original.hostname,
+ title,
+ ...(description ? { description } : {}),
+ ...(siteName ? { siteName } : {}),
+ ...(thumbnailSource ? { thumbnailSource } : {}),
+ }
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+export const LINK_PREVIEW_LIMITS = {
+ maxHtmlBytes: MAX_HTML_BYTES,
+ maxOEmbedBytes: MAX_OEMBED_BYTES,
+ maxRedirects: MAX_REDIRECTS,
+ timeoutMs: TOTAL_TIMEOUT_MS,
+} as const
diff --git a/src/web/src/lib/community/link-preview-thumbnail.test.ts b/src/web/src/lib/community/link-preview-thumbnail.test.ts
new file mode 100644
index 000000000..4771a6df9
--- /dev/null
+++ b/src/web/src/lib/community/link-preview-thumbnail.test.ts
@@ -0,0 +1,500 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import {
+ LINK_PREVIEW_THUMBNAIL_LIMITS,
+ fetchAndTransformLinkPreviewThumbnail,
+ isFreshLinkPreviewThumbnailObject,
+ linkPreviewPageDigest,
+ linkPreviewThumbnailManifestKey,
+ linkPreviewThumbnailNegativeKey,
+ linkPreviewThumbnailObjectKey,
+ linkPreviewThumbnailObjectMetadata,
+ linkPreviewThumbnailUrl,
+ normalizePublicImageUrl,
+ readLinkPreviewThumbnailManifest,
+ writeLinkPreviewThumbnailManifest,
+ type LinkPreviewThumbnailManifest,
+} from "./link-preview-thumbnail"
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+function bytesStream(bytes: Uint8Array, cancel?: () => void): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(bytes)
+ controller.close()
+ },
+ cancel,
+ })
+}
+
+function mockImages(args: {
+ format?: string
+ width?: number
+ height?: number
+ output?: Uint8Array
+ outputType?: string
+} = {}) {
+ const transform = vi.fn()
+ const output = vi.fn()
+ const transformer = {
+ transform: (...values: unknown[]) => {
+ transform(...values)
+ return transformer
+ },
+ output: async (...values: unknown[]) => {
+ output(...values)
+ const transformed = args.output ?? new Uint8Array([1, 2, 3])
+ return {
+ contentType: () => args.outputType ?? "image/webp",
+ image: () => bytesStream(transformed),
+ response: () => new Response(transformed),
+ }
+ },
+ }
+ const binding = {
+ info: vi.fn().mockResolvedValue({
+ format: args.format ?? "image/jpeg",
+ fileSize: 3,
+ width: args.width ?? 1200,
+ height: args.height ?? 630,
+ }),
+ input: vi.fn(() => transformer),
+ } as unknown as ImagesBinding
+ return { binding, output, transform }
+}
+
+function response(body = new Uint8Array([0xff, 0xd8, 0xff]), init: ResponseInit = {}): Response {
+ return new Response(body, {
+ ...init,
+ headers: { "content-type": "image/jpeg", ...init.headers },
+ })
+}
+
+describe("link preview thumbnail addressing and manifests", () => {
+ it("derives only fixed digest paths and keys", async () => {
+ const digest = await linkPreviewPageDigest("https://example.com/")
+ expect(digest).toMatch(/^[a-f0-9]{64}$/)
+ expect(linkPreviewThumbnailUrl(digest)).toBe(`/api/community/link-preview/thumbnail/${digest}`)
+ expect(linkPreviewThumbnailManifestKey(digest)).toBe(`link-preview-thumbnails/v1/${digest}/manifest.json`)
+ expect(linkPreviewThumbnailObjectKey(digest)).toBe(`link-preview-thumbnails/v1/${digest}/thumbnail.webp`)
+ expect(linkPreviewThumbnailNegativeKey(digest, "b".repeat(64)))
+ .toBe(`link-preview-thumbnail-negative:v1:${digest}:${"b".repeat(64)}`)
+ expect(() => linkPreviewThumbnailUrl("../source")).toThrow("invalid thumbnail digest")
+ })
+
+ it("accepts only normalized public HTTPS image candidates", () => {
+ expect(normalizePublicImageUrl("/og.png#private", new URL("https://example.com/post")).href)
+ .toBe("https://example.com/og.png")
+ expect(() => normalizePublicImageUrl("http://example.com/og.png")).toThrow("must use HTTPS")
+ expect(() => normalizePublicImageUrl("https://127.0.0.1/og.png")).toThrow("non-public")
+ expect(() => normalizePublicImageUrl("https://user:[email protected]/og.png")).toThrow("authority")
+ expect(() => normalizePublicImageUrl("https://example.com:8443/og.png")).toThrow("authority")
+ })
+
+ it("writes and reads one strongly-bound, expiring private manifest", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const pageDigest = "a".repeat(64)
+ const manifest = await writeLinkPreviewThumbnailManifest({
+ bucket: { put } as Pick<R2Bucket, "put">,
+ pageDigest,
+ sourceUrl: "https://images.example.com/og.png#fragment",
+ now: 1_000,
+ })
+ expect(manifest).toMatchObject({
+ version: 1,
+ pageDigest,
+ sourceUrl: "https://images.example.com/og.png",
+ expiresAt: 1_000 + LINK_PREVIEW_THUMBNAIL_LIMITS.manifestTtlMs,
+ })
+ expect(manifest.sourceDigest).toMatch(/^[a-f0-9]{64}$/)
+ const stored = put.mock.calls[0]?.[1] as string
+ const object = {
+ size: new TextEncoder().encode(stored).byteLength,
+ body: bytesStream(new TextEncoder().encode(stored)),
+ text: vi.fn().mockResolvedValue(stored),
+ }
+ await expect(readLinkPreviewThumbnailManifest({
+ bucket: { get: vi.fn().mockResolvedValue(object) } as unknown as Pick<R2Bucket, "get">,
+ pageDigest,
+ now: 2_000,
+ })).resolves.toEqual(manifest)
+ })
+
+ it("rejects invalid manifest writes and supports the default clock", async () => {
+ await expect(writeLinkPreviewThumbnailManifest({
+ bucket: { put: vi.fn() } as Pick<R2Bucket, "put">,
+ pageDigest: "../source",
+ sourceUrl: "https://example.com/image.jpg",
+ })).rejects.toThrow("invalid thumbnail digest")
+
+ const before = Date.now()
+ const manifest = await writeLinkPreviewThumbnailManifest({
+ bucket: { put: vi.fn().mockResolvedValue(undefined) } as Pick<R2Bucket, "put">,
+ pageDigest: "a".repeat(64),
+ sourceUrl: "https://example.com/image.jpg",
+ })
+ expect(manifest.expiresAt).toBeGreaterThanOrEqual(before + LINK_PREVIEW_THUMBNAIL_LIMITS.manifestTtlMs)
+ })
+
+ it.each([
+ ["missing", null],
+ ["oversized", { size: 4097, body: bytesStream(new Uint8Array([1])), text: vi.fn() }],
+ ["malformed", { size: 1, body: bytesStream(new Uint8Array([1])), text: vi.fn().mockResolvedValue("{") }],
+ ["mismatched", { size: 100, body: bytesStream(new Uint8Array([1])), text: vi.fn().mockResolvedValue(JSON.stringify({ version: 1, pageDigest: "b".repeat(64), sourceUrl: "https://example.com/a.jpg", sourceDigest: "c".repeat(64), expiresAt: 9_999 })) }],
+ ["expired", { size: 100, body: bytesStream(new Uint8Array([1])), text: vi.fn().mockResolvedValue(JSON.stringify({ version: 1, pageDigest: "a".repeat(64), sourceUrl: "https://example.com/a.jpg", sourceDigest: "c".repeat(64), expiresAt: 1 })) }],
+ ])("fails closed for a %s manifest", async (_label, object) => {
+ await expect(readLinkPreviewThumbnailManifest({
+ bucket: { get: vi.fn().mockResolvedValue(object) } as unknown as Pick<R2Bucket, "get">,
+ pageDigest: "a".repeat(64),
+ now: 2,
+ })).resolves.toBeNull()
+ })
+
+ it("rejects invalid, non-record, and source-digest-mismatched manifests", async () => {
+ const get = vi.fn()
+ await expect(readLinkPreviewThumbnailManifest({
+ bucket: { get } as unknown as Pick<R2Bucket, "get">,
+ pageDigest: "../source",
+ })).resolves.toBeNull()
+ expect(get).not.toHaveBeenCalled()
+
+ for (const stored of [
+ "null",
+ JSON.stringify({
+ version: 1,
+ pageDigest: "a".repeat(64),
+ sourceUrl: "https://example.com/a.jpg",
+ sourceDigest: "c".repeat(64),
+ expiresAt: 9_999,
+ }),
+ ]) {
+ await expect(readLinkPreviewThumbnailManifest({
+ bucket: {
+ get: vi.fn().mockResolvedValue({
+ size: stored.length,
+ body: bytesStream(new TextEncoder().encode(stored)),
+ text: vi.fn().mockResolvedValue(stored),
+ }),
+ } as unknown as Pick<R2Bucket, "get">,
+ pageDigest: "a".repeat(64),
+ now: 1,
+ })).resolves.toBeNull()
+ }
+ })
+
+ it("swallows a failed oversized-manifest body cancellation", async () => {
+ const cancel = vi.fn().mockRejectedValue(new Error("already closed"))
+ await expect(readLinkPreviewThumbnailManifest({
+ bucket: {
+ get: vi.fn().mockResolvedValue({ size: 4097, body: { cancel } }),
+ } as unknown as Pick<R2Bucket, "get">,
+ pageDigest: "a".repeat(64),
+ })).resolves.toBeNull()
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("serves only a fresh WebP object matching the current source digest", () => {
+ const manifest = { sourceDigest: "a".repeat(64) } as LinkPreviewThumbnailManifest
+ const object = {
+ size: 123,
+ httpMetadata: { contentType: "image/webp" },
+ customMetadata: { sourceDigest: "a".repeat(64), expiresAt: "2000" },
+ } as unknown as R2ObjectBody
+ expect(isFreshLinkPreviewThumbnailObject(object, manifest, 1_000)).toBe(true)
+ expect(isFreshLinkPreviewThumbnailObject({ ...object, size: 512 * 1024 + 1 } as R2ObjectBody, manifest, 1_000)).toBe(false)
+ expect(isFreshLinkPreviewThumbnailObject({ ...object, customMetadata: { ...object.customMetadata, sourceDigest: "b".repeat(64) } } as R2ObjectBody, manifest, 1_000)).toBe(false)
+ expect(isFreshLinkPreviewThumbnailObject(object, manifest, 2_000)).toBe(false)
+ })
+})
+
+describe("fetchAndTransformLinkPreviewThumbnail", () => {
+ it.each([
+ ["image/jpeg", "image/jpeg"],
+ ["image/png", "image/png"],
+ ["image/webp", "image/webp"],
+ ])("accepts a bounded static %s and applies the one fixed profile", async (declared, decoded) => {
+ const images = mockImages({ format: decoded })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(new Uint8Array([1, 2, 3]), {
+ headers: { "content-type": declared },
+ })))
+
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://images.example.com/og", images.binding))
+ .resolves.toEqual(new Uint8Array([1, 2, 3]))
+ expect(images.transform).toHaveBeenCalledWith({ width: 640, height: 360, fit: "cover" })
+ expect(images.output).toHaveBeenCalledWith({ format: "image/webp", quality: 78, anim: false })
+ })
+
+ it("follows at most three redirects, cancels them, and revalidates every HTTPS hop", async () => {
+ const cancel = vi.fn()
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(new ReadableStream<Uint8Array>({ cancel }), {
+ status: 302,
+ headers: { location: "https://cdn.example.com/second" },
+ }))
+ .mockResolvedValueOnce(response())
+ vi.stubGlobal("fetch", fetchMock)
+
+ await fetchAndTransformLinkPreviewThumbnail("https://images.example.com/start", mockImages().binding)
+
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ redirect: "manual",
+ credentials: "omit",
+ referrerPolicy: "no-referrer",
+ })
+ })
+
+ it.each([
+ ["HTTP downgrade", "http://example.com/image.jpg", "must use HTTPS"],
+ ["private redirect", "https://127.0.0.1/image.jpg", "non-public"],
+ ])("rejects a %s before the next fetch", async (_label, location, message) => {
+ const cancel = vi.fn()
+ const fetchMock = vi.fn().mockResolvedValue(new Response(new ReadableStream<Uint8Array>({ cancel }), {
+ status: 302,
+ headers: { location },
+ }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/start", mockImages().binding))
+ .rejects.toThrow(message)
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it("rejects a missing redirect location and a fourth redirect, canceling every body", async () => {
+ const missingCancel = vi.fn()
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(new ReadableStream<Uint8Array>({ cancel: missingCancel }), { status: 302 })))
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/start", mockImages().binding))
+ .rejects.toThrow("invalid thumbnail redirect")
+ expect(missingCancel).toHaveBeenCalledOnce()
+
+ const cancel = vi.fn()
+ const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(new ReadableStream<Uint8Array>({ cancel }), {
+ status: 302,
+ headers: { location: "https://example.com/again" },
+ })))
+ vi.stubGlobal("fetch", fetchMock)
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/start", mockImages().binding))
+ .rejects.toThrow("too many thumbnail redirects")
+ expect(fetchMock).toHaveBeenCalledTimes(4)
+ expect(cancel).toHaveBeenCalledTimes(4)
+ })
+
+ it.each([
+ ["bodyless", new Response(null, { headers: { "content-type": "image/jpeg" } }), "no body"],
+ ["non-success", response(undefined, { status: 503 }), "rejected request"],
+ ["missing MIME", new Response(new Uint8Array([1])), "unsupported thumbnail MIME"],
+ ["wrong MIME", response(undefined, { headers: { "content-type": "image/gif" } }), "unsupported thumbnail MIME"],
+ ["declared oversize", response(undefined, { headers: { "content-type": "image/jpeg", "content-length": String(5 * 1024 * 1024 + 1) } }), "too large"],
+ ["unsafe declared length", response(undefined, { headers: { "content-type": "image/jpeg", "content-length": "9".repeat(400) } }), "too large"],
+ ["empty body", response(new Uint8Array()), "empty"],
+ ])("rejects a %s upstream response", async (_label, upstream, message) => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(upstream))
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/image", mockImages().binding))
+ .rejects.toThrow(message)
+ })
+
+ it("stream-counts and cancels an oversized body without content-length", async () => {
+ const cancel = vi.fn()
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array(LINK_PREVIEW_THUMBNAIL_LIMITS.maxSourceBytes + 1))
+ },
+ cancel,
+ })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(body, {
+ headers: { "content-type": "image/jpeg" },
+ })))
+
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/image", mockImages().binding))
+ .rejects.toThrow("too large")
+ expect(cancel).toHaveBeenCalledOnce()
+ })
+
+ it.each([
+ ["SVG", "image/svg+xml", 100, 100, "image/jpeg"],
+ ["GIF", "image/gif", 100, 100, "image/jpeg"],
+ ["MIME mismatch", "image/png", 100, 100, "image/jpeg"],
+ ["oversized side", "image/jpeg", 8193, 1, "image/jpeg"],
+ ["oversized area", "image/jpeg", 8000, 2001, "image/jpeg"],
+ ])("rejects decoded %s before transformation", async (_label, format, width, height, declared) => {
+ const images = mockImages({ format, width, height })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(undefined, {
+ headers: { "content-type": declared },
+ })))
+
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/image", images.binding)).rejects.toThrow()
+ expect(images.transform).not.toHaveBeenCalled()
+ })
+
+ it("rejects APNG and animated WebP before transformation", async () => {
+ const apng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0, 0, 0, 0, 0x61, 0x63, 0x54, 0x4c, 0, 0, 0, 0,
+ ])
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(apng, { headers: { "content-type": "image/png" } })))
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/apng", mockImages({ format: "image/png" }).binding))
+ .rejects.toThrow("animated thumbnail")
+
+ const animatedWebp = new Uint8Array([
+ 0x52, 0x49, 0x46, 0x46, 10, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
+ 0x56, 0x50, 0x38, 0x58, 1, 0, 0, 0, 0x02, 0,
+ ])
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(animatedWebp, { headers: { "content-type": "image/webp" } })))
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/animated", mockImages({ format: "image/webp" }).binding))
+ .rejects.toThrow("animated thumbnail")
+
+ const animChunkWebp = new Uint8Array([
+ 0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
+ 0x41, 0x4e, 0x49, 0x4d, 0, 0, 0, 0,
+ ])
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(animChunkWebp, { headers: { "content-type": "image/webp" } })))
+ await expect(fetchAndTransformLinkPreviewThumbnail("https://example.com/anim-chunk", mockImages({ format: "image/webp" }).binding))
+ .rejects.toThrow("animated thumbnail")
+ })
+
+ it.each([
+ [
+ "a malformed PNG chunk",
+ "image/png",
+ new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0, 0, 0, 20, 0x74, 0x45, 0x58, 0x74, 0, 0, 0, 0,
+ ]),
+ ],
+ [
+ "a malformed WebP chunk",
+ "image/webp",
+ new Uint8Array([
+ 0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
+ 0x56, 0x50, 0x38, 0x20, 20, 0, 0, 0,
+ ]),
+ ],
+ ])("fails safely while scanning %s", async (_label, mime, bytes) => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(bytes, {
+ headers: { "content-type": mime },
+ })))
+
+ await expect(fetchAndTransformLinkPreviewThumbnail(
+ "https://example.com/static",
+ mockImages({ format: mime }).binding,
+ )).resolves.toEqual(new Uint8Array([1, 2, 3]))
+ })
+
+ it.each([
+ [
+ "a static PNG ending at IDAT",
+ "image/png",
+ new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0, 0, 0, 0, 0x49, 0x44, 0x41, 0x54, 0, 0, 0, 0,
+ ]),
+ ],
+ [
+ "a static PNG with only an ancillary chunk",
+ "image/png",
+ new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0, 0, 0, 0, 0x74, 0x45, 0x58, 0x74, 0, 0, 0, 0,
+ ]),
+ ],
+ [
+ "a static WebP chunk",
+ "image/webp",
+ new Uint8Array([
+ 0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50,
+ 0x56, 0x50, 0x38, 0x20, 0, 0, 0, 0,
+ ]),
+ ],
+ ])("accepts %s as non-animated", async (_label, mime, bytes) => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(bytes, {
+ headers: { "content-type": mime },
+ })))
+
+ await expect(fetchAndTransformLinkPreviewThumbnail(
+ "https://example.com/static",
+ mockImages({ format: mime }).binding,
+ )).resolves.toEqual(new Uint8Array([1, 2, 3]))
+ })
+
+ it("rejects a wrong or oversized transformed output", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockImplementation(() => Promise.resolve(response())))
+ await expect(fetchAndTransformLinkPreviewThumbnail(
+ "https://example.com/image",
+ mockImages({ outputType: "image/png" }).binding,
+ )).rejects.toThrow("wrong MIME")
+
+ await expect(fetchAndTransformLinkPreviewThumbnail(
+ "https://example.com/image",
+ mockImages({ output: new Uint8Array(LINK_PREVIEW_THUMBNAIL_LIMITS.maxOutputBytes + 1) }).binding,
+ )).rejects.toThrow("too large")
+ })
+
+ it("rejects decoded image info without raster dimensions", async () => {
+ const images = mockImages()
+ vi.mocked(images.binding.info).mockResolvedValue({
+ format: "image/svg+xml",
+ fileSize: 3,
+ })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response()))
+
+ await expect(fetchAndTransformLinkPreviewThumbnail(
+ "https://example.com/image",
+ images.binding,
+ )).rejects.toThrow("unsupported decoded thumbnail format")
+ })
+
+ it("applies one three-second budget across a stalled source read", async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => Promise.resolve(new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ init?.signal?.addEventListener("abort", () => controller.error(new Error("aborted")), { once: true })
+ },
+ }),
+ { headers: { "content-type": "image/jpeg" } },
+ ))))
+
+ const result = fetchAndTransformLinkPreviewThumbnail("https://example.com/slow", mockImages().binding)
+ .catch((error: unknown) => error)
+ await vi.advanceTimersByTimeAsync(LINK_PREVIEW_THUMBNAIL_LIMITS.timeoutMs)
+ await expect(result).resolves.toMatchObject({ message: expect.stringMatching(/aborted|timed out/) })
+ })
+
+ it("rejects before reading when the source fetch resolves after the total budget", async () => {
+ vi.useFakeTimers()
+ let resolveFetch!: (response: Response) => void
+ vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => {
+ resolveFetch = resolve
+ })))
+
+ const result = fetchAndTransformLinkPreviewThumbnail(
+ "https://example.com/late-headers",
+ mockImages().binding,
+ )
+ await vi.advanceTimersByTimeAsync(LINK_PREVIEW_THUMBNAIL_LIMITS.timeoutMs)
+ resolveFetch(response())
+
+ await expect(result).rejects.toMatchObject({ name: "AbortError" })
+ })
+
+ it("builds exact 24-hour R2 object metadata", () => {
+ const manifest = { sourceDigest: "a".repeat(64) } as LinkPreviewThumbnailManifest
+ expect(linkPreviewThumbnailObjectMetadata(manifest, 1_000)).toEqual({
+ httpMetadata: {
+ contentType: "image/webp",
+ cacheControl: "private, max-age=21600, immutable",
+ contentDisposition: "inline",
+ },
+ customMetadata: {
+ sourceDigest: "a".repeat(64),
+ expiresAt: String(1_000 + LINK_PREVIEW_THUMBNAIL_LIMITS.thumbnailTtlMs),
+ },
+ })
+ })
+})
diff --git a/src/web/src/lib/community/link-preview-thumbnail.ts b/src/web/src/lib/community/link-preview-thumbnail.ts
new file mode 100644
index 000000000..1c104c1b8
--- /dev/null
+++ b/src/web/src/lib/community/link-preview-thumbnail.ts
@@ -0,0 +1,394 @@
+import { normalizePublicPreviewUrl } from "./link-preview-fetch"
+
+const THUMBNAIL_VERSION = 1
+const THUMBNAIL_PREFIX = "link-preview-thumbnails/v1"
+const MAX_SOURCE_BYTES = 5 * 1024 * 1024
+const MAX_OUTPUT_BYTES = 512 * 1024
+const MAX_MANIFEST_BYTES = 4 * 1024
+const MAX_REDIRECTS = 3
+const TOTAL_TIMEOUT_MS = 3_000
+const MAX_DIMENSION = 8_192
+const MAX_AREA = 16_000_000
+const THUMBNAIL_WIDTH = 640
+const THUMBNAIL_HEIGHT = 360
+const THUMBNAIL_QUALITY = 78
+const MANIFEST_TTL_MS = 6 * 60 * 60 * 1_000
+const THUMBNAIL_TTL_MS = 24 * 60 * 60 * 1_000
+const TOKEN_RE = /^[a-f0-9]{64}$/
+const ALLOWED_MIME = new Set(["image/jpeg", "image/png", "image/webp"])
+
+export type LinkPreviewThumbnailManifest = {
+ version: 1
+ pageDigest: string
+ sourceUrl: string
+ sourceDigest: string
+ expiresAt: number
+}
+
+function streamFromBytes(bytes: Uint8Array): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(bytes)
+ controller.close()
+ },
+ })
+}
+
+async function sha256Hex(value: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")
+}
+
+export async function linkPreviewPageDigest(canonicalPageUrl: string): Promise<string> {
+ return sha256Hex(canonicalPageUrl)
+}
+
+export function linkPreviewThumbnailUrl(pageDigest: string): string {
+ if (!TOKEN_RE.test(pageDigest)) throw new Error("invalid thumbnail digest")
+ return `/api/community/link-preview/thumbnail/${pageDigest}`
+}
+
+export function linkPreviewThumbnailManifestKey(pageDigest: string): string {
+ return `${THUMBNAIL_PREFIX}/${pageDigest}/manifest.json`
+}
+
+export function linkPreviewThumbnailObjectKey(pageDigest: string): string {
+ return `${THUMBNAIL_PREFIX}/${pageDigest}/thumbnail.webp`
+}
+
+export function linkPreviewThumbnailNegativeKey(pageDigest: string, sourceDigest: string): string {
+ return `link-preview-thumbnail-negative:v1:${pageDigest}:${sourceDigest}`
+}
+
+export function isLinkPreviewThumbnailDigest(value: string | undefined): value is string {
+ return typeof value === "string" && TOKEN_RE.test(value)
+}
+
+export function normalizePublicImageUrl(input: string, base?: URL): URL {
+ const resolved = base ? new URL(input, base) : new URL(input)
+ const normalized = normalizePublicPreviewUrl(resolved.href)
+ if (normalized.protocol !== "https:") throw new Error("thumbnail source must use HTTPS")
+ return normalized
+}
+
+export async function writeLinkPreviewThumbnailManifest(args: {
+ bucket: Pick<R2Bucket, "put">
+ pageDigest: string
+ sourceUrl: string
+ now?: number
+}): Promise<LinkPreviewThumbnailManifest> {
+ if (!isLinkPreviewThumbnailDigest(args.pageDigest)) throw new Error("invalid thumbnail digest")
+ const sourceUrl = normalizePublicImageUrl(args.sourceUrl).href
+ const now = args.now ?? Date.now()
+ const manifest: LinkPreviewThumbnailManifest = {
+ version: THUMBNAIL_VERSION,
+ pageDigest: args.pageDigest,
+ sourceUrl,
+ sourceDigest: await sha256Hex(sourceUrl),
+ expiresAt: now + MANIFEST_TTL_MS,
+ }
+ await args.bucket.put(
+ linkPreviewThumbnailManifestKey(args.pageDigest),
+ JSON.stringify(manifest),
+ {
+ httpMetadata: { contentType: "application/json" },
+ customMetadata: {
+ version: String(THUMBNAIL_VERSION),
+ pageDigest: args.pageDigest,
+ sourceDigest: manifest.sourceDigest,
+ expiresAt: String(manifest.expiresAt),
+ },
+ },
+ )
+ return manifest
+}
+
+function manifestRecord(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null
+}
+
+export async function readLinkPreviewThumbnailManifest(args: {
+ bucket: Pick<R2Bucket, "get">
+ pageDigest: string
+ now?: number
+}): Promise<LinkPreviewThumbnailManifest | null> {
+ if (!isLinkPreviewThumbnailDigest(args.pageDigest)) return null
+ const object = await args.bucket.get(linkPreviewThumbnailManifestKey(args.pageDigest))
+ if (!object) return null
+ if (object.size <= 0 || object.size > MAX_MANIFEST_BYTES) {
+ await object.body.cancel().catch(() => {})
+ return null
+ }
+ try {
+ const record = manifestRecord(JSON.parse(await object.text()))
+ if (!record
+ || record.version !== THUMBNAIL_VERSION
+ || record.pageDigest !== args.pageDigest
+ || typeof record.sourceUrl !== "string"
+ || typeof record.sourceDigest !== "string"
+ || !TOKEN_RE.test(record.sourceDigest)
+ || typeof record.expiresAt !== "number"
+ || !Number.isSafeInteger(record.expiresAt)
+ || record.expiresAt <= (args.now ?? Date.now())) {
+ return null
+ }
+ const sourceUrl = normalizePublicImageUrl(record.sourceUrl).href
+ if (await sha256Hex(sourceUrl) !== record.sourceDigest) return null
+ return {
+ version: THUMBNAIL_VERSION,
+ pageDigest: args.pageDigest,
+ sourceUrl,
+ sourceDigest: record.sourceDigest,
+ expiresAt: record.expiresAt,
+ }
+ } catch {
+ return null
+ }
+}
+
+export function isFreshLinkPreviewThumbnailObject(
+ object: R2ObjectBody,
+ manifest: LinkPreviewThumbnailManifest,
+ now = Date.now(),
+): boolean {
+ const expiresAt = Number(object.customMetadata?.expiresAt)
+ return object.size > 0
+ && object.size <= MAX_OUTPUT_BYTES
+ && object.httpMetadata?.contentType === "image/webp"
+ && object.customMetadata?.sourceDigest === manifest.sourceDigest
+ && Number.isSafeInteger(expiresAt)
+ && expiresAt > now
+}
+
+function isRedirect(status: number): boolean {
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
+}
+
+function abortError(): Error {
+ return new DOMException("thumbnail request timed out", "AbortError")
+}
+
+async function withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) throw abortError()
+ let rejectAbort!: (reason?: unknown) => void
+ const aborted = new Promise<never>((_resolve, reject) => {
+ rejectAbort = reject
+ })
+ const onAbort = () => rejectAbort(abortError())
+ signal.addEventListener("abort", onAbort, { once: true })
+ try {
+ return await Promise.race([promise, aborted])
+ } finally {
+ signal.removeEventListener("abort", onAbort)
+ }
+}
+
+async function readBoundedBytes(
+ body: ReadableStream<Uint8Array> | null,
+ maxBytes: number,
+ signal: AbortSignal,
+): Promise<Uint8Array> {
+ if (!body) throw new Error("thumbnail response has no body")
+ const reader = body.getReader()
+ const chunks: Uint8Array[] = []
+ let total = 0
+ try {
+ while (true) {
+ const { done, value } = await withAbort(reader.read(), signal)
+ if (done) break
+ total += value.byteLength
+ if (total > maxBytes) {
+ await reader.cancel().catch(() => {})
+ throw new Error("thumbnail response is too large")
+ }
+ chunks.push(value)
+ }
+ } catch (error) {
+ await reader.cancel().catch(() => {})
+ throw error
+ } finally {
+ reader.releaseLock()
+ }
+ if (total === 0) throw new Error("thumbnail response is empty")
+ const bytes = new Uint8Array(total)
+ let offset = 0
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset)
+ offset += chunk.byteLength
+ }
+ return bytes
+}
+
+function declaredContentLength(response: Response): number | null {
+ const raw = response.headers.get("content-length")
+ if (!raw || !/^\d+$/.test(raw)) return null
+ const value = Number(raw)
+ return Number.isSafeInteger(value) ? value : Number.POSITIVE_INFINITY
+}
+
+async function fetchThumbnailSource(start: URL, signal: AbortSignal): Promise<{
+ bytes: Uint8Array
+ contentType: string
+}> {
+ let current = start
+ for (let redirects = 0; ; redirects += 1) {
+ const response = await fetch(current.href, {
+ method: "GET",
+ redirect: "manual",
+ signal,
+ credentials: "omit",
+ headers: {
+ Accept: "image/jpeg,image/png,image/webp",
+ "User-Agent": "Alook-Link-Preview-Thumbnail/1.0",
+ },
+ referrerPolicy: "no-referrer",
+ })
+ if (isRedirect(response.status)) {
+ await response.body?.cancel().catch(() => {})
+ if (redirects === MAX_REDIRECTS) throw new Error("too many thumbnail redirects")
+ const location = response.headers.get("location")
+ if (!location) throw new Error("invalid thumbnail redirect")
+ current = normalizePublicImageUrl(location, current)
+ continue
+ }
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {})
+ throw new Error("thumbnail origin rejected request")
+ }
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
+ if (!ALLOWED_MIME.has(contentType)) {
+ await response.body?.cancel().catch(() => {})
+ throw new Error("unsupported thumbnail MIME")
+ }
+ if ((declaredContentLength(response) ?? 0) > MAX_SOURCE_BYTES) {
+ await response.body?.cancel().catch(() => {})
+ throw new Error("thumbnail response is too large")
+ }
+ return {
+ bytes: await readBoundedBytes(response.body, MAX_SOURCE_BYTES, signal),
+ contentType,
+ }
+ }
+}
+
+function ascii(bytes: Uint8Array, offset: number, length: number): string {
+ return String.fromCharCode(...bytes.subarray(offset, offset + length))
+}
+
+function isAnimatedPng(bytes: Uint8Array): boolean {
+ const pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
+ if (bytes.length < 8 || pngSignature.some((byte, index) => bytes[index] !== byte)) return false
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
+ let offset = 8
+ while (offset + 12 <= bytes.length) {
+ const length = view.getUint32(offset)
+ const end = offset + 12 + length
+ if (end > bytes.length) return false
+ const type = ascii(bytes, offset + 4, 4)
+ if (type === "acTL") return true
+ if (type === "IDAT" || type === "IEND") return false
+ offset = end
+ }
+ return false
+}
+
+function isAnimatedWebp(bytes: Uint8Array): boolean {
+ if (bytes.length < 12 || ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") return false
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
+ let offset = 12
+ while (offset + 8 <= bytes.length) {
+ const type = ascii(bytes, offset, 4)
+ const length = view.getUint32(offset + 4, true)
+ const dataStart = offset + 8
+ const end = dataStart + length
+ if (end > bytes.length) return false
+ if (type === "ANIM" || type === "ANMF") return true
+ if (type === "VP8X" && length >= 1 && (bytes[dataStart]! & 0x02) !== 0) return true
+ offset = end + (length % 2)
+ }
+ return false
+}
+
+function decodedMime(format: string): string | null {
+ const normalized = format.toLowerCase()
+ if (normalized === "image/jpeg" || normalized === "jpeg" || normalized === "jpg") return "image/jpeg"
+ if (normalized === "image/png" || normalized === "png") return "image/png"
+ if (normalized === "image/webp" || normalized === "webp") return "image/webp"
+ return null
+}
+
+async function transformThumbnail(
+ images: ImagesBinding,
+ bytes: Uint8Array,
+ declaredMime: string,
+ signal: AbortSignal,
+): Promise<Uint8Array> {
+ const info = await withAbort(images.info(streamFromBytes(bytes)), signal)
+ if (!("width" in info) || !("height" in info)) throw new Error("unsupported decoded thumbnail format")
+ const actualMime = decodedMime(info.format)
+ if (!actualMime || actualMime !== declaredMime) throw new Error("thumbnail MIME mismatch")
+ if (actualMime === "image/png" && isAnimatedPng(bytes)) throw new Error("animated thumbnail rejected")
+ if (actualMime === "image/webp" && isAnimatedWebp(bytes)) throw new Error("animated thumbnail rejected")
+ if (!Number.isSafeInteger(info.width)
+ || !Number.isSafeInteger(info.height)
+ || info.width <= 0
+ || info.height <= 0
+ || info.width > MAX_DIMENSION
+ || info.height > MAX_DIMENSION
+ || info.width * info.height > MAX_AREA) {
+ throw new Error("thumbnail dimensions exceed limit")
+ }
+
+ const output = await withAbort(images
+ .input(streamFromBytes(bytes))
+ .transform({ width: THUMBNAIL_WIDTH, height: THUMBNAIL_HEIGHT, fit: "cover" })
+ .output({ format: "image/webp", quality: THUMBNAIL_QUALITY, anim: false }), signal)
+ if (output.contentType() !== "image/webp") throw new Error("thumbnail transform returned wrong MIME")
+ return readBoundedBytes(output.image(), MAX_OUTPUT_BYTES, signal)
+}
+
+export async function fetchAndTransformLinkPreviewThumbnail(
+ sourceUrl: string,
+ images: ImagesBinding,
+): Promise<Uint8Array> {
+ const source = normalizePublicImageUrl(sourceUrl)
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), TOTAL_TIMEOUT_MS)
+ try {
+ const fetched = await fetchThumbnailSource(source, controller.signal)
+ return await transformThumbnail(images, fetched.bytes, fetched.contentType, controller.signal)
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+export function linkPreviewThumbnailObjectMetadata(manifest: LinkPreviewThumbnailManifest, now = Date.now()) {
+ return {
+ httpMetadata: {
+ contentType: "image/webp",
+ cacheControl: "private, max-age=21600, immutable",
+ contentDisposition: "inline",
+ },
+ customMetadata: {
+ sourceDigest: manifest.sourceDigest,
+ expiresAt: String(now + THUMBNAIL_TTL_MS),
+ },
+ } satisfies R2PutOptions
+}
+
+export const LINK_PREVIEW_THUMBNAIL_LIMITS = {
+ maxSourceBytes: MAX_SOURCE_BYTES,
+ maxOutputBytes: MAX_OUTPUT_BYTES,
+ maxRedirects: MAX_REDIRECTS,
+ timeoutMs: TOTAL_TIMEOUT_MS,
+ maxDimension: MAX_DIMENSION,
+ maxArea: MAX_AREA,
+ width: THUMBNAIL_WIDTH,
+ height: THUMBNAIL_HEIGHT,
+ quality: THUMBNAIL_QUALITY,
+ manifestTtlMs: MANIFEST_TTL_MS,
+ thumbnailTtlMs: THUMBNAIL_TTL_MS,
+ prefix: THUMBNAIL_PREFIX,
+} as const
diff --git a/src/web/src/lib/community/link-preview.test.ts b/src/web/src/lib/community/link-preview.test.ts
new file mode 100644
index 000000000..b750d07cc
--- /dev/null
+++ b/src/web/src/lib/community/link-preview.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest"
+import { extractLinkPreviewUrl } from "./link-preview"
+
+describe("extractLinkPreviewUrl", () => {
+ it("selects the first eligible URL and strips fragments", () => {
+ expect(extractLinkPreviewUrl(
+ "first https://example.com/path#section then https://example.org/later",
+ )).toBe("https://example.com/path")
+ })
+
+ it("keeps prose punctuation outside the selected URL", () => {
+ expect(extractLinkPreviewUrl("See (https://github.com/alookai/alook/pull/1)."))
+ .toBe("https://github.com/alookai/alook/pull/1")
+ })
+
+ it("skips invite action-card URLs and selects the next ordinary link", () => {
+ expect(extractLinkPreviewUrl(
+ "https://alook.ai/c/invite/abcdef https://x.com/alook/status/123",
+ )).toBe("https://x.com/alook/status/123")
+ })
+
+ it("returns null when the message has no eligible public-web URL", () => {
+ expect(extractLinkPreviewUrl("no link here /c/invite/abcdef ftp://example.com"))
+ .toBeNull()
+ })
+})
diff --git a/src/web/src/lib/community/link-preview.ts b/src/web/src/lib/community/link-preview.ts
new file mode 100644
index 000000000..02992023a
--- /dev/null
+++ b/src/web/src/lib/community/link-preview.ts
@@ -0,0 +1,34 @@
+export type LinkPreview = {
+ url: string
+ hostname: string
+ title: string
+ description?: string
+ siteName?: string
+ thumbnailUrl?: string
+}
+
+const URL_CANDIDATE_RE = /https?:\/\/[^\s<>"']+/gi
+const TRAILING_PROSE_RE = /[.,!?;:'"\)\]\}]+$/
+const INVITE_PATH_RE = /^\/c\/invite\/[A-Za-z0-9_-]{6,64}\/?$/
+
+/**
+ * Returns at most one ordinary public-web URL for a message preview. The raw
+ * message remains untouched; this is only a cheap selector for the lazy card.
+ * Alook invite URLs keep their dedicated action card and are skipped here.
+ */
+export function extractLinkPreviewUrl(text: string): string | null {
+ for (const match of text.matchAll(URL_CANDIDATE_RE)) {
+ const candidate = match[0]?.replace(TRAILING_PROSE_RE, "")
+ if (!candidate) continue
+ try {
+ const url = new URL(candidate)
+ if (url.protocol !== "http:" && url.protocol !== "https:") continue
+ if (INVITE_PATH_RE.test(url.pathname)) continue
+ url.hash = ""
+ return url.href
+ } catch {
+ // Keep scanning: malformed prose before a valid URL must not suppress it.
+ }
+ }
+ return null
+}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index df22fd6c3..730ed63b6 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -70,6 +70,8 @@ export const tid = {
imageLightboxLoading: "community-image-lightbox-loading",
imageLightboxError: "community-image-lightbox-error",
imageLightboxRetry: "community-image-lightbox-retry",
+ linkPreviewCard: "community-link-preview-card",
+ linkPreviewThumbnail: "community-link-preview-thumbnail",
message: (id: string) => `community-message-${id}`,
messageImage: (id: string, index: number) => `community-message-image-${id}-${index}`,
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 137d132e8..e779737c8 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -139,6 +139,11 @@ describe("communityKeys", () => {
"message",
"m1",
])
+ expect(communityKeys.linkPreview("https://example.com/")).toEqual([
+ "community",
+ "link-preview",
+ "https://example.com/",
+ ])
})
it("keeps report polling specific to one report and outside the bots-list cache", () => {
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 6fd3ffe0c..14c410981 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -53,6 +53,10 @@ export const communityKeys = {
// have — the id/serverId only comes back with the response.
inviteInfo: (token: string) =>
[...communityKeys.all, "invite-info", token] as const,
+ // Independent lazy unfurl. The full normalized URL is safe in the
+ // per-browser query cache; server KV keys hash it before persistence.
+ linkPreview: (url: string) =>
+ [...communityKeys.all, "link-preview", url] as const,
// ── Channel-scoped resources ────────────────────────────────────────────
// Message list roots are keyed by channelId so paginated pages nest under
diff --git a/src/web/src/test/architecture/link-preview-runtime-config.test.ts b/src/web/src/test/architecture/link-preview-runtime-config.test.ts
new file mode 100644
index 000000000..15ff26a3e
--- /dev/null
+++ b/src/web/src/test/architecture/link-preview-runtime-config.test.ts
@@ -0,0 +1,36 @@
+import { readFileSync } from "node:fs"
+import { fileURLToPath } from "node:url"
+import { describe, expect, it } from "vitest"
+import { RATE_LIMITS } from "../../../../shared/src/lib/rate-limits"
+
+describe("link preview Worker network boundary", () => {
+ it("deploys global fetch through the public Internet boundary", () => {
+ const wranglerPath = fileURLToPath(new URL("../../../wrangler.toml", import.meta.url))
+ const config = readFileSync(wranglerPath, "utf8")
+ const flags = config.match(/^compatibility_flags\s*=\s*\[([^\]]+)\]/m)?.[1] ?? ""
+
+ expect(flags).toContain('"nodejs_compat"')
+ expect(flags).toContain('"global_fetch_strictly_public"')
+ expect(config).toMatch(/^\[images\]\nbinding\s*=\s*"IMAGES"$/m)
+ expect(RATE_LIMITS["community:linkPreviewThumbnail"]).toEqual({
+ windowMs: 60_000,
+ max: 120,
+ })
+ })
+
+ it("fails every Web production artifact path closed on the R2 lifecycle preflight", () => {
+ const webPackagePath = fileURLToPath(new URL("../../../package.json", import.meta.url))
+ const rootPackagePath = fileURLToPath(new URL("../../../../../package.json", import.meta.url))
+ const webPackage = JSON.parse(readFileSync(webPackagePath, "utf8")) as {
+ scripts: Record<string, string>
+ }
+ const rootPackage = JSON.parse(readFileSync(rootPackagePath, "utf8")) as {
+ scripts: Record<string, string>
+ }
+
+ expect(webPackage.scripts.deploy).toMatch(/^pnpm preflight:link-preview-thumbnails && /)
+ expect(webPackage.scripts.upload).toMatch(/^pnpm preflight:link-preview-thumbnails && /)
+ expect(rootPackage.scripts["deploy:web"])
+ .toMatch(/^pnpm --filter @alook\/web preflight:link-preview-thumbnails && /)
+ })
+})
diff --git a/src/web/test-runtime/worker.runtime.test.ts b/src/web/test-runtime/worker.runtime.test.ts
index 649c765f7..f1b99158f 100644
--- a/src/web/test-runtime/worker.runtime.test.ts
+++ b/src/web/test-runtime/worker.runtime.test.ts
@@ -9,6 +9,15 @@ const worker = (exports as unknown as {
default: { fetch(request: Request): Promise<Response> }
}).default
+function byteStream(bytes: Uint8Array): ReadableStream<Uint8Array> {
+ return new ReadableStream({
+ start(controller) {
+ controller.enqueue(bytes)
+ controller.close()
+ },
+ })
+}
+
describe("Web workerd runtime", () => {
it("loads production migrations and local storage bindings", async () => {
const schema = await runtimeEnv.DB.prepare(
@@ -27,6 +36,23 @@ describe("Web workerd runtime", () => {
await runtimeEnv.CACHE_KV.delete(kvKey)
})
+ it("decodes and transforms a raster through the configured Images binding", async () => {
+ const png = Uint8Array.from(
+ atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="),
+ (char) => char.charCodeAt(0),
+ )
+ const info = await runtimeEnv.IMAGES.info(byteStream(png))
+ expect(info).toMatchObject({ format: "image/png", width: 1, height: 1 })
+
+ const output = await runtimeEnv.IMAGES
+ .input(byteStream(png))
+ .transform({ width: 640, height: 360, fit: "cover" })
+ .output({ format: "image/webp", quality: 78, anim: false })
+ expect(output.contentType()).toBe("image/webp")
+ const transformed = new Uint8Array(await new Response(output.image()).arrayBuffer())
+ expect(transformed.byteLength).toBeGreaterThan(0)
+ })
+
it.each(["/", "/pricing", "/apiary"])(
"adds browser and CDN revalidation headers to public route %s",
async (pathname) => {
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index 4db1bfef6..60174278a 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -1,7 +1,7 @@
name = "alook-web"
main = "custom-worker.ts"
compatibility_date = "2026-04-09"
-compatibility_flags = ["nodejs_compat"]
+compatibility_flags = ["nodejs_compat", "global_fetch_strictly_public"]
# Disable esbuild keep_names — otherwise __name(...) wrappers leak into
# stringified inline scripts (ThemeScript, next-themes) and throw
# "__name is not defined" at runtime in the browser.
@@ -62,6 +62,9 @@ bucket_name = "alook-emails"
binding = "COMMUNITY_MEDIA"
bucket_name = "alook-community-media"
+[images]
+binding = "IMAGES"
+
[[r2_buckets]]
binding = "BUG_REPORTS"
bucket_name = "alook-bug-reports"