workers-start 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scripts.js CHANGED
@@ -30,6 +30,23 @@ export function themeScript(options = {}) {
30
30
  : "";
31
31
  return `try{var t=localStorage.getItem(${key});${fallback}if(${values}.indexOf(t)!==-1){${apply}}}catch(e){}`;
32
32
  }
33
+ /** The hostname, path and consent checks both analytics bootstraps start with. */
34
+ function gateChecks(options) {
35
+ const hosts = inlineJson(options.hosts.map((h) => h.toLowerCase()));
36
+ const checks = [
37
+ `if(${hosts}.indexOf(location.hostname.toLowerCase())===-1)return;`,
38
+ ];
39
+ if (options.skipPaths?.length) {
40
+ checks.push(`var p=location.pathname;if(${inlineJson(options.skipPaths)}.some(function(s){return p===s||p.indexOf(s.replace(/\\/$/,"")+"/")===0}))return;`);
41
+ }
42
+ if (options.consentCookie) {
43
+ const pair = options.consentCookie.value === undefined
44
+ ? null
45
+ : `${options.consentCookie.name}=${options.consentCookie.value}`;
46
+ checks.push(`var k=document.cookie.split(/;\\s*/);if(!k.some(function(c){return ${pair === null ? `c.split("=")[0]===${inlineJson(options.consentCookie.name)}` : `c===${inlineJson(pair)}`}}))return;`);
47
+ }
48
+ return checks.join("");
49
+ }
33
50
  /**
34
51
  * Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
35
52
  * preview deploys never fetch gtag.js or land in the production property.
@@ -39,15 +56,17 @@ export function analyticsScript(options) {
39
56
  throw new Error(`Not a GA4 measurement id: ${options.measurementId}`);
40
57
  }
41
58
  const id = inlineJson(options.measurementId);
42
- const hosts = inlineJson(options.hosts.map((h) => h.toLowerCase()));
43
- const checks = [`if(${hosts}.indexOf(location.hostname.toLowerCase())===-1)return;`];
44
- if (options.skipPaths?.length) {
45
- checks.push(`var p=location.pathname;if(${inlineJson(options.skipPaths)}.some(function(s){return p===s||p.indexOf(s.replace(/\\/$/,"")+"/")===0}))return;`);
46
- }
47
- if (options.consentCookie) {
48
- const pair = options.consentCookie.value === undefined ? null : `${options.consentCookie.name}=${options.consentCookie.value}`;
49
- checks.push(`var k=document.cookie.split(/;\\s*/);if(!k.some(function(c){return ${pair === null ? `c.split("=")[0]===${inlineJson(options.consentCookie.name)}` : `c===${inlineJson(pair)}`}}))return;`);
59
+ return `(function(){${gateChecks(options)}var s=document.createElement("script");s.async=true;s.src="https://www.googletagmanager.com/gtag/js?id="+${id};document.head.appendChild(s);window.dataLayer=window.dataLayer||[];function gtag(){window.dataLayer.push(arguments);}window.gtag=gtag;gtag("js",new Date());gtag("config",${id});})();`;
60
+ }
61
+ /**
62
+ * Google Tag Manager bootstrap with the same gates as `analyticsScript`: only
63
+ * the listed hosts load gtm.js, so local dev and previews never fire tags.
64
+ */
65
+ export function tagManagerScript(options) {
66
+ if (!/^GTM-[A-Z0-9]+$/.test(options.containerId)) {
67
+ throw new Error(`Not a Tag Manager container id: ${options.containerId}`);
50
68
  }
51
- return `(function(){${checks.join("")}var s=document.createElement("script");s.async=true;s.src="https://www.googletagmanager.com/gtag/js?id="+${id};document.head.appendChild(s);window.dataLayer=window.dataLayer||[];function gtag(){window.dataLayer.push(arguments);}window.gtag=gtag;gtag("js",new Date());gtag("config",${id});})();`;
69
+ const id = inlineJson(options.containerId);
70
+ return `(function(){${gateChecks(options)}window.dataLayer=window.dataLayer||[];window.dataLayer.push({"gtm.start":new Date().getTime(),event:"gtm.js"});var s=document.createElement("script");s.async=true;s.src="https://www.googletagmanager.com/gtm.js?id="+${id};document.head.appendChild(s);})();`;
52
71
  }
53
72
  //# sourceMappingURL=scripts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"scripts.js","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;SACzB,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC;SAC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C,KAAK,IAAI,CAAC;CACjD;AAcD,gEAAgE;AAChE,wBAAgB,WAAW,IAAI,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAU3D;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI,CAG5E;AAED,wEAAwE;AACxE,wBAAsB,UAAU,CAAC,CAAC,EAChC,IAAI,EAAE,MAAM,EACZ,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,KAAK,IAAI,CAAC,GACrC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAUnB;AAED,wGAAwG;AACxG,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAO5E;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAazE;AAED,gHAAgH;AAChH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI;IACtD,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACzC,GAAG,CACD,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,GACnC,OAAO,CAAC,IAAI,CAAC,CAAC;CAClB,CAcA"}
package/dist/workers.js CHANGED
@@ -13,7 +13,8 @@ const WORKERS_MODULE = "cloudflare:workers";
13
13
  let modulePromise = null;
14
14
  let override;
15
15
  function processEnv() {
16
- return globalThis.process?.env ?? {};
16
+ return (globalThis
17
+ .process?.env ?? {});
17
18
  }
18
19
  /** The `cloudflare:workers` module, or null outside workerd. */
19
20
  export function loadWorkers() {
@@ -1 +1 @@
1
- {"version":3,"file":"workers.js","sourceRoot":"","sources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,WAAW,EAAE,CAAC;IAChC,MAAM,WAAW,GAAG,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9D,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,OAAO,UAAU,EAAE,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC;AACzC,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,IAAsB;IACxD,MAAM,GAAG,GAAG,MAAM,WAAW,EAAE,CAAC;IAChC,IAAI,GAAG,EAAE,SAAS,EAAE,CAAC;QACnB,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;QACpB,OAAO;IACT,CAAC;IACD,2EAA2E;IAC3E,oCAAoC;IACpC,IAAI,CAAC;QACH,MAAM,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,uCAAuC,EAAE,KAAK,CAAC,CAAC;IAChE,CAAC;AACH,CAAC;AAED,gHAAgH;AAChH,MAAM,UAAU,aAAa,CAAC,KAAc;IAQ1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAChD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,SAAS,GAAG,KAIjB,CAAC;IACF,OAAO,CACL,OAAO,SAAS,CAAC,GAAG,KAAK,UAAU;QACnC,OAAO,SAAS,CAAC,GAAG,KAAK,UAAU;QACnC,OAAO,SAAS,CAAC,eAAe,KAAK,UAAU,CAChD,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workers-start",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "The parts every TanStack Start app on Cloudflare Workers ends up writing: Markdown for agents on the same URL, a head helper that stops share cards leaking between pages, lazy Workers bindings, and a check that no local secret ships in the build.",
5
5
  "license": "MIT",
6
6
  "author": "Ryan Ghods",
@@ -51,7 +51,6 @@
51
51
  "import": "./dist/check-bundle.js",
52
52
  "default": "./dist/check-bundle.js"
53
53
  },
54
- "./biome": "./biome.preset.json",
55
54
  "./accept": {
56
55
  "types": "./dist/accept.d.ts",
57
56
  "import": "./dist/accept.js",
@@ -65,7 +64,6 @@
65
64
  "files": [
66
65
  "dist",
67
66
  "src",
68
- "biome.preset.json",
69
67
  "README.md",
70
68
  "CHANGELOG.md",
71
69
  "LICENSE"
@@ -80,7 +78,8 @@
80
78
  "format": "biome check --write",
81
79
  "test": "npm run build && vitest run",
82
80
  "check": "npm run lint && npm run typecheck && npm run build && vitest run",
83
- "prepack": "npm run build"
81
+ "prepack": "npm run build",
82
+ "prepare": "git config core.hooksPath .githooks || true"
84
83
  },
85
84
  "publishConfig": {
86
85
  "access": "public"
package/src/accept.ts CHANGED
@@ -49,9 +49,17 @@ export function quality(
49
49
  let specificity = -1;
50
50
  if (range.type === type && range.subtype === subtype) {
51
51
  specificity = 2;
52
- } else if (!options.exactOnly && range.type === type && range.subtype === "*") {
52
+ } else if (
53
+ !options.exactOnly &&
54
+ range.type === type &&
55
+ range.subtype === "*"
56
+ ) {
53
57
  specificity = 1;
54
- } else if (!options.exactOnly && range.type === "*" && range.subtype === "*") {
58
+ } else if (
59
+ !options.exactOnly &&
60
+ range.type === "*" &&
61
+ range.subtype === "*"
62
+ ) {
55
63
  specificity = 0;
56
64
  }
57
65
  if (specificity > best) {
@@ -7,7 +7,11 @@
7
7
  */
8
8
 
9
9
  import { relative, resolve } from "node:path";
10
- import { checkBundle, DEFAULT_PUBLIC_PREFIXES, DEFAULT_SKIP } from "./check-bundle.js";
10
+ import {
11
+ checkBundle,
12
+ DEFAULT_PUBLIC_PREFIXES,
13
+ DEFAULT_SKIP,
14
+ } from "./check-bundle.js";
11
15
 
12
16
  const USAGE = `Usage: workers-start-check-bundle [options]
