@speedkit/cli 4.44.0-beta.5 → 4.44.0-beta.6

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,3 +1,16 @@
1
+ # [4.44.0-beta.6](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.44.0-beta.5...v4.44.0-beta.6) (2026-10-28)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **onboarding:** run the document handler bundle in the browser mock of the server ([3547699](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/3547699ec9f26052793fabb88b202d8648b64c23))
7
+
8
+
9
+ ### Features
10
+
11
+ * **onboarding:** bundle the service worker with the embedded config for embedded_config ([9bb1ce0](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/9bb1ce0716693e3ff377a5c40e718cc025a65b37))
12
+ * **onboarding:** report a config that embedded_config cannot embed ([ddb792d](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/ddb792dd13f8aa21f56b3decd324a204fde90886))
13
+
1
14
  # [4.44.0-beta.5](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.44.0-beta.4...v4.44.0-beta.5) (2026-10-16)
2
15
 
3
16
 
@@ -49,6 +49,14 @@ export interface PackjockelDocumentHandlerRequest {
49
49
  customStyle?: string;
50
50
  versions?: AssetVersions;
51
51
  }
52
+ export interface PackjockelServiceWorkerRequest {
53
+ /** The Speed Kit service worker, with the `INSERT_CONFIG_HERE` placeholder of its config. */
54
+ serviceWorker: string;
55
+ /** The Speed Kit config, which writes `SpeedKit.config`. */
56
+ speedKitConfig: string;
57
+ appName: string;
58
+ versions?: AssetVersions;
59
+ }
52
60
  /**
53
61
  * Bundles with the packjockel binary in embedded mode, so no packjockel server is needed.
54
62
  *
@@ -82,6 +90,14 @@ export declare class PackjockelService {
82
90
  * @returns the code of one CommonJS module, which exports `post`
83
91
  */
84
92
  bundleDocumentHandler(request: PackjockelDocumentHandlerRequest): Promise<string>;
