workers-start 0.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0 (2026-11-19)
4
+
5
+ - `workers-start/scripts`: `tagManagerScript({ containerId, hosts })`, a Google Tag Manager bootstrap with the same host, path and consent gates as `analyticsScript`.
6
+
3
7
  ## 0.4.0 (2026-11-17)
4
8
 
5
9
  - Removed the `workers-start/biome` preset. A Workers helper library is the wrong place for a lint opinion, and once it shrank to Biome's defaults there was little left to share. Apps that extended it put the few lines they need in their own `biome.jsonc`: `vcs.useIgnoreFile`, `formatter.indentStyle: "space"`, `css.parser.tailwindDirectives` if they use Tailwind, and the rules they want on top of `recommended`.
package/README.md CHANGED
@@ -21,6 +21,8 @@ This came out of moving my sites from Next.js on OpenNext to TanStack Start on W
21
21
  npm install workers-start
22
22
  ```
23
23
 
24
+ The secret check CLI needs Node 22 or later. The other entry points run in workerd and the browser.
25
+
24
26
  ## Worker entry
25
27
 
26
28
  `workers-start/entry` wraps the Start handler.
@@ -116,6 +118,7 @@ In tests, `setWorkersModule({ env, waitUntil })` stands in for the runtime. Unde
116
118
 
117
119
  - `themeScript()` applies a stored `light` or `dark` choice before first paint, as a `data-theme` attribute by default or as a class with `target: { class: true }`. With nothing stored it does nothing, and `color-scheme: light dark` follows the OS; `followSystem: true` applies the OS choice instead, for CSS keyed off the class.
118
120
  - `analyticsScript({ measurementId, hosts })` loads GA4 only on the listed hostnames, so local dev and preview deploys never report. `skipPaths` keeps it off paths like `/admin`, and `consentCookie` waits for a consent cookie.
121
+ - `tagManagerScript({ containerId, hosts })` does the same for a Google Tag Manager container (`GTM-…`): it pushes the `gtm.js` start event and loads `gtm.js` only on the listed hostnames, with the same `skipPaths` and `consentCookie` options. The `<noscript>` iframe fallback is not included.
119
122
 
120
123
  Every value is embedded with `inlineJson`, which escapes `<`, so no option can close the script tag.
121
124
 
@@ -127,10 +130,16 @@ Run it between the build and the deploy:
127
130
  "deploy": "vite build && workers-start-check-bundle && wrangler deploy"
128
131
  ```
129
132
 
130
- It reads every value in your local `.env*` and `.dev.vars*` files (not `.example` or `.tpl` templates, and not `op://` references) and fails if any of them appears in a built file. It parses dotenv the way dotenv does, and searches for each value raw, URL-encoded, JSON-escaped and base64-encoded, inside `.gz` and `.br` files too. Symlinks are skipped. `VITE_*` keys are public by design and ignored.
133
+ It reads every value in your local `.env*` and `.dev.vars*` files (not `.example` or `.tpl` templates, and not `op://` references) and fails if any of them appears in a built file. It parses dotenv the way dotenv does, and searches for each value raw, URL-encoded, JSON-escaped and base64-encoded, inside `.gz` and `.br` files too. Symlinks are skipped. `VITE_*` keys are public by design and ignored. Values shorter than 12 characters are skipped, since short values like `true` or a port number match by chance.
131
134
 
132
135
  It skips `server/.dev.vars` inside the build directory, which wrangler never uploads. Flags: `--dist <dir>` (repeatable; default `dist`, `out` for a static site), `--root <dir>` (the base the other paths resolve against), `--env-dir <dir>` (repeatable; where the env files are, default `--root`; in a monorepo package, `--env-dir . --env-dir ../..` reads the package's and the root's), `--skip <path inside the build>`, `--allow <KEY>` for another public value, `--public-prefix <PREFIX>` for a whole family of them (for example `NEXT_PUBLIC_` in an app that kept its Next.js variable names).
133
136
 