13
17
 
@@ -92,15 +96,21 @@ function main(): void {
92
96
  });
93
97
 
94
98
  if (result.leaked.length === 0) {
95
- console.log(` ok none of ${result.envValues} local env value(s) appear in ${result.files} built file(s)`);
99
+ console.log(
100
+ ` ok none of ${result.envValues} local env value(s) appear in ${result.files} built file(s)`,
101
+ );
96
102
  return;
97
103
  }
98
104
 
99
- console.error(`\nRefusing to ship: the build contains the value of ${result.leaked.length} local secret(s):\n`);
105
+ console.error(
106
+ `\nRefusing to ship: the build contains the value of ${result.leaked.length} local secret(s):\n`,
107
+ );
100
108
  for (const key of result.leaked) {
101
109
  console.error(` ${key}`);
102
110
  }
103
- const where = dists.map((dist) => `${relative(process.cwd(), dist) || "."}/`).join(", ");
111
+ const where = dists
112
+ .map((dist) => `${relative(process.cwd(), dist) || "."}/`)
113
+ .join(", ");
104
114
  console.error(
105
115
  `\n Find where it is read at build time (import.meta.env, define, a module-scope\n process.env read) under ${where} and fix that. If the value is meant to be\n public, pass --allow <KEY> or --public-prefix <PREFIX>.\n`,
106
116
  );