93
+ /**
94
+ * Bundles the service worker with the embedded Speed Kit config. The config module runs before
95
+ * the service worker, so its plugin imports resolve to their service worker builds, and the
96
+ * placeholder reads the `SpeedKit.config` it wrote.
97
+ *
98
+ * @returns the bundled service worker
99
+ */
100
+ bundleServiceWorker(request: PackjockelServiceWorkerRequest): Promise<string>;
85
101
  /**
86
102
  * Runs packjockel in a scratch directory, which is removed afterwards.
87
103
  *
@@ -104,6 +104,26 @@ export class PackjockelService {
104
104
  return args;
105
105
  }, request.versions);
106
106
  }
107
+ /**
108
+ * Bundles the service worker with the embedded Speed Kit config. The config module runs before
109
+ * the service worker, so its plugin imports resolve to their service worker builds, and the
110
+ * placeholder reads the `SpeedKit.config` it wrote.
111
+ *
112
+ * @returns the bundled service worker
113
+ */
114
+ async bundleServiceWorker(request) {
115
+ return this.run(async (directory) => [
116
+ "bundle",
117
+ "service-worker",
118
+ await writeInput(directory, "sw.js", `${request.speedKitConfig}\n${request.serviceWorker}`),
119
+ "--sk-config=SpeedKit.config",
120
+ // The Speed Kit service worker is ES6 and cannot be lowered to the es5 default.
121
+ "--target=es6",
122
+ ...keyValueFlags("--define", {
123
+ APP: JSON.stringify(request.appName),
124
+ }),
125
+ ], request.versions);
126
+ }
107
127
  /**
108
128
  * Runs packjockel in a scratch directory, which is removed afterwards.
109
129
  *
@@ -125,6 +125,24 @@ describe("PackjockelService", () => {
125
125
  "dynamicFetcherConfig.js: window.dynamicBlockConfig = {}",
126
126
  ]);
127
127
  });
128
+ it("should bundle the service worker after the Speed Kit config", async () => {
129
+ await service.bundleServiceWorker({
130
+ serviceWorker: "const config = INSERT_CONFIG_HERE;",
131
+ speedKitConfig: "SpeedKit.config = {}",
132
+ appName: "shop",
133
+ versions: { configPluginsVersion: "@release" },
134
+ });
135
+ const { args, inputs } = await recorded();
136
+ expect(args.slice(0, 2)).to.deep.equal(["bundle", "service-worker"]);
137
+ expect(args).to.include("--sk-config=SpeedKit.config");
138
+ expect(args).to.include("--target=es6");
139
+ expect(args).to.include('--define=APP="shop"');
140
+ expect(args).to.include("--config-plugins-version=@release");
141
+ expect(inputs).to.deep.equal([
142
+ "sw.js: SpeedKit.config = {}",
143
+ "const config = INSERT_CONFIG_HERE;",
144
+ ]);
145
+ });
128
146
  it("should leave the document handler to packjockel without one", async () => {
129
147
  await service.bundleDocumentHandler({
130
148
  documentHandlerConfig: "export default new DomDocumentHandler()",
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The browser mock that the server passes to a document handler, as in
3
+ * `orestes-node/helper/browserMock.js`. The embedded Speed Kit config runs in
4
+ * it, so a read such as `location.hostname` in `getCurrentHostConfig()` works.
5
+ * `location` points at the app domain, and `window` and `top` are the mock
6
+ * itself. It has no timers and no event listeners, like the server's mock.
7
+ *
8
+ * @param app the app whose domain `location` points to
9
+ * @returns the browser globals by name
10
+ */
11
+ export declare function createBrowserGlobals(app: string): Record<string, unknown>;
12
+ /** The browser global that `error` reports as not defined, or undefined for any other error. */
13
+ export declare function missingBrowserGlobal(error: unknown): string | undefined;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The browser mock that the server passes to a document handler, as in
3
+ * `orestes-node/helper/browserMock.js`. The embedded Speed Kit config runs in
4
+ * it, so a read such as `location.hostname` in `getCurrentHostConfig()` works.
5
+ * `location` points at the app domain, and `window` and `top` are the mock
6
+ * itself. It has no timers and no event listeners, like the server's mock.
7
+ *
8
+ * @param app the app whose domain `location` points to
9
+ * @returns the browser globals by name
10
+ */
11
+ export function createBrowserGlobals(app) {
12
+ const url = new URL(`https://${app}.app.baqend.com/`);
13
+ const location = {
14
+ href: url.href,
15
+ origin: url.origin,
16
+ protocol: url.protocol,
17
+ host: url.host,
18
+ hostname: url.hostname,
19
+ port: url.port,
20
+ pathname: url.pathname,
21
+ search: url.search,
22
+ hash: url.hash,
23
+ toString: () => url.href,
24
+ };
25
+ const noop = () => {
26
+ /* empty */
27
+ };
28
+ const document = {
29
+ cookie: "",
30
+ referrer: "",
31
+ getElementById: () => null,
32
+ querySelector: () => null,
33
+ querySelectorAll: () => [],
34
+ createElement: noop,
35
+ };
36
+ document.head = document;
37
+ document.body = document;
38
+ const browserGlobals = {
39
+ location,
40
+ APP: app,
41
+ speedKit: {
42
+ split: undefined,
43
+ splitTestId: undefined,
44
+ detectDevice: noop,
45
+ customVariation: [],
46
+ },
47
+ serviceWorkerUrl: "",
48
+ screen: { width: 0, height: 0 },
49
+ devicePixelRatio: 1,
50
+ navigator: {
51
+ userAgent: "",
52
+ connection: {},
53
+ cookieEnabled: false,
54
+ languages: [],
55
+ online: true,
56
+ },
57
+ document,
58
+ localStorage: { getItem: noop, setItem: noop },
59
+ };
60
+ browserGlobals.window = browserGlobals;
61
+ browserGlobals.top = browserGlobals;
62
+ return browserGlobals;
63
+ }
64
+ const BROWSER_GLOBALS = Object.keys(createBrowserGlobals("local"));
65
+ /** The browser global that `error` reports as not defined, or undefined for any other error. */
66
+ export function missingBrowserGlobal(error) {
67
+ const name = /^(\S+) is not defined$/.exec(error?.message ?? "")?.[1];
68
+ return name && BROWSER_GLOBALS.includes(name) ? name : undefined;
69
+ }
@@ -29,8 +29,18 @@ export declare class DocumentHandlerServer {
29
29
  transform(contentType: string, html: string, variation: string, url: string, headers: Record<string, string>): Promise<DocumentHandlerResponse>;
30
30
  /** Runs the handler in the context, and returns the config, which calls its `post`. */
31
31
  private createScript;
32
- /** Loads the packjockel bundle like a CommonJS module, and calls the `post` it exports. */
32
+ /**
33
+ * Loads the packjockel bundle like a CommonJS module, and calls the `post` it exports. The browser mock
34
+ * shadows the globals of the bundle, as on the server.
35
+ */
33
36
  private createBundleScript;
37
+ /**
38
+ * Loads the bundle once without the browser mock. The service worker embeds the config without a browser
39
+ * around it, so the server's proof rejects a config that reads a browser global while it loads.
40
+ *
41
+ * @returns the browser global the config reads, or undefined
42
+ */
43
+ private findBrowserGlobalRead;
34
44
  private getDocumentHandlerConfigPath;
35
45
  private getTransformFunctionWrapper;
36
46
  buildDocumentHandler(): Promise<void>;
@@ -2,12 +2,13 @@ import { LATEST_DYNAMIC_FETCHER_URL, LOCAL_DOCUMENT_HANDLER, LOCAL_DOCUMENT_HAND
2
2
  import RequiredFileNotFoundError from "./error/required-file-not-found-error.js";
3
3
  import DatabaseMock from "./templates/database-mock.js";
4
4
  import * as vm from "node:vm";
5
- import { usesConfigPlugins, } from "../integration-api/index.js";
5
+ import { embedsConfigInServiceWorker, usesConfigPlugins, } from "../integration-api/index.js";
6
6
  import { INTEGRATION_FILES } from "../../models/files.js";
7
7
  // documentHandlerDependencies
8
8
  import fetch from "node-fetch";
9
9
  import { Request } from "./server/request.js";
10
10
  import { DocumentHandlerResponse } from "./server/document-handler-response.js";
11
+ import { createBrowserGlobals, missingBrowserGlobal, } from "./document-handler-browser-mock.js";
11
12
  import { DocumentHandlerAbort } from "./document-handler-abort.js";
12
13
  import { DocumentHandlerConsole } from "./document-handler-console.js";
13
14
  import { safe } from "../../helpers/safe.js";
@@ -69,7 +70,10 @@ export class DocumentHandlerServer {
69
70
  APP: this.customerConfig.app,
70
71
  // packjockel defines these in the bundle itself.
71
72
  ...(configPlugins
72
- ? {}
73
+ ? {
74
+ // A fresh mock per request, so that one transform sees no state of the last one.
75
+ skBrowserGlobals: createBrowserGlobals(this.customerConfig.app),
76
+ }
73
77
  : {
74
78
  DYNAMIC_FETCHER: await this.getDynamicFetcher(),
75
79
  DYNAMIC_FETCHER_CONFIG: await this.getDynamicFetcherConfig(),
@@ -111,11 +115,31 @@ export class DocumentHandlerServer {
111
115
  }
112
116
  return new vm.Script(this.documentHandlerConfigCode + this.getTransformFunctionWrapper(), { filename: this.getDocumentHandlerConfigPath() });
113
117
  }
114
- /** Loads the packjockel bundle like a CommonJS module, and calls the `post` it exports. */
118
+ /**
119
+ * Loads the packjockel bundle like a CommonJS module, and calls the `post` it exports. The browser mock
120
+ * shadows the globals of the bundle, as on the server.
121
+ */
115
122
  createBundleScript() {
116
- return new vm.Script(`(function (module, exports) {\n${this.documentHandlerBundle}\n})(module, module.exports);\n\n` +
123
+ const names = Object.keys(createBrowserGlobals(this.customerConfig.app));
124
+ return new vm.Script(`(function (module, exports, ${names.join(", ")}) {\n${this.documentHandlerBundle}\n})(module, module.exports, ${names.map((name) => `skBrowserGlobals.${name}`).join(", ")});\n\n` +
117
125
  `module.exports.post(db, skInternalRequest, skInternalResponse).catch((error)=>reject(error));`, { filename: this.getDocumentHandlerConfigPath() });
118
126
  }
127
+ /**
128
+ * Loads the bundle once without the browser mock. The service worker embeds the config without a browser
129
+ * around it, so the server's proof rejects a config that reads a browser global while it loads.
130
+ *
131
+ * @returns the browser global the config reads, or undefined
132
+ */
133
+ findBrowserGlobalRead() {
134
+ const loaded = safe(() => vm.runInNewContext(this.documentHandlerBundle, {
135
+ APP: this.customerConfig.app,
136
+ ...this.getContextVars(),
137
+ ...this.createNodeVmContext(),
138
+ }, { filename: this.getDocumentHandlerConfigPath() }));
139
+ return loaded.success === true
140
+ ? undefined
141
+ : missingBrowserGlobal(loaded.errorObj);
142
+ }
119
143
  getDocumentHandlerConfigPath() {
120
144
  return this.files.getByName("config_documentHandler")
121
145
  .path;
@@ -127,6 +151,13 @@ export class DocumentHandlerServer {
127
151
  this.cli.startAction("DOCUMENTHANDLER:BUILD", "rebuild documentHandler");
128
152
  if (usesConfigPlugins(this.customerConfig)) {
129
153
  this.documentHandlerBundle = await this.bundleWithPackjockel();
154
+ const read = embedsConfigInServiceWorker(this.customerConfig)
155
+ ? this.findBrowserGlobalRead()
156
+ : undefined;
157
+ if (read) {
158
+ this.cli.failAction("DOCUMENTHANDLER:BUILD", `embedded_config: the Speed Kit config reads "${read}" while it loads, so the server rejects it. Read it in a callback, or turn embedded_config off.`);
159
+ return;
160
+ }
130
161
  this.cli.successAction("DOCUMENTHANDLER:BUILD");
131
162
  return;
132
163
  }
@@ -0,0 +1,34 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import vm from "node:vm";
4
+ import { createBrowserGlobals, missingBrowserGlobal, } from "../document-handler-browser-mock.js";
5
+ describe("createBrowserGlobals", () => {
6
+ it("should let a config read location.hostname, like the server", () => {
7
+ const globals = createBrowserGlobals("shop");
8
+ const names = Object.keys(globals);
9
+ const read = vm.compileFunction("return [location.hostname, window.location === location, top === window, typeof setTimeout];", names);
10
+ expect(read(...names.map((name) => globals[name]))).to.deep.equal([
11
+ "shop.app.baqend.com",
12
+ true,
13
+ true,
14
+ // The mock shadows no timer: the document handler keeps the real one of Node.js.
15
+ "function",
16
+ ]);
17
+ });
18
+ });
19
+ describe("missingBrowserGlobal", () => {
20
+ it("should name a browser global that a config reads without the mock", () => {
21
+ const read = (code) => {
22
+ try {
23
+ vm.runInNewContext(code, {});
24
+ }
25
+ catch (error) {
26
+ return missingBrowserGlobal(error);
27
+ }
28
+ };
29
+ expect(read("location.hostname")).to.equal("location");
30
+ // Only a browser global makes a config not embeddable.
31
+ expect(read("db.find()")).to.equal(undefined);
32
+ expect(read("var x = 1;")).to.equal(undefined);
33
+ });
34
+ });
@@ -9,6 +9,8 @@ export interface CustomerFeatures {
9
9
  * writes `SpeedKit.config`.
10
10
  */
11
11
  enableSpeedKitConfigPlugins?: boolean | null;
12
+ /** The server embeds the config into the service worker as well. */
13
+ embedded_config?: boolean | null;
12
14
  [feature: string]: unknown;
13
15
  }
14
16
  export interface CustomerConfigs {
@@ -65,3 +65,5 @@ export declare class VirtualSpeedKitConfigFile extends SpeedKitConfigFile implem
65
65
  }
66
66
  /** The customer has the `enableSpeedKitConfigPlugins` feature: packjockel bundles its config. */
67
67
  export declare function usesConfigPlugins(customer: SpeedKitConfigCustomer): boolean;
68
+ /** The customer also has the `embedded_config` feature: the service worker embeds the config too. */
69
+ export declare function embedsConfigInServiceWorker(customer: SpeedKitConfigCustomer): boolean;
@@ -222,6 +222,10 @@ function safeFileContentWrapper(fileContent) {
222
222
  export function usesConfigPlugins(customer) {
223
223
  return customer.features?.enableSpeedKitConfigPlugins === true;
224
224
  }
225
+ /** The customer also has the `embedded_config` feature: the service worker embeds the config too. */
226
+ export function embedsConfigInServiceWorker(customer) {
227
+ return (usesConfigPlugins(customer) && customer.features?.embedded_config === true);
228
+ }
225
229
  async function bundle(bundler, content, customer) {
226
230
  if (!content) {
227
231
  throw new ApplicationError("Content is empty");
@@ -4,12 +4,14 @@ import { FetchRequestPausedEventHandler } from "../onboarding-model.js";
4
4
  /**
5
5
  * SpeedKitServiceWorkerJs class is responsible for handling fetch requests for the SpeedKit service worker.
6
6
  * Injects serviceWorker from local file, if custom_sw is present.
7
+ * With `bundle`, it serves the service worker bundled with the embedded config instead.
7
8
  *
8
9
  * @implements FetchRequestPausedEventHandler
9
10
  */
10
11
  export declare class SpeedKitServiceWorkerJs implements FetchRequestPausedEventHandler {
11
12
  private customerConfig;
12
13
  private serviceWorker;
14
+ private bundle?;
13
15
  readonly patterns: Protocol.Fetch.RequestPattern[];
14
16
  /**
15
17
  * Timestamp of the last locally served sw.js. Chrome's SW update checker
@@ -19,6 +21,6 @@ export declare class SpeedKitServiceWorkerJs implements FetchRequestPausedEventH
19
21
  * OnboardingService uses this timestamp to detect and repair it.
20
22
  */
21
23
  lastServedAt: number;
22
- constructor(customerConfig: CustomerConfig, serviceWorker: FileInterface);
24
+ constructor(customerConfig: CustomerConfig, serviceWorker: FileInterface, bundle?: (serviceWorker: string) => Promise<string>);
23
25
  handle(): Promise<Partial<Protocol.Fetch.FulfillRequestRequest>>;
24
26
  }
@@ -2,12 +2,14 @@ import { BaqendResponse } from "../browser/baqend-response.js";
2
2
  /**
3
3
  * SpeedKitServiceWorkerJs class is responsible for handling fetch requests for the SpeedKit service worker.
4
4
  * Injects serviceWorker from local file, if custom_sw is present.
5
+ * With `bundle`, it serves the service worker bundled with the embedded config instead.
5
6
  *
6
7
  * @implements FetchRequestPausedEventHandler
7
8
  */
8
9
  export class SpeedKitServiceWorkerJs {
9
10
  customerConfig;
10
11
  serviceWorker;
12
+ bundle;
11
13
  patterns;
12
14
  /**
13
15
  * Timestamp of the last locally served sw.js. Chrome's SW update checker
@@ -17,9 +19,10 @@ export class SpeedKitServiceWorkerJs {
17
19
  * OnboardingService uses this timestamp to detect and repair it.
18
20
  */
19
21
  lastServedAt = 0;
20
- constructor(customerConfig, serviceWorker) {
22
+ constructor(customerConfig, serviceWorker, bundle) {
21
23
  this.customerConfig = customerConfig;
22
24
  this.serviceWorker = serviceWorker;
25
+ this.bundle = bundle;
23
26
  this.patterns = [
24
27
  {
25
28
  requestStage: "Request",
@@ -28,7 +31,12 @@ export class SpeedKitServiceWorkerJs {
28
31
  ];
29
32
  }
30
33
  async handle() {
34
+ const serviceWorker = this.serviceWorker.getContent();
35
+ // shortcut: bundles on every request, about a second; cache it per config change if updates feel slow.
36
+ const content = this.bundle
37
+ ? await this.bundle(serviceWorker)
38
+ : serviceWorker;
31
39
  this.lastServedAt = Date.now();
32
- return new BaqendResponse(this.serviceWorker.getContent(), "text/javascript; charset=utf-8");
40
+ return new BaqendResponse(content, "text/javascript; charset=utf-8");
33
41
  }
34
42
  }
@@ -6,7 +6,7 @@ import { BundleServiceFactory } from "../bundler/index.js";
6
6
  import { DiffServiceBuildContext, DiffServiceFactory } from "../diff/index.js";
7
7
  import { DocumentHandlerRuntimeServiceBuildContext } from "../document-handler-runtime/document-handler-runtime-service-build-context.js";
8
8
  import DocumentHandlerRuntimeServiceFactory from "../document-handler-runtime/factory/document-handler-runtime-service-factory.js";
9
- import { CustomerConfig, ExternalFileReader, IntegrationApiServiceBuildContext, VirtualFile, ExternalRecipe, IntegrationApiFactory, } from "../integration-api/index.js";
9
+ import { CustomerConfig, ExternalFileReader, IntegrationApiServiceBuildContext, VirtualFile, ExternalRecipe, IntegrationApiFactory, embedsConfigInServiceWorker, } from "../integration-api/index.js";
10
10
  import { InstallFileRecipe } from "./config-renderer/install-file-recipe.js";
11
11
  import { SpeedKitInstallContext } from "./config-renderer/speed-kit-install-context.js";
12
12
  import { Dashboard } from "./dashboard/index.js";
@@ -238,7 +238,17 @@ export class OnboardingServiceFactory {
238
238
  const fileWatcher = new FileWatcher(cli, customerConfig, files, documentHandler, browserContext, cache);
239
239
  const athenaClient = (await this.getAthenaClient(customerConfig.app)) || null;
240
240
  const messageHandler = await this.prepareMessagehandler(athenaClient, files, customerConfig);
241
- const speedKitServiceWorkerJs = new SpeedKitServiceWorkerJs(customerConfig, files.getByName(INTEGRATION_FILES.CUSTOM.SW));
241
+ const speedKitServiceWorkerJs = new SpeedKitServiceWorkerJs(customerConfig, files.getByName(INTEGRATION_FILES.CUSTOM.SW), embedsConfigInServiceWorker(customerConfig)
242
+ ? (serviceWorker) => bundler.packjockel.bundleServiceWorker({
243
+ serviceWorker,
244
+ // The service worker gets the split of the onboarding page, which runs every visitor in group A.
245
+ speedKitConfig: `${files
246
+ .getByName(INTEGRATION_FILES.CONFIG.SPEED_KIT)
247
+ .getContent()}\nSpeedKit.config.split = 1;\nSpeedKit.config.splitTestId = "debug";`,
248
+ appName: customerConfig.app,
249
+ versions: customerConfig,
250
+ })
251
+ : undefined);
242
252
  const fetchHandler = await this.getFetchEventHandler(files, customerConfig, documentHandler, cache, cli, browserContext, athenaClient, messageHandler, fileWatcher, speedKitServiceWorkerJs);
243
253
  const extensionBridge = new ExtensionBridge(cli, browserExtensions.hasDevtoolsExtension);
244
254
  return new OnboardingService(browserContext, customerConfig, fetchHandler, fileWatcher, cli, messageHandler, extensionBridge, speedKitServiceWorkerJs, browserFetch);
@@ -1788,5 +1788,5 @@
1788
1788
  ]
1789
1789
  }
1790
1790
  },
1791
- "version": "4.44.0-beta.5"
1791
+ "version": "4.44.0-beta.6"
1792
1792
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@speedkit/cli",
3
3
  "description": "Speed Kit CLI",
4
- "version": "4.44.0-beta.5",
4
+ "version": "4.44.0-beta.6",
5
5
  "author": {
6
6
  "name": "Baqend.com",
7
7
  "email": "info@baqend.com"