137
+ The same check is exported from `workers-start/check-bundle` as `checkBundle(envDirs, dists, options)`, which returns the leaked keys instead of exiting, for a build script that runs it in process.
138
+
139
+ ## Related
140
+
141
+ [`workers-jobs`](https://github.com/ryanio/workers-jobs) runs background jobs on Cron Triggers and Workflows, with dedup, explicit retries, a run ledger and a backstop for missed cron slots.
142
+
134
143
  ## License
135
144
 
136
145
  MIT
package/dist/scripts.d.ts CHANGED
@@ -56,4 +56,13 @@ export interface AnalyticsScriptOptions {
56
56
  * preview deploys never fetch gtag.js or land in the production property.
57
57
  */
58
58
  export declare function analyticsScript(options: AnalyticsScriptOptions): string;
59
+ export interface TagManagerScriptOptions extends Omit<AnalyticsScriptOptions, "measurementId"> {
60
+ /** Google Tag Manager container id, `GTM-…`. Public; safe in the bundle. */
61
+ containerId: string;
62
+ }
63
+ /**
64
+ * Google Tag Manager bootstrap with the same gates as `analyticsScript`: only
65
+ * the listed hosts load gtm.js, so local dev and previews never fire tags.
66
+ */
67
+ export declare function tagManagerScript(options: TagManagerScriptOptions): string;
59
68
  //# sourceMappingURL=scripts.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"scripts.d.ts","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKjD;AAED,MAAM,WAAW,kBAAkB;IACjC,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB;;;;OAIG;IACH,MAAM,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,KAAK,EAAE,IAAI,CAAA;KAAE,CAAC;IACjD;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAYpE;AAED,MAAM,WAAW,sBAAsB;IACrC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,0GAA0G;IAC1G,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,iEAAiE;IACjE,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB;;;OAGG;IACH,aAAa,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAClD;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,CAwBvE"}
1
+ {"version":3,"file":"scripts.d.ts","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKjD;AAED,MAAM,WAAW,kBAAkB;IACjC,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB;;;;OAIG;IACH,MAAM,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,KAAK,EAAE,IAAI,CAAA;KAAE,CAAC;IACjD;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAYpE;AAED,MAAM,WAAW,sBAAsB;IACrC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,0GAA0G;IAC1G,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,iEAAiE;IACjE,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB;;;OAGG;IACH,aAAa,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAClD;AA6BD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,CAMvE;AAED,MAAM,WAAW,uBACf,SAAQ,IAAI,CAAC,sBAAsB,EAAE,eAAe,CAAC;IACrD,4EAA4E;IAC5E,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,MAAM,CAMzE"}
package/dist/scripts.js CHANGED
@@ -30,15 +30,8 @@ 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
- /**
34
- * Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
35
- * preview deploys never fetch gtag.js or land in the production property.
36
- */
37
- export function analyticsScript(options) {
38
- if (!/^G-[A-Z0-9]+$/.test(options.measurementId)) {
39
- throw new Error(`Not a GA4 measurement id: ${options.measurementId}`);
40
- }
41
- const id = inlineJson(options.measurementId);
33
+ /** The hostname, path and consent checks both analytics bootstraps start with. */
34
+ function gateChecks(options) {
42
35
  const hosts = inlineJson(options.hosts.map((h) => h.toLowerCase()));
43
36
  const checks = [
44
37
  `if(${hosts}.indexOf(location.hostname.toLowerCase())===-1)return;`,
@@ -52,6 +45,28 @@ export function analyticsScript(options) {
52
45
  : `${options.consentCookie.name}=${options.consentCookie.value}`;
53
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;`);
54
47
  }
55
- 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});})();`;
48
+ return checks.join("");
49
+ }
50
+ /**
51
+ * Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
52
+ * preview deploys never fetch gtag.js or land in the production property.
53
+ */
54
+ export function analyticsScript(options) {
55
+ if (!/^G-[A-Z0-9]+$/.test(options.measurementId)) {
56
+ throw new Error(`Not a GA4 measurement id: ${options.measurementId}`);
57
+ }
58
+ const id = inlineJson(options.measurementId);
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}`);
68
+ }
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);})();`;
56
71
  }
57
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;SACxB,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACnC,CAAC;AAoBD;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,OAAO,GAAuB,EAAE;IAC1D,MAAM,GAAG,GAAG,UAAU,CAAC,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,CAAC;IACtD,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;IAC/D,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC;IAC7D,MAAM,KAAK,GACT,OAAO,IAAI,MAAM;QACf,CAAC,CAAC,4CAA4C,MAAM,6CAA6C;QACjG,CAAC,CAAC,yCAAyC,UA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AAO,eAAe,UAAU,CAAC,OAAO,CAAC,4GAA4G,EAAE,8KAA8K,EAAE,SAAS,CAAC;AACnV,CAAC;AAQD;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgC;IAC/D,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,CAAC;QACjD,MAAM,IAAI,KAAK,CAAC,mCAAmC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,EAAE,GAAG,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IAC3C,OAAO,eAAe,UAAU,CAAC,OAAO,CAAC,0NAA0N,EAAE,qCAAqC,CAAC;AAC7S,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workers-start",
3
- "version": "0.4.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",
@@ -78,7 +78,8 @@
78
78
  "format": "biome check --write",
79
79
  "test": "npm run build && vitest run",
80
80
  "check": "npm run lint && npm run typecheck && npm run build && vitest run",
81
- "prepack": "npm run build"
81
+ "prepack": "npm run build",
82
+ "prepare": "git config core.hooksPath .githooks || true"
82
83
  },
83
84
  "publishConfig": {
84
85
  "access": "public"
package/src/scripts.ts CHANGED
@@ -66,15 +66,12 @@ export interface AnalyticsScriptOptions {
66
66
  consentCookie?: { name: string; value?: string };
67
67
  }
68
68
 
69
- /**
70
- * Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
71
- * preview deploys never fetch gtag.js or land in the production property.
72
- */
73
- export function analyticsScript(options: AnalyticsScriptOptions): string {
74
- if (!/^G-[A-Z0-9]+$/.test(options.measurementId)) {
75
- throw new Error(`Not a GA4 measurement id: ${options.measurementId}`);
76
- }
77
- const id = inlineJson(options.measurementId);
69
+ /** The hostname, path and consent checks both analytics bootstraps start with. */
70
+ function gateChecks(options: {
71
+ hosts: string[];
72
+ skipPaths?: string[];
73
+ consentCookie?: { name: string; value?: string };
74
+ }): string {
78
75
  const hosts = inlineJson(options.hosts.map((h) => h.toLowerCase()));
79
76
  const checks = [
80
77
  `if(${hosts}.indexOf(location.hostname.toLowerCase())===-1)return;`,
@@ -93,5 +90,35 @@ export function analyticsScript(options: AnalyticsScriptOptions): string {
93
90
  `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;`,
94
91
  );
95
92
  }
96
- 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});})();`;
93
+ return checks.join("");
94
+ }
95
+
96
+ /**
97
+ * Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
98
+ * preview deploys never fetch gtag.js or land in the production property.
99
+ */
100
+ export function analyticsScript(options: AnalyticsScriptOptions): string {
101
+ if (!/^G-[A-Z0-9]+$/.test(options.measurementId)) {
102
+ throw new Error(`Not a GA4 measurement id: ${options.measurementId}`);
103
+ }
104
+ const id = inlineJson(options.measurementId);
105
+ 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});})();`;
106
+ }
107
+
108
+ export interface TagManagerScriptOptions
109
+ extends Omit<AnalyticsScriptOptions, "measurementId"> {
110
+ /** Google Tag Manager container id, `GTM-…`. Public; safe in the bundle. */
111
+ containerId: string;
112
+ }
113
+
114
+ /**
115
+ * Google Tag Manager bootstrap with the same gates as `analyticsScript`: only
116
+ * the listed hosts load gtm.js, so local dev and previews never fire tags.
117
+ */
118
+ export function tagManagerScript(options: TagManagerScriptOptions): string {
119
+ if (!/^GTM-[A-Z0-9]+$/.test(options.containerId)) {
120
+ throw new Error(`Not a Tag Manager container id: ${options.containerId}`);
121
+ }
122
+ const id = inlineJson(options.containerId);
123
+ 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);})();`;
97
124
  }