@@ -110,6 +120,8 @@ function main(): void {
110
120
  try {
111
121
  main();
112
122
  } catch (error) {
113
- console.error(`\n ${error instanceof Error ? error.message : String(error)}\n`);
123
+ console.error(
124
+ `\n ${error instanceof Error ? error.message : String(error)}\n`,
125
+ );
114
126
  process.exit(1);
115
127
  }
@@ -27,7 +27,13 @@ const ENV_FILE = /^(\.env(\..+)?|\.dev\.vars(\..+)?)$/;
27
27
  const NOT_SECRETS = /\.(example|sample|template|tpl)$/;
28
28
  const KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/;
29
29
  const INLINE_COMMENT = /\s+#.*$/;
30
- const ESCAPES: Record<string, string> = { n: "\n", r: "\r", t: "\t", '"': '"', "\\": "\\" };
30
+ const ESCAPES: Record<string, string> = {
31
+ n: "\n",
32
+ r: "\r",
33
+ t: "\t",
34
+ '"': '"',
35
+ "\\": "\\",
36
+ };
31
37
 
32
38
  /**
33
39
  * KEY=value pairs from a dotenv file, parsed the way dotenv does: `#`
@@ -54,7 +60,12 @@ export function parseEnvFile(source: string): [string, string][] {
54
60
  }
55
61
  const end = closingQuoteIndex(body, quote);
56
62
  raw = end === -1 ? body : body.slice(0, end);
57
- pairs.push([key, quote === '"' ? raw.replace(/\\(.)/g, (m, c: string) => ESCAPES[c] ?? m) : raw]);
63
+ pairs.push([
64
+ key,
65
+ quote === '"'
66
+ ? raw.replace(/\\(.)/g, (m, c: string) => ESCAPES[c] ?? m)
67
+ : raw,
68
+ ]);
58
69
  } else {
59
70
  pairs.push([key, raw.replace(INLINE_COMMENT, "").trim()]);
60
71
  }
@@ -97,14 +108,21 @@ export interface LeakOptions {
97
108
  }
98
109
 
99
110
  /** The env keys whose values appear, in any encoding, in any of the given file contents. */
100
- export function leakedKeys(pairs: [string, string][], contents: string[], options: LeakOptions = {}): string[] {
111
+ export function leakedKeys(
112
+ pairs: [string, string][],
113
+ contents: string[],
114
+ options: LeakOptions = {},
115
+ ): string[] {
101
116
  const publicPrefixes = options.publicPrefixes ?? DEFAULT_PUBLIC_PREFIXES;
102
117
  const leaked = new Set<string>();
103
118
  for (const [key, value] of pairs) {
104
119
  if (value.length < MIN_SECRET_LENGTH || value.startsWith("op://")) {
105
120
  continue;
106
121
  }
107
- if (options.allow?.includes(key) || publicPrefixes.some((prefix) => key.startsWith(prefix))) {
122
+ if (
123
+ options.allow?.includes(key) ||
124
+ publicPrefixes.some((prefix) => key.startsWith(prefix))
125
+ ) {
108
126
  continue;
109
127
  }
110
128
  const forms = encodings(value);
@@ -116,7 +134,9 @@ export function leakedKeys(pairs: [string, string][], contents: string[], option
116
134
  }
117
135
 
118
136
  /** Every KEY=value pair in the local env files of one or more directories. */
119
- export function localEnvPairs(dirs: string | readonly string[]): [string, string][] {
137
+ export function localEnvPairs(
138
+ dirs: string | readonly string[],
139
+ ): [string, string][] {
120
140
  return (typeof dirs === "string" ? [dirs] : dirs).flatMap((dir) =>
121
141
  readdirSync(dir)
122
142
  .filter((name) => ENV_FILE.test(name) && !NOT_SECRETS.test(name))
@@ -129,7 +149,10 @@ export function localEnvPairs(dirs: string | readonly string[]): [string, string
129
149
  * walk never loops or leaves the directory. `skip` holds paths relative to
130
150
  * `dir`, with forward slashes.
131
151
  */
132
- export function listFiles(dir: string, skip: readonly string[] = DEFAULT_SKIP): string[] {
152
+ export function listFiles(
153
+ dir: string,
154
+ skip: readonly string[] = DEFAULT_SKIP,
155
+ ): string[] {
133
156
  const files: string[] = [];
134
157
  const walk = (current: string): void => {
135
158
  for (const name of readdirSync(current)) {
@@ -140,7 +163,10 @@ export function listFiles(dir: string, skip: readonly string[] = DEFAULT_SKIP):
140
163
  }
141
164
  if (stat.isDirectory()) {
142
165
  walk(path);
143
- } else if (stat.isFile() && !skip.includes(relative(dir, path).split(sep).join("/"))) {
166
+ } else if (
167
+ stat.isFile() &&
168
+ !skip.includes(relative(dir, path).split(sep).join("/"))
169
+ ) {
144
170
  files.push(path);
145
171
  }
146
172
  }
@@ -154,7 +180,8 @@ export function readBuilt(path: string): string {
154
180
  const bytes = readFileSync(path);
155
181
  try {
156
182
  if (path.endsWith(".gz")) return gunzipSync(bytes).toString("latin1");
157
- if (path.endsWith(".br")) return brotliDecompressSync(bytes).toString("latin1");
183
+ if (path.endsWith(".br"))
184
+ return brotliDecompressSync(bytes).toString("latin1");
158
185
  } catch {
159
186
  // Not really compressed; scan the bytes as they are.
160
187
  }
@@ -192,7 +219,9 @@ export function checkBundle(
192
219
  }
193
220
  }
194
221
  const pairs = localEnvPairs(envDirs);
195
- const files = dirs.flatMap((dir) => listFiles(dir, options.skip ?? DEFAULT_SKIP));
222
+ const files = dirs.flatMap((dir) =>
223
+ listFiles(dir, options.skip ?? DEFAULT_SKIP),
224
+ );
196
225
  const leaked = leakedKeys(pairs, files.map(readBuilt), options);
197
226
  return { envValues: pairs.length, files: files.length, leaked };
198
227
  }
package/src/entry.ts CHANGED
@@ -17,7 +17,11 @@ import { parseAccept, quality } from "./accept.js";
17
17
  type MaybePromise<T> = T | Promise<T>;
18
18
 
19
19
  /** What a Markdown renderer returns: a body, a body with a status, or null to serve HTML. */
20
- export type MarkdownResult = string | { body: string; status?: number } | null | undefined;
20
+ export type MarkdownResult =
21
+ | string
22
+ | { body: string; status?: number }
23
+ | null
24
+ | undefined;
21
25
 
22
26
  /** What the Markdown renderer can reach besides the path and request. */
23
27
  export interface MarkdownPage {
@@ -40,7 +44,11 @@ export interface EntryOptions {
40
44
  * served. `page.html()` renders the same request through the handler as
41
45
  * HTML, for a renderer that converts the page instead of building it.
42
46
  */
43
- markdown?: (path: string, request: Request, page: MarkdownPage) => MaybePromise<MarkdownResult>;
47
+ markdown?: (
48
+ path: string,
49
+ request: Request,
50
+ page: MarkdownPage,
51
+ ) => MaybePromise<MarkdownResult>;
44
52
  /**
45
53
  * Path prefixes that only accept GET, HEAD and OPTIONS. Matched by segment,
46
54
  * case-insensitively, after decoding: `/api` covers `/api`, `/api/x` and
@@ -54,16 +62,24 @@ export interface EntryOptions {
54
62
  /** Last-segment extensions that mark a file rather than a page. */
55
63
  const FILE_EXTENSION =
56
64
  /\.(?:js|mjs|cjs|css|map|json|xml|txt|md|csv|ico|png|jpe?g|gif|svg|webp|avif|bmp|woff2?|ttf|otf|eot|pdf|mp[34]|webm|wav|ogg|zip|gz|br|wasm|webmanifest|html?|rss|atom)$/i;
57
- const DEV_INTERNALS = ["/@vite/", "/@fs/", "/@id/", "/@react-refresh", "/node_modules/"];
65
+ const DEV_INTERNALS = [
66
+ "/@vite/",
67
+ "/@fs/",
68
+ "/@id/",
69
+ "/@react-refresh",
70
+ "/node_modules/",
71
+ ];
58
72
  const DUPLICATE_SLASHES = /\/{2,}/g;
59
73
  const TRAILING_SLASHES = /\/+$/;
60
74
 
61
- export const MARKDOWN_HEADERS: Readonly<Record<string, string>> = Object.freeze({
62
- "content-type": "text/markdown; charset=utf-8",
63
- vary: "Accept",
64
- // A Markdown body is a second representation of a page, not a page of its own.
65
- "x-robots-tag": "noindex",
66
- });
75
+ export const MARKDOWN_HEADERS: Readonly<Record<string, string>> = Object.freeze(
76
+ {
77
+ "content-type": "text/markdown; charset=utf-8",
78
+ vary: "Accept",
79
+ // A Markdown body is a second representation of a page, not a page of its own.
80
+ "x-robots-tag": "noindex",
81
+ },
82
+ );
67
83
 
68
84
  /**
69
85
  * True when the client names text/markdown with q > 0 and rates it at least
@@ -108,11 +124,17 @@ export function underPrefix(path: string, prefix: string): boolean {
108
124
  * `.js` or `.xml` on the last segment. A dotted slug like `/blog/node.js-tips`
109
125
  * is still a page.
110
126
  */
111
- export function defaultIsPage(path: string, readOnlyPrefixes: readonly string[] = ["/api"]): boolean {
127
+ export function defaultIsPage(
128
+ path: string,
129
+ readOnlyPrefixes: readonly string[] = ["/api"],
130
+ ): boolean {
112
131
  if (readOnlyPrefixes.some((prefix) => underPrefix(path, prefix))) {
113
132
  return false;
114
133
  }
115
- if (path.startsWith("/_") || DEV_INTERNALS.some((prefix) => path.startsWith(prefix))) {
134
+ if (
135
+ path.startsWith("/_") ||
136
+ DEV_INTERNALS.some((prefix) => path.startsWith(prefix))
137
+ ) {
116
138
  return false;
117
139
  }
118
140
  return !FILE_EXTENSION.test(path);
@@ -132,10 +154,17 @@ export function mergeVary(existing: string | null, token: string): string {
132
154
 
133
155
  const NULL_BODY_STATUS = new Set([101, 204, 205, 304]);
134
156
 
135
- function markdownResponse(result: Exclude<MarkdownResult, null | undefined>, head: boolean): Response {
136
- const { body, status = 200 } = typeof result === "string" ? { body: result } : result;
157
+ function markdownResponse(
158
+ result: Exclude<MarkdownResult, null | undefined>,
159
+ head: boolean,
160
+ ): Response {
161
+ const { body, status = 200 } =
162
+ typeof result === "string" ? { body: result } : result;
137
163
  const noBody = head || NULL_BODY_STATUS.has(status);
138
- return new Response(noBody ? null : body, { status, headers: MARKDOWN_HEADERS });
164
+ return new Response(noBody ? null : body, {
165
+ status,
166
+ headers: MARKDOWN_HEADERS,
167
+ });
139
168
  }
140
169
 
141
170
  function withAcceptHtml(request: Request): Request {
@@ -151,14 +180,19 @@ function withVaryAccept(response: Response): Response {
151
180
  }
152
181
  const headers = new Headers(response.headers);
153
182
  headers.set("vary", vary);
154
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
183
+ return new Response(response.body, {
184
+ status: response.status,
185
+ statusText: response.statusText,
186
+ headers,
187
+ });
155
188
  }
156
189
 
157
190
  export function createEntry(options: EntryOptions): {
158
191
  fetch(request: Request, ...rest: unknown[]): Promise<Response>;
159
192
  } {
160
193
  const readOnlyPrefixes = options.readOnlyPrefixes ?? ["/api"];
161
- const isPage = options.isPage ?? ((path: string) => defaultIsPage(path, readOnlyPrefixes));
194
+ const isPage =
195
+ options.isPage ?? ((path: string) => defaultIsPage(path, readOnlyPrefixes));
162
196
 
163
197
  return {
164
198
  async fetch(request, ...rest) {
@@ -168,7 +202,10 @@ export function createEntry(options: EntryOptions): {
168
202
 
169
203
  if (readOnlyPrefixes.some((prefix) => underPrefix(path, prefix))) {
170
204
  if (method === "OPTIONS") {
171
- return new Response(null, { status: 204, headers: { allow: "GET, HEAD, OPTIONS" } });
205
+ return new Response(null, {
206
+ status: 204,
207
+ headers: { allow: "GET, HEAD, OPTIONS" },
208
+ });
172
209
  }
173
210
  if (!isRead) {
174
211
  return Response.json(
@@ -186,17 +223,23 @@ export function createEntry(options: EntryOptions): {
186
223
  if (options.markdown && wantsMarkdown(request)) {
187
224
  try {
188
225
  const result = await options.markdown(path, request, {
189
- html: async () => options.handler.fetch(withAcceptHtml(request), ...rest),
226
+ html: async () =>
227
+ options.handler.fetch(withAcceptHtml(request), ...rest),
190
228
  });
191
229
  if (result !== null && result !== undefined) {
192
230
  return markdownResponse(result, method === "HEAD");
193
231
  }
194
232
  } catch (error) {
195
- console.error("workers-start: markdown renderer failed, serving HTML", error);
233
+ console.error(
234
+ "workers-start: markdown renderer failed, serving HTML",
235
+ error,
236
+ );
196
237
  }
197
238
  }
198
239
 
199
- const pageRequest = acceptsHtml(request) ? request : withAcceptHtml(request);
240
+ const pageRequest = acceptsHtml(request)
241
+ ? request
242
+ : withAcceptHtml(request);
200
243
  const response = await options.handler.fetch(pageRequest, ...rest);
201
244
  return options.markdown ? withVaryAccept(response) : response;
202
245
  },
package/src/head.ts CHANGED
@@ -88,7 +88,12 @@ export interface PageSeo {
88
88
  * `link rel="alternate"` entries after the canonical: language versions
89
89
  * with `hreflang`, or feeds with `type`. `href` is a path or URL.
90
90
  */
91
- alternates?: { href: string; hreflang?: string; type?: string; title?: string }[];
91
+ alternates?: {
92
+ href: string;
93
+ hreflang?: string;
94
+ type?: string;
95
+ title?: string;
96
+ }[];
92
97
  /** Extra links, appended last as given. */
93
98
  links?: HeadLink[];
94
99
  /**
@@ -98,7 +103,10 @@ export interface PageSeo {
98
103
  jsonLd?: object | object[];
99
104
  }
100
105
 
101
- export type MetaTag = { title: string } | { name: string; content: string } | { property: string; content: string };
106
+ export type MetaTag =
107
+ | { title: string }
108
+ | { name: string; content: string }
109
+ | { property: string; content: string };
102
110
 
103
111
  export interface HeadLink {
104
112
  rel: string;
@@ -155,7 +163,8 @@ export function createPageHead(site: SiteHead): {
155
163
  absoluteUrl: (path: string) => string;
156
164
  } {
157
165
  const origin = new URL(site.url).origin;
158
- const template = site.titleTemplate ?? ((title: string) => `${title} | ${site.name}`);
166
+ const template =
167
+ site.titleTemplate ?? ((title: string) => `${title} | ${site.name}`);
159
168
 
160
169
  /** `/` maps to the bare origin; anything else resolves against it, so absolute URLs pass through. */
161
170
  const absoluteUrl = (path: string): string => {
@@ -163,7 +172,9 @@ export function createPageHead(site: SiteHead): {
163
172
  return origin;
164
173
  }
165
174
  const resolved = new URL(
166
- path.startsWith("/") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(path) ? path : `/${path}`,
175
+ path.startsWith("/") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(path)
176
+ ? path
177
+ : `/${path}`,
167
178
  `${origin}/`,
168
179
  );
169
180
  return resolved.href;
@@ -175,7 +186,9 @@ export function createPageHead(site: SiteHead): {
175
186
  const socialDescription = seo.socialDescription ?? seo.description;
176
187
  const imageInput = seo.image ?? site.defaultImage;
177
188
  const image: PageImage | undefined =
178
- typeof imageInput === "string" ? { url: imageInput, ...seo.imageSize } : imageInput;
189
+ typeof imageInput === "string"
190
+ ? { url: imageInput, ...seo.imageSize }
191
+ : imageInput;
179
192
  const imageUrl = image ? absoluteUrl(image.url) : undefined;
180
193
 
181
194
  const meta: MetaTag[] = [
@@ -202,43 +215,80 @@ export function createPageHead(site: SiteHead): {
202
215
  );
203
216
  if (image && imageUrl) {
204
217
  meta.push({ property: "og:image", content: imageUrl });
205
- if (image.type) meta.push({ property: "og:image:type", content: image.type });
206
- if (image.width) meta.push({ property: "og:image:width", content: String(image.width) });
207
- if (image.height) meta.push({ property: "og:image:height", content: String(image.height) });
208
- if (image.alt) meta.push({ property: "og:image:alt", content: image.alt });
218
+ if (image.type)
219
+ meta.push({ property: "og:image:type", content: image.type });
220
+ if (image.width)
221
+ meta.push({ property: "og:image:width", content: String(image.width) });
222
+ if (image.height)
223
+ meta.push({
224
+ property: "og:image:height",
225
+ content: String(image.height),
226
+ });
227
+ if (image.alt)
228
+ meta.push({ property: "og:image:alt", content: image.alt });
209
229
  }
210
230
  meta.push({ property: "og:type", content: seo.type ?? "website" });
211
- if (seo.published) meta.push({ property: "article:published_time", content: seo.published });
212
- if (seo.modified) meta.push({ property: "article:modified_time", content: seo.modified });
213
- for (const author of seo.authors ?? []) meta.push({ property: "article:author", content: author });
214
- for (const tag of seo.tags ?? []) meta.push({ property: "article:tag", content: tag });
215
- if (seo.section) meta.push({ property: "article:section", content: seo.section });
216
-
217
- meta.push({ name: "twitter:card", content: imageUrl ? "summary_large_image" : "summary" });
218
- if (site.twitterSite) meta.push({ name: "twitter:site", content: site.twitterSite });
219
- if (site.twitterCreator) meta.push({ name: "twitter:creator", content: site.twitterCreator });
231
+ if (seo.published)
232
+ meta.push({ property: "article:published_time", content: seo.published });
233
+ if (seo.modified)
234
+ meta.push({ property: "article:modified_time", content: seo.modified });
235
+ for (const author of seo.authors ?? [])
236
+ meta.push({ property: "article:author", content: author });
237
+ for (const tag of seo.tags ?? [])
238
+ meta.push({ property: "article:tag", content: tag });
239
+ if (seo.section)
240
+ meta.push({ property: "article:section", content: seo.section });
241
+
242
+ meta.push({
243
+ name: "twitter:card",
244
+ content: imageUrl ? "summary_large_image" : "summary",
245
+ });
246
+ if (site.twitterSite)
247
+ meta.push({ name: "twitter:site", content: site.twitterSite });
248
+ if (site.twitterCreator)
249
+ meta.push({ name: "twitter:creator", content: site.twitterCreator });
220
250
  meta.push(
221
251
  { name: "twitter:title", content: socialTitle },
222
- { name: "twitter:description", content: seo.twitterDescription ?? socialDescription },
252
+ {
253
+ name: "twitter:description",
254
+ content: seo.twitterDescription ?? socialDescription,
255
+ },
223
256
  );
224
257
  if (imageUrl) {
225
258
  meta.push({ name: "twitter:image", content: imageUrl });
226
- if (image?.alt) meta.push({ name: "twitter:image:alt", content: image.alt });
259
+ if (image?.alt)
260
+ meta.push({ name: "twitter:image:alt", content: image.alt });
227
261
  }
228
262
  const pageKeys = new Set((seo.meta ?? []).map(metaKey));
229
- meta.push(...(site.meta ?? []).filter((tag) => !pageKeys.has(metaKey(tag))));
263
+ meta.push(
264
+ ...(site.meta ?? []).filter((tag) => !pageKeys.has(metaKey(tag))),
265
+ );
230
266
  meta.push(...(seo.meta ?? []));
231
267
 
232
268
  const links: HeadLink[] =
233
- seo.canonical === false ? [] : [{ rel: "canonical", href: seo.canonical ? absoluteUrl(seo.canonical) : url }];
269
+ seo.canonical === false
270
+ ? []
271
+ : [
272
+ {
273
+ rel: "canonical",
274
+ href: seo.canonical ? absoluteUrl(seo.canonical) : url,
275
+ },
276
+ ];
234
277
  for (const alternate of seo.alternates ?? []) {
235
- links.push({ rel: "alternate", ...alternate, href: absoluteUrl(alternate.href) });
278
+ links.push({
279
+ rel: "alternate",
280
+ ...alternate,
281
+ href: absoluteUrl(alternate.href),
282
+ });
236
283
  }
237
284
  for (const author of site.authors ?? []) {
238
- if (author.url) links.push({ rel: "author", href: absoluteUrl(author.url) });
285
+ if (author.url)
286
+ links.push({ rel: "author", href: absoluteUrl(author.url) });
239
287
  }
240
288
  links.push(...(seo.links ?? []));
241
- return seo.jsonLd ? { meta, links, scripts: [jsonLdScript(seo.jsonLd)] } : { meta, links };
289
+ return seo.jsonLd
290
+ ? { meta, links, scripts: [jsonLdScript(seo.jsonLd)] }
291
+ : { meta, links };
242
292
  };
243
293
 
244
294
  return { pageHead, absoluteUrl };