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/src/head.ts ADDED
@@ -0,0 +1,125 @@
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
+
10
+ export interface SiteHead {
11
+ /** Absolute origin, no trailing slash: `https://example.com`. */
12
+ url: string;
13
+ /** Used for `og:site_name` and the default title suffix. */
14
+ name: string;
15
+ /** Path under the site of the default share image. */
16
+ defaultImage?: string;
17
+ /** Twitter handle with the @. */
18
+ twitterCreator?: string;
19
+ /** Default `en_US`. */
20
+ locale?: string;
21
+ /** Default `(title) => \`${title} | ${name}\``. */
22
+ titleTemplate?: (title: string) => string;
23
+ }
24
+
25
+ export interface PageSeo {
26
+ title: string;
27
+ /** Use `title` as the whole document title, without the template. */
28
+ rawTitle?: boolean;
29
+ description: string;
30
+ /** Path under the site, starting with "/". "/" is the homepage. */
31
+ path: string;
32
+ type?: "website" | "article";
33
+ /** Defaults to `title`. */
34
+ socialTitle?: string;
35
+ /** Defaults to `description`. */
36
+ socialDescription?: string;
37
+ /** Defaults to `socialDescription`. */
38
+ twitterDescription?: string;
39
+ /** Path under the site, or an absolute URL. */
40
+ image?: string;
41
+ imageSize?: { width: number; height: number; alt: string };
42
+ /** ISO date, for articles. */
43
+ published?: string;
44
+ /** ISO date, for articles. */
45
+ modified?: string;
46
+ /** Adds `robots: noindex`. */
47
+ noindex?: boolean;
48
+ }
49
+
50
+ export type MetaTag = { title: string } | { name: string; content: string } | { property: string; content: string };
51
+
52
+ export interface HeadTags {
53
+ meta: MetaTag[];
54
+ links: { rel: string; href: string }[];
55
+ }
56
+
57
+ export function createPageHead(site: SiteHead): {
58
+ pageHead: (seo: PageSeo) => HeadTags;
59
+ absoluteUrl: (path: string) => string;
60
+ } {
61
+ const origin = site.url.replace(/\/+$/, "");
62
+ const template = site.titleTemplate ?? ((title: string) => `${title} | ${site.name}`);
63
+
64
+ const absoluteUrl = (path: string): string => {
65
+ if (/^https?:\/\//.test(path)) {
66
+ return path;
67
+ }
68
+ return path === "/" ? origin : `${origin}${path}`;
69
+ };
70
+
71
+ const pageHead = (seo: PageSeo): HeadTags => {
72
+ const url = absoluteUrl(seo.path);
73
+ const socialTitle = seo.socialTitle ?? seo.title;
74
+ const socialDescription = seo.socialDescription ?? seo.description;
75
+ const imagePath = seo.image ?? site.defaultImage;
76
+ const image = imagePath ? absoluteUrl(imagePath) : undefined;
77
+
78
+ const meta: MetaTag[] = [
79
+ { title: seo.rawTitle ? seo.title : template(seo.title) },
80
+ { name: "description", content: seo.description },
81
+ ];
82
+ if (seo.noindex) {
83
+ meta.push({ name: "robots", content: "noindex" });
84
+ }
85
+ meta.push(
86
+ { property: "og:title", content: socialTitle },
87
+ { property: "og:description", content: socialDescription },
88
+ { property: "og:url", content: url },
89
+ { property: "og:site_name", content: site.name },
90
+ { property: "og:locale", content: site.locale ?? "en_US" },
91
+ );
92
+ if (image) {
93
+ meta.push({ property: "og:image", content: image });
94
+ }
95
+ if (image && seo.imageSize) {
96
+ meta.push(
97
+ { property: "og:image:width", content: String(seo.imageSize.width) },
98
+ { property: "og:image:height", content: String(seo.imageSize.height) },
99
+ { property: "og:image:alt", content: seo.imageSize.alt },
100
+ );
101
+ }
102
+ meta.push({ property: "og:type", content: seo.type ?? "website" });
103
+ if (seo.published) {
104
+ meta.push({ property: "article:published_time", content: seo.published });
105
+ }
106
+ if (seo.modified) {
107
+ meta.push({ property: "article:modified_time", content: seo.modified });
108
+ }
109
+ meta.push({ name: "twitter:card", content: image ? "summary_large_image" : "summary" });
110
+ if (site.twitterCreator) {
111
+ meta.push({ name: "twitter:creator", content: site.twitterCreator });
112
+ }
113
+ meta.push(
114
+ { name: "twitter:title", content: socialTitle },
115
+ { name: "twitter:description", content: seo.twitterDescription ?? socialDescription },
116
+ );
117
+ if (image) {
118
+ meta.push({ name: "twitter:image", content: image });
119
+ }
120
+
121
+ return { meta, links: [{ rel: "canonical", href: url }] };
122
+ };
123
+
124
+ return { pageHead, absoluteUrl };
125
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
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";
package/src/scripts.ts ADDED
@@ -0,0 +1,45 @@
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
+ export interface ThemeScriptOptions {
8
+ /** localStorage key. Default `theme`. */
9
+ storageKey?: string;
10
+ /** Attribute set on `<html>`. Default `data-theme`. */
11
+ attribute?: string;
12
+ /** Accepted stored values. Default `["light", "dark"]`. */
13
+ values?: string[];
14
+ }
15
+
16
+ /**
17
+ * Applies a stored theme choice before first paint, so it never flashes the
18
+ * other theme. With no stored choice it does nothing, and CSS
19
+ * `color-scheme: light dark` follows the operating system.
20
+ */
21
+ export function themeScript(options: ThemeScriptOptions = {}): string {
22
+ const key = JSON.stringify(options.storageKey ?? "theme");
23
+ const attribute = JSON.stringify(options.attribute ?? "data-theme");
24
+ const values = JSON.stringify(options.values ?? ["light", "dark"]);
25
+ return `try{var t=localStorage.getItem(${key});if(${values}.indexOf(t)!==-1){document.documentElement.setAttribute(${attribute},t)}}catch(e){}`;
26
+ }
27
+
28
+ export interface AnalyticsScriptOptions {
29
+ /** GA4 measurement id, `G-…`. Public; safe in the bundle. */
30
+ measurementId: string;
31
+ /** Hostnames that report. Every other host (localhost, previews) loads nothing. */
32
+ hosts: string[];
33
+ }
34
+
35
+ /**
36
+ * Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
37
+ * preview deploys never fetch gtag.js or land in the production property.
38
+ */
39
+ export function analyticsScript({ measurementId, hosts }: AnalyticsScriptOptions): string {
40
+ if (!/^G-[A-Z0-9]+$/.test(measurementId)) {
41
+ throw new Error(`Not a GA4 measurement id: ${measurementId}`);
42
+ }
43
+ const id = JSON.stringify(measurementId);
44
+ 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});})();`;
45
+ }
package/src/workers.ts ADDED
@@ -0,0 +1,101 @@
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
+
11
+ export interface WorkersModule {
12
+ env: Record<string, unknown>;
13
+ waitUntil?: (promise: Promise<unknown>) => void;
14
+ }
15
+
16
+ const WORKERS_MODULE = "cloudflare:workers";
17
+
18
+ let modulePromise: Promise<WorkersModule | null> | null = null;
19
+ let override: WorkersModule | null | undefined;
20
+
21
+ function processEnv(): Record<string, string | undefined> {
22
+ return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};
23
+ }
24
+
25
+ function isTestRuntime(): boolean {
26
+ const env = processEnv();
27
+ return Boolean(env.VITEST) || env.NODE_ENV === "test";
28
+ }
29
+
30
+ /** The `cloudflare:workers` module, or null outside workerd. */
31
+ export function loadWorkers(): Promise<WorkersModule | null> {
32
+ if (override !== undefined) {
33
+ return Promise.resolve(override);
34
+ }
35
+ if (isTestRuntime()) {
36
+ return Promise.resolve(null);
37
+ }
38
+ if (!modulePromise) {
39
+ modulePromise = import(/* @vite-ignore */ WORKERS_MODULE)
40
+ .then((mod) => mod as unknown as WorkersModule)
41
+ .catch(() => null);
42
+ }
43
+ return modulePromise;
44
+ }
45
+
46
+ /**
47
+ * Test hook: make `loadWorkers` return this module (or null). Pass `undefined`
48
+ * to go back to the real import.
49
+ */
50
+ export function setWorkersModule(mod: WorkersModule | null | undefined): void {
51
+ override = mod;
52
+ modulePromise = null;
53
+ }
54
+
55
+ /** A binding by name, or null when it is missing or fails the guard. */
56
+ export async function getBinding<T>(name: string, guard?: (value: unknown) => value is T): Promise<T | null> {
57
+ const mod = await loadWorkers();
58
+ const value = mod?.env[name];
59
+ if (value === undefined || value === null) {
60
+ return null;
61
+ }
62
+ if (guard && !guard(value)) {
63
+ return null;
64
+ }
65
+ return value as T;
66
+ }
67
+
68
+ /** A secret or var from the Worker env, falling back to `process.env`. Empty strings count as unset. */
69
+ export async function getEnvString(name: string): Promise<string | undefined> {
70
+ const mod = await loadWorkers();
71
+ const fromBinding = mod?.env[name];
72
+ if (typeof fromBinding === "string" && fromBinding.length > 0) {
73
+ return fromBinding;
74
+ }
75
+ return processEnv()[name] || undefined;
76
+ }
77
+
78
+ /**
79
+ * Hand work to the runtime to finish after the response is sent. Outside
80
+ * workerd there is nobody to hand it to, so this awaits it instead.
81
+ */
82
+ export async function afterResponse(work: Promise<unknown>): Promise<void> {
83
+ const mod = await loadWorkers();
84
+ if (mod?.waitUntil) {
85
+ mod.waitUntil(work);
86
+ return;
87
+ }
88
+ await work;
89
+ }
90
+
91
+ /** True for anything with KV's `get` and `put`. Use as a `getBinding` guard. */
92
+ export function isKvNamespace(value: unknown): value is {
93
+ get(key: string): Promise<string | null>;
94
+ put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;
95
+ } {
96
+ if (typeof value !== "object" || value === null) {
97
+ return false;
98
+ }
99
+ const candidate = value as { get?: unknown; put?: unknown };
100
+ return typeof candidate.get === "function" && typeof candidate.put === "function";
101
+ }