workers-start 0.0.0-stage → 0.1.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/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +118 -2
- package/biome.preset.json +29 -0
- package/dist/check-bundle-cli.d.ts +9 -0
- package/dist/check-bundle-cli.d.ts.map +1 -0
- package/dist/check-bundle-cli.js +61 -0
- package/dist/check-bundle-cli.js.map +1 -0
- package/dist/check-bundle.d.ts +26 -0
- package/dist/check-bundle.d.ts.map +1 -0
- package/dist/check-bundle.js +69 -0
- package/dist/check-bundle.js.map +1 -0
- package/dist/entry.d.ts +48 -0
- package/dist/entry.d.ts.map +1 -0
- package/dist/entry.js +79 -0
- package/dist/entry.js.map +1 -0
- package/dist/head.d.ts +71 -0
- package/dist/head.d.ts.map +1 -0
- package/dist/head.js +57 -0
- package/dist/head.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/scripts.d.ts +31 -0
- package/dist/scripts.d.ts.map +1 -0
- package/dist/scripts.js +28 -0
- package/dist/scripts.js.map +1 -0
- package/dist/workers.d.ts +37 -0
- package/dist/workers.d.ts.map +1 -0
- package/dist/workers.js +84 -0
- package/dist/workers.js.map +1 -0
- package/package.json +80 -4
- package/src/check-bundle-cli.ts +64 -0
- package/src/check-bundle.ts +85 -0
- package/src/entry.ts +122 -0
- package/src/head.ts +125 -0
- package/src/index.ts +8 -0
- package/src/scripts.ts +45 -0
- package/src/workers.ts +101 -0
package/dist/head.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-page head tags in the shape a TanStack Router `head()` returns.
|
|
3
|
+
*
|
|
4
|
+
* The router keeps one meta per `name` or `property`, deepest route winning,
|
|
5
|
+
* so any tag a page leaves out falls back to a parent's. This helper writes
|
|
6
|
+
* the full Open Graph and Twitter set for every page so nothing inherits the
|
|
7
|
+
* homepage's share card by accident.
|
|
8
|
+
*/
|
|
9
|
+
export function createPageHead(site) {
|
|
10
|
+
const origin = site.url.replace(/\/+$/, "");
|
|
11
|
+
const template = site.titleTemplate ?? ((title) => `${title} | ${site.name}`);
|
|
12
|
+
const absoluteUrl = (path) => {
|
|
13
|
+
if (/^https?:\/\//.test(path)) {
|
|
14
|
+
return path;
|
|
15
|
+
}
|
|
16
|
+
return path === "/" ? origin : `${origin}${path}`;
|
|
17
|
+
};
|
|
18
|
+
const pageHead = (seo) => {
|
|
19
|
+
const url = absoluteUrl(seo.path);
|
|
20
|
+
const socialTitle = seo.socialTitle ?? seo.title;
|
|
21
|
+
const socialDescription = seo.socialDescription ?? seo.description;
|
|
22
|
+
const imagePath = seo.image ?? site.defaultImage;
|
|
23
|
+
const image = imagePath ? absoluteUrl(imagePath) : undefined;
|
|
24
|
+
const meta = [
|
|
25
|
+
{ title: seo.rawTitle ? seo.title : template(seo.title) },
|
|
26
|
+
{ name: "description", content: seo.description },
|
|
27
|
+
];
|
|
28
|
+
if (seo.noindex) {
|
|
29
|
+
meta.push({ name: "robots", content: "noindex" });
|
|
30
|
+
}
|
|
31
|
+
meta.push({ property: "og:title", content: socialTitle }, { property: "og:description", content: socialDescription }, { property: "og:url", content: url }, { property: "og:site_name", content: site.name }, { property: "og:locale", content: site.locale ?? "en_US" });
|
|
32
|
+
if (image) {
|
|
33
|
+
meta.push({ property: "og:image", content: image });
|
|
34
|
+
}
|
|
35
|
+
if (image && seo.imageSize) {
|
|
36
|
+
meta.push({ property: "og:image:width", content: String(seo.imageSize.width) }, { property: "og:image:height", content: String(seo.imageSize.height) }, { property: "og:image:alt", content: seo.imageSize.alt });
|
|
37
|
+
}
|
|
38
|
+
meta.push({ property: "og:type", content: seo.type ?? "website" });
|
|
39
|
+
if (seo.published) {
|
|
40
|
+
meta.push({ property: "article:published_time", content: seo.published });
|
|
41
|
+
}
|
|
42
|
+
if (seo.modified) {
|
|
43
|
+
meta.push({ property: "article:modified_time", content: seo.modified });
|
|
44
|
+
}
|
|
45
|
+
meta.push({ name: "twitter:card", content: image ? "summary_large_image" : "summary" });
|
|
46
|
+
if (site.twitterCreator) {
|
|
47
|
+
meta.push({ name: "twitter:creator", content: site.twitterCreator });
|
|
48
|
+
}
|
|
49
|
+
meta.push({ name: "twitter:title", content: socialTitle }, { name: "twitter:description", content: seo.twitterDescription ?? socialDescription });
|
|
50
|
+
if (image) {
|
|
51
|
+
meta.push({ name: "twitter:image", content: image });
|
|
52
|
+
}
|
|
53
|
+
return { meta, links: [{ rel: "canonical", href: url }] };
|
|
54
|
+
};
|
|
55
|
+
return { pageHead, absoluteUrl };
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=head.js.map
|
package/dist/head.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"head.js","sourceRoot":"","sources":["../src/head.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAiDH,MAAM,UAAU,cAAc,CAAC,IAAc;IAI3C,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC5C,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,IAAI,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,GAAG,KAAK,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IAEtF,MAAM,WAAW,GAAG,CAAC,IAAY,EAAU,EAAE;QAC3C,IAAI,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,GAAG,IAAI,EAAE,CAAC;IACpD,CAAC,CAAC;IAEF,MAAM,QAAQ,GAAG,CAAC,GAAY,EAAY,EAAE;QAC1C,MAAM,GAAG,GAAG,WAAW,CAA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AI,CACP,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAE,EAC/C,EAAE,IAAI,EAAE,qBAAqB,EAAE,OAAO,EAAE,GAAG,CAAC,kBAAkB,IAAI,iBAAiB,EAAE,CACtF,CAAC;QACF,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QACvD,CAAC;QAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC;IAC5D,CAAC,CAAC;IAEF,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type { EntryOptions, FetchHandler, MarkdownResult } from "./entry.js";
|
|
2
|
+
export { createEntry, defaultIsPage, MARKDOWN_HEADERS, normalizePath, wantsMarkdown } from "./entry.js";
|
|
3
|
+
export type { HeadTags, MetaTag, PageSeo, SiteHead } from "./head.js";
|
|
4
|
+
export { createPageHead } from "./head.js";
|
|
5
|
+
export type { AnalyticsScriptOptions, ThemeScriptOptions } from "./scripts.js";
|
|
6
|
+
export { analyticsScript, themeScript } from "./scripts.js";
|
|
7
|
+
export type { WorkersModule } from "./workers.js";
|
|
8
|
+
export { afterResponse, getBinding, getEnvString, isKvNamespace, loadWorkers, setWorkersModule } from "./workers.js";
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACxG,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,YAAY,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createEntry, defaultIsPage, MARKDOWN_HEADERS, normalizePath, wantsMarkdown } from "./entry.js";
|
|
2
|
+
export { createPageHead } from "./head.js";
|
|
3
|
+
export { analyticsScript, themeScript } from "./scripts.js";
|
|
4
|
+
export { afterResponse, getBinding, getEnvString, isKvNamespace, loadWorkers, setWorkersModule } from "./workers.js";
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAExG,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE5D,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inline scripts for the document head, as strings to put in
|
|
3
|
+
* `dangerouslySetInnerHTML`. Both run before hydration and touch nothing
|
|
4
|
+
* React renders, so they cause no hydration mismatch.
|
|
5
|
+
*/
|
|
6
|
+
export interface ThemeScriptOptions {
|
|
7
|
+
/** localStorage key. Default `theme`. */
|
|
8
|
+
storageKey?: string;
|
|
9
|
+
/** Attribute set on `<html>`. Default `data-theme`. */
|
|
10
|
+
attribute?: string;
|
|
11
|
+
/** Accepted stored values. Default `["light", "dark"]`. */
|
|
12
|
+
values?: string[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Applies a stored theme choice before first paint, so it never flashes the
|
|
16
|
+
* other theme. With no stored choice it does nothing, and CSS
|
|
17
|
+
* `color-scheme: light dark` follows the operating system.
|
|
18
|
+
*/
|
|
19
|
+
export declare function themeScript(options?: ThemeScriptOptions): string;
|
|
20
|
+
export interface AnalyticsScriptOptions {
|
|
21
|
+
/** GA4 measurement id, `G-…`. Public; safe in the bundle. */
|
|
22
|
+
measurementId: string;
|
|
23
|
+
/** Hostnames that report. Every other host (localhost, previews) loads nothing. */
|
|
24
|
+
hosts: string[];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
|
|
28
|
+
* preview deploys never fetch gtag.js or land in the production property.
|
|
29
|
+
*/
|
|
30
|
+
export declare function analyticsScript({ measurementId, hosts }: AnalyticsScriptOptions): string;
|
|
31
|
+
//# sourceMappingURL=scripts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scripts.d.ts","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,WAAW,kBAAkB;IACjC,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAKpE;AAED,MAAM,WAAW,sBAAsB;IACrC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,mFAAmF;IACnF,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,EAAE,sBAAsB,GAAG,MAAM,CAMxF"}
|
package/dist/scripts.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inline scripts for the document head, as strings to put in
|
|
3
|
+
* `dangerouslySetInnerHTML`. Both run before hydration and touch nothing
|
|
4
|
+
* React renders, so they cause no hydration mismatch.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Applies a stored theme choice before first paint, so it never flashes the
|
|
8
|
+
* other theme. With no stored choice it does nothing, and CSS
|
|
9
|
+
* `color-scheme: light dark` follows the operating system.
|
|
10
|
+
*/
|
|
11
|
+
export function themeScript(options = {}) {
|
|
12
|
+
const key = JSON.stringify(options.storageKey ?? "theme");
|
|
13
|
+
const attribute = JSON.stringify(options.attribute ?? "data-theme");
|
|
14
|
+
const values = JSON.stringify(options.values ?? ["light", "dark"]);
|
|
15
|
+
return `try{var t=localStorage.getItem(${key});if(${values}.indexOf(t)!==-1){document.documentElement.setAttribute(${attribute},t)}}catch(e){}`;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
|
|
19
|
+
* preview deploys never fetch gtag.js or land in the production property.
|
|
20
|
+
*/
|
|
21
|
+
export function analyticsScript({ measurementId, hosts }) {
|
|
22
|
+
if (!/^G-[A-Z0-9]+$/.test(measurementId)) {
|
|
23
|
+
throw new Error(`Not a GA4 measurement id: ${measurementId}`);
|
|
24
|
+
}
|
|
25
|
+
const id = JSON.stringify(measurementId);
|
|
26
|
+
return `(function(){if(${JSON.stringify(hosts)}.indexOf(location.hostname)===-1)return;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});})();`;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=scripts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scripts.js","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAWH;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,OAAO,GAAuB,EAAE;IAC1D,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,CAAC;IAC1D,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,SAAS,IAAI,YAAY,CAAC,CAAC;IACpE,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;IACnE,OAAO,kCAAkC,GAAG,QAAQ,MAAM,2DAA2D,SAAS,iBAAiB,CAAC;AAClJ,CAAC;AASD;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,EAAE,aAAa,EAAE,KAAK,EAA0B;IAC9E,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CAAC,6BAA6B,aAAa,EAAE,CAAC,CAAC;IAChE,CAAC;IACD,MAAM,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;IACzC,OAAO,kBAAkB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,oJAAoJ,EAAE,8KAA8K,EAAE,SAAS,CAAC;AAChY,CAAC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lazy access to `cloudflare:workers` (env bindings and `waitUntil`) from code
|
|
3
|
+
* that also runs in vitest, Node scripts and the client bundle.
|
|
4
|
+
*
|
|
5
|
+
* The module is imported through a variable specifier, so neither Vite nor
|
|
6
|
+
* vitest tries to resolve it, and only on first use. Outside workerd the
|
|
7
|
+
* import fails and every helper here degrades: bindings are null, env reads
|
|
8
|
+
* fall back to `process.env`, and `afterResponse` awaits the work in place.
|
|
9
|
+
*/
|
|
10
|
+
export interface WorkersModule {
|
|
11
|
+
env: Record<string, unknown>;
|
|
12
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
13
|
+
}
|
|
14
|
+
/** The `cloudflare:workers` module, or null outside workerd. */
|
|
15
|
+
export declare function loadWorkers(): Promise<WorkersModule | null>;
|
|
16
|
+
/**
|
|
17
|
+
* Test hook: make `loadWorkers` return this module (or null). Pass `undefined`
|
|
18
|
+
* to go back to the real import.
|
|
19
|
+
*/
|
|
20
|
+
export declare function setWorkersModule(mod: WorkersModule | null | undefined): void;
|
|
21
|
+
/** A binding by name, or null when it is missing or fails the guard. */
|
|
22
|
+
export declare function getBinding<T>(name: string, guard?: (value: unknown) => value is T): Promise<T | null>;
|
|
23
|
+
/** A secret or var from the Worker env, falling back to `process.env`. Empty strings count as unset. */
|
|
24
|
+
export declare function getEnvString(name: string): Promise<string | undefined>;
|
|
25
|
+
/**
|
|
26
|
+
* Hand work to the runtime to finish after the response is sent. Outside
|
|
27
|
+
* workerd there is nobody to hand it to, so this awaits it instead.
|
|
28
|
+
*/
|
|
29
|
+
export declare function afterResponse(work: Promise<unknown>): Promise<void>;
|
|
30
|
+
/** True for anything with KV's `get` and `put`. Use as a `getBinding` guard. */
|
|
31
|
+
export declare function isKvNamespace(value: unknown): value is {
|
|
32
|
+
get(key: string): Promise<string | null>;
|
|
33
|
+
put(key: string, value: string, options?: {
|
|
34
|
+
expirationTtl?: number;
|
|
35
|
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M,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtF,CAMA"}
|
package/dist/workers.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lazy access to `cloudflare:workers` (env bindings and `waitUntil`) from code
|
|
3
|
+
* that also runs in vitest, Node scripts and the client bundle.
|
|
4
|
+
*
|
|
5
|
+
* The module is imported through a variable specifier, so neither Vite nor
|
|
6
|
+
* vitest tries to resolve it, and only on first use. Outside workerd the
|
|
7
|
+
* import fails and every helper here degrades: bindings are null, env reads
|
|
8
|
+
* fall back to `process.env`, and `afterResponse` awaits the work in place.
|
|
9
|
+
*/
|
|
10
|
+
const WORKERS_MODULE = "cloudflare:workers";
|
|
11
|
+
let modulePromise = null;
|
|
12
|
+
let override;
|
|
13
|
+
function processEnv() {
|
|
14
|
+
return globalThis.process?.env ?? {};
|
|
15
|
+
}
|
|
16
|
+
function isTestRuntime() {
|
|
17
|
+
const env = processEnv();
|
|
18
|
+
return Boolean(env.VITEST) || env.NODE_ENV === "test";
|
|
19
|
+
}
|
|
20
|
+
/** The `cloudflare:workers` module, or null outside workerd. */
|
|
21
|
+
export function loadWorkers() {
|
|
22
|
+
if (override !== undefined) {
|
|
23
|
+
return Promise.resolve(override);
|
|
24
|
+
}
|
|
25
|
+
if (isTestRuntime()) {
|
|
26
|
+
return Promise.resolve(null);
|
|
27
|
+
}
|
|
28
|
+
if (!modulePromise) {
|
|
29
|
+
modulePromise = import(/* @vite-ignore */ WORKERS_MODULE)
|
|
30
|
+
.then((mod) => mod)
|
|
31
|
+
.catch(() => null);
|
|
32
|
+
}
|
|
33
|
+
return modulePromise;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Test hook: make `loadWorkers` return this module (or null). Pass `undefined`
|
|
37
|
+
* to go back to the real import.
|
|
38
|
+
*/
|
|
39
|
+
export function setWorkersModule(mod) {
|
|
40
|
+
override = mod;
|
|
41
|
+
modulePromise = null;
|
|
42
|
+
}
|
|
43
|
+
/** A binding by name, or null when it is missing or fails the guard. */
|
|
44
|
+
export async function getBinding(name, guard) {
|
|
45
|
+
const mod = await loadWorkers();
|
|
46
|
+
const value = mod?.env[name];
|
|
47
|
+
if (value === undefined || value === null) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (guard && !guard(value)) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
/** A secret or var from the Worker env, falling back to `process.env`. Empty strings count as unset. */
|
|
56
|
+
export async function getEnvString(name) {
|
|
57
|
+
const mod = await loadWorkers();
|
|
58
|
+
const fromBinding = mod?.env[name];
|
|
59
|
+
if (typeof fromBinding === "string" && fromBinding.length > 0) {
|
|
60
|
+
return fromBinding;
|
|
61
|
+
}
|
|
62
|
+
return processEnv()[name] || undefined;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Hand work to the runtime to finish after the response is sent. Outside
|
|
66
|
+
* workerd there is nobody to hand it to, so this awaits it instead.
|
|
67
|
+
*/
|
|
68
|
+
export async function afterResponse(work) {
|
|
69
|
+
const mod = await loadWorkers();
|
|
70
|
+
if (mod?.waitUntil) {
|
|
71
|
+
mod.waitUntil(work);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
await work;
|
|
75
|
+
}
|
|
76
|
+
/** True for anything with KV's `get` and `put`. Use as a `getBinding` guard. */
|
|
77
|
+
export function isKvNamespace(value) {
|
|
78
|
+
if (typeof value !== "object" || value === null) {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
const candidate = value;
|
|
82
|
+
return typeof candidate.get === "function" && typeof candidate.put === "function";
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=workers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workers.js","sourceRoot":"","sources":["../src/workers.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH,MAAM,cAAc,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
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"license": "MIT",
|
|
6
|
+
"author": "Ryan Ghods",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/ryanio/workers-start.git"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"cloudflare",
|
|
13
|
+
"workers",
|
|
14
|
+
"tanstack-start",
|
|
15
|
+
"tanstack",
|
|
16
|
+
"vite",
|
|
17
|
+
"seo",
|
|
18
|
+
"markdown",
|
|
19
|
+
"llms"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./entry": {
|
|
29
|
+
"types": "./dist/entry.d.ts",
|
|
30
|
+
"import": "./dist/entry.js"
|
|
31
|
+
},
|
|
32
|
+
"./head": {
|
|
33
|
+
"types": "./dist/head.d.ts",
|
|
34
|
+
"import": "./dist/head.js"
|
|
35
|
+
},
|
|
36
|
+
"./workers": {
|
|
37
|
+
"types": "./dist/workers.d.ts",
|
|
38
|
+
"import": "./dist/workers.js"
|
|
39
|
+
},
|
|
40
|
+
"./scripts": {
|
|
41
|
+
"types": "./dist/scripts.d.ts",
|
|
42
|
+
"import": "./dist/scripts.js"
|
|
43
|
+
},
|
|
44
|
+
"./check-bundle": {
|
|
45
|
+
"types": "./dist/check-bundle.d.ts",
|
|
46
|
+
"import": "./dist/check-bundle.js"
|
|
47
|
+
},
|
|
48
|
+
"./biome": "./biome.preset.json"
|
|
49
|
+
},
|
|
50
|
+
"bin": {
|
|
51
|
+
"workers-start-check-bundle": "dist/check-bundle-cli.js"
|
|
52
|
+
},
|
|
53
|
+
"files": [
|
|
54
|
+
"dist",
|
|
55
|
+
"src",
|
|
56
|
+
"biome.preset.json",
|
|
57
|
+
"README.md",
|
|
58
|
+
"CHANGELOG.md",
|
|
59
|
+
"LICENSE"
|
|
60
|
+
],
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": ">=20"
|
|
63
|
+
},
|
|
64
|
+
"scripts": {
|
|
65
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/check-bundle-cli.js",
|
|
66
|
+
"typecheck": "tsc --noEmit",
|
|
67
|
+
"lint": "biome check",
|
|
68
|
+
"format": "biome check --write",
|
|
69
|
+
"test": "npm run build && vitest run",
|
|
70
|
+
"check": "npm run lint && npm run typecheck && npm run build && vitest run",
|
|
71
|
+
"prepack": "npm run build"
|
|
72
|
+
},
|
|
73
|
+
"publishConfig": {
|
|
74
|
+
"access": "public"
|
|
75
|
+
},
|
|
76
|
+
"devDependencies": {
|
|
77
|
+
"@biomejs/biome": "^2.6.8",
|
|
78
|
+
"@types/node": "^24.19.2",
|
|
79
|
+
"typescript": "^7.0.2",
|
|
80
|
+
"vitest": "^5.1.0"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* workers-start-check-bundle [--dist dist] [--root .] [--skip name ...]
|
|
4
|
+
*
|
|
5
|
+
* Exits 1 if any local env value appears in a built file. Run it between the
|
|
6
|
+
* build and the deploy.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { relative, resolve } from "node:path";
|
|
10
|
+
import { checkBundle, DEFAULT_SKIP } from "./check-bundle.js";
|
|
11
|
+
|
|
12
|
+
function parseArgs(argv: string[]): { dist: string; root: string; skip: string[] } {
|
|
13
|
+
let dist = "dist";
|
|
14
|
+
let root = ".";
|
|
15
|
+
const skip = [...DEFAULT_SKIP];
|
|
16
|
+
for (let i = 0; i < argv.length; i++) {
|
|
17
|
+
const flag = argv[i];
|
|
18
|
+
const value = argv[i + 1];
|
|
19
|
+
if ((flag === "--dist" || flag === "--root" || flag === "--skip") && value === undefined) {
|
|
20
|
+
throw new Error(`${flag} needs a value`);
|
|
21
|
+
}
|
|
22
|
+
if (flag === "--dist") {
|
|
23
|
+
dist = value as string;
|
|
24
|
+
i++;
|
|
25
|
+
} else if (flag === "--root") {
|
|
26
|
+
root = value as string;
|
|
27
|
+
i++;
|
|
28
|
+
} else if (flag === "--skip") {
|
|
29
|
+
skip.push(value as string);
|
|
30
|
+
i++;
|
|
31
|
+
} else {
|
|
32
|
+
throw new Error(`Unknown argument: ${flag}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { dist, root, skip };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function main(): void {
|
|
39
|
+
const args = parseArgs(process.argv.slice(2));
|
|
40
|
+
const root = resolve(args.root);
|
|
41
|
+
const dist = resolve(root, args.dist);
|
|
42
|
+
const result = checkBundle(root, dist, args.skip);
|
|
43
|
+
|
|
44
|
+
if (result.leaked.length === 0) {
|
|
45
|
+
console.log(` ok none of ${result.envValues} local env value(s) appear in ${result.files} built file(s)`);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
console.error(`\nRefusing to ship: the build contains the value of ${result.leaked.length} local secret(s):\n`);
|
|
50
|
+
for (const key of result.leaked) {
|
|
51
|
+
console.error(` ${key}`);
|
|
52
|
+
}
|
|
53
|
+
console.error(
|
|
54
|
+
`\n Find where it is read at build time (import.meta.env, define, a module-scope\n process.env read) under ${relative(process.cwd(), dist) || "."}/ and fix that.\n`,
|
|
55
|
+
);
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
main();
|
|
61
|
+
} catch (error) {
|
|
62
|
+
console.error(`\n ${error instanceof Error ? error.message : String(error)}\n`);
|
|
63
|
+
process.exit(1);
|
|
64
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finds local secrets compiled into a build.
|
|
3
|
+
*
|
|
4
|
+
* Reads every value in the local `.env*` and `.dev.vars*` files (examples
|
|
5
|
+
* excluded) and searches the built files for each one. A match means a key
|
|
6
|
+
* reached something that ships, whichever tool put it there.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
/** Values shorter than this are flags or placeholders, not secrets. */
|
|
13
|
+
export const MIN_SECRET_LENGTH = 12;
|
|
14
|
+
|
|
15
|
+
const ENV_FILE = /^(\.env(\..+)?|\.dev\.vars(\..+)?)$/;
|
|
16
|
+
const EXAMPLE_FILE = /\.example$/;
|
|
17
|
+
const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/;
|
|
18
|
+
const QUOTED = /^(['"])(.*)\1$/;
|
|
19
|
+
|
|
20
|
+
/** `.dev.vars` copies the Cloudflare Vite plugin writes for `vite preview`; wrangler never uploads them. */
|
|
21
|
+
export const DEFAULT_SKIP = [".dev.vars"];
|
|
22
|
+
|
|
23
|
+
/** KEY=value pairs from a dotenv-style file, quotes stripped. */
|
|
24
|
+
export function parseEnvFile(source: string): [string, string][] {
|
|
25
|
+
const pairs: [string, string][] = [];
|
|
26
|
+
for (const line of source.split("\n")) {
|
|
27
|
+
const match = line.match(ENV_LINE);
|
|
28
|
+
if (!(match?.[1] && match[2] !== undefined)) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
pairs.push([match[1], match[2].replace(QUOTED, "$2")]);
|
|
32
|
+
}
|
|
33
|
+
return pairs;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The env keys whose values appear in any of the given file contents. */
|
|
37
|
+
export function leakedKeys(pairs: [string, string][], contents: string[]): string[] {
|
|
38
|
+
const leaked = new Set<string>();
|
|
39
|
+
for (const [key, value] of pairs) {
|
|
40
|
+
if (value.length >= MIN_SECRET_LENGTH && contents.some((text) => text.includes(value))) {
|
|
41
|
+
leaked.add(key);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return [...leaked].sort();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Every KEY=value pair in the local env files of `dir`. */
|
|
48
|
+
export function localEnvPairs(dir: string): [string, string][] {
|
|
49
|
+
return readdirSync(dir)
|
|
50
|
+
.filter((name) => ENV_FILE.test(name) && !EXAMPLE_FILE.test(name))
|
|
51
|
+
.flatMap((name) => parseEnvFile(readFileSync(join(dir, name), "utf8")));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Every file under `dir`, recursively, minus names in `skip`. */
|
|
55
|
+
export function listFiles(dir: string, skip: readonly string[] = DEFAULT_SKIP): string[] {
|
|
56
|
+
const files: string[] = [];
|
|
57
|
+
for (const name of readdirSync(dir)) {
|
|
58
|
+
const path = join(dir, name);
|
|
59
|
+
if (statSync(path).isDirectory()) {
|
|
60
|
+
files.push(...listFiles(path, skip));
|
|
61
|
+
} else if (!skip.includes(name)) {
|
|
62
|
+
files.push(path);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return files;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface CheckResult {
|
|
69
|
+
envValues: number;
|
|
70
|
+
files: number;
|
|
71
|
+
leaked: string[];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function checkBundle(root: string, dist: string, skip: readonly string[] = DEFAULT_SKIP): CheckResult {
|
|
75
|
+
if (!existsSync(dist)) {
|
|
76
|
+
throw new Error(`${dist} does not exist. Build first.`);
|
|
77
|
+
}
|
|
78
|
+
const pairs = localEnvPairs(root);
|
|
79
|
+
const files = listFiles(dist, skip);
|
|
80
|
+
const leaked = leakedKeys(
|
|
81
|
+
pairs,
|
|
82
|
+
files.map((path) => readFileSync(path, "latin1")),
|
|
83
|
+
);
|
|
84
|
+
return { envValues: pairs.length, files: files.length, leaked };
|
|
85
|
+
}
|
package/src/entry.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Worker entry that sits in front of a TanStack Start handler (or any
|
|
3
|
+
* `{ fetch }` handler) and fixes what Start leaves to the app:
|
|
4
|
+
*
|
|
5
|
+
* - A page request whose Accept header includes text/markdown gets the
|
|
6
|
+
* Markdown rendering the app provides, on the same URL.
|
|
7
|
+
* - A page request whose Accept header names neither text/html nor *∕* gets
|
|
8
|
+
* HTML instead of Start's 406.
|
|
9
|
+
* - Page responses of both kinds carry `Vary: Accept`.
|
|
10
|
+
* - Paths under a read-only prefix (default `/api/`) answer any method other
|
|
11
|
+
* than GET and HEAD with 405, instead of an empty 200 page shell.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
15
|
+
|
|
16
|
+
/** What a Markdown renderer returns: a body, a body with a status, or null to serve HTML. */
|
|
17
|
+
export type MarkdownResult = string | { body: string; status?: number } | null | undefined;
|
|
18
|
+
|
|
19
|
+
export interface FetchHandler {
|
|
20
|
+
// biome-ignore lint/suspicious/noExplicitAny: handlers pass framework-specific extra arguments through.
|
|
21
|
+
fetch(request: Request, ...rest: any[]): MaybePromise<Response>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface EntryOptions {
|
|
25
|
+
/** The framework handler, usually the default export of `@tanstack/react-start/server-entry`. */
|
|
26
|
+
handler: FetchHandler;
|
|
27
|
+
/**
|
|
28
|
+
* Markdown rendering of a page. Called for GET and HEAD page requests whose
|
|
29
|
+
* Accept header includes text/markdown. Return null to serve HTML instead.
|
|
30
|
+
*/
|
|
31
|
+
markdown?: (pathname: string, request: Request) => MaybePromise<MarkdownResult>;
|
|
32
|
+
/** Path prefixes that only accept GET and HEAD. Default `["/api/"]`. Pass `[]` to turn off. */
|
|
33
|
+
readOnlyPrefixes?: string[];
|
|
34
|
+
/**
|
|
35
|
+
* Whether a path is a page (negotiated and given `Vary: Accept`). Default:
|
|
36
|
+
* not under a read-only prefix, not a framework internal (`/_…`, `/@…`), and
|
|
37
|
+
* no file extension on the last segment.
|
|
38
|
+
*/
|
|
39
|
+
isPage?: (pathname: string) => boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const ACCEPTS_HTML = /(^|,)\s*(\*\/\*|text\/html)/;
|
|
43
|
+
const TRAILING_SLASHES = /\/+$/;
|
|
44
|
+
|
|
45
|
+
export const MARKDOWN_HEADERS: Readonly<Record<string, string>> = {
|
|
46
|
+
"content-type": "text/markdown; charset=utf-8",
|
|
47
|
+
vary: "Accept",
|
|
48
|
+
// A Markdown body is a second representation of a page, not a page of its own.
|
|
49
|
+
"x-robots-tag": "noindex",
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export function wantsMarkdown(request: Request): boolean {
|
|
53
|
+
return (request.headers.get("accept") ?? "").includes("text/markdown");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function defaultIsPage(pathname: string, readOnlyPrefixes: readonly string[] = ["/api/"]): boolean {
|
|
57
|
+
if (readOnlyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
if (pathname.startsWith("/_") || pathname.startsWith("/@")) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
const lastSegment = pathname.slice(pathname.lastIndexOf("/") + 1);
|
|
64
|
+
return !lastSegment.includes(".");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** `/learn/` becomes `/learn`; `/` stays `/`. */
|
|
68
|
+
export function normalizePath(pathname: string): string {
|
|
69
|
+
return pathname.length > 1 ? pathname.replace(TRAILING_SLASHES, "") || "/" : pathname;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function markdownResponse(result: Exclude<MarkdownResult, null | undefined>, head: boolean): Response {
|
|
73
|
+
const { body, status = 200 } = typeof result === "string" ? { body: result } : result;
|
|
74
|
+
return new Response(head ? null : body, { status, headers: MARKDOWN_HEADERS });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function withVaryAccept(response: Response): Response {
|
|
78
|
+
if (!response.headers.get("content-type")?.startsWith("text/html")) {
|
|
79
|
+
return response;
|
|
80
|
+
}
|
|
81
|
+
const headers = new Headers(response.headers);
|
|
82
|
+
headers.append("vary", "Accept");
|
|
83
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function createEntry(options: EntryOptions): {
|
|
87
|
+
fetch(request: Request, ...rest: unknown[]): Promise<Response>;
|
|
88
|
+
} {
|
|
89
|
+
const readOnlyPrefixes = options.readOnlyPrefixes ?? ["/api/"];
|
|
90
|
+
const isPage = options.isPage ?? ((pathname: string) => defaultIsPage(pathname, readOnlyPrefixes));
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
async fetch(request, ...rest) {
|
|
94
|
+
const { pathname } = new URL(request.url);
|
|
95
|
+
const isRead = request.method === "GET" || request.method === "HEAD";
|
|
96
|
+
|
|
97
|
+
if (!isRead && readOnlyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
|
|
98
|
+
return Response.json({ error: "Method not allowed" }, { status: 405, headers: { allow: "GET, HEAD" } });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (!isPage(pathname)) {
|
|
102
|
+
return options.handler.fetch(request, ...rest);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (isRead && options.markdown && wantsMarkdown(request)) {
|
|
106
|
+
const result = await options.markdown(normalizePath(pathname), request);
|
|
107
|
+
if (result !== null && result !== undefined) {
|
|
108
|
+
return markdownResponse(result, request.method === "HEAD");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let pageRequest = request;
|
|
113
|
+
if (isRead && !ACCEPTS_HTML.test(request.headers.get("accept") ?? "*/*")) {
|
|
114
|
+
const headers = new Headers(request.headers);
|
|
115
|
+
headers.set("accept", "text/html");
|
|
116
|
+
pageRequest = new Request(request, { headers });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return withVaryAccept(await options.handler.fetch(pageRequest, ...rest));
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|