@speedkit/cli 4.44.0-beta.4 → 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.
Files changed (24) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/services/bundler/packjockel-service.d.ts +40 -0
  3. package/dist/services/bundler/packjockel-service.js +46 -0
  4. package/dist/services/bundler/spec/packjockel-service.spec.js +43 -0
  5. package/dist/services/document-handler-runtime/document-handler-browser-mock.d.ts +13 -0
  6. package/dist/services/document-handler-runtime/document-handler-browser-mock.js +69 -0
  7. package/dist/services/document-handler-runtime/document-handler-server.d.ts +11 -1
  8. package/dist/services/document-handler-runtime/document-handler-server.js +35 -4
  9. package/dist/services/document-handler-runtime/spec/document-handler-browser-mock.spec.d.ts +1 -0
  10. package/dist/services/document-handler-runtime/spec/document-handler-browser-mock.spec.js +34 -0
  11. package/dist/services/integration-api/struct/customer-config.d.ts +2 -0
  12. package/dist/services/integration-api/struct/speed-kit-config-file.d.ts +2 -0
  13. package/dist/services/integration-api/struct/speed-kit-config-file.js +4 -0
  14. package/dist/services/onboarding/config-renderer/speed-kit-install-context.d.ts +2 -0
  15. package/dist/services/onboarding/config-renderer/speed-kit-install-context.js +19 -15
  16. package/dist/services/onboarding/fetch-events/speed-kit-service-worker-js.d.ts +3 -1
  17. package/dist/services/onboarding/fetch-events/speed-kit-service-worker-js.js +10 -2
  18. package/dist/services/onboarding/file-events/file-watcher.d.ts +3 -1
  19. package/dist/services/onboarding/file-events/file-watcher.js +9 -2
  20. package/dist/services/onboarding/onboarding-service-factory.js +12 -2
  21. package/dist/services/onboarding/spec/file-events/file-watcher.spec.d.ts +1 -0
  22. package/dist/services/onboarding/spec/file-events/file-watcher.spec.js +67 -0
  23. package/oclif.manifest.json +1 -1
  24. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,3 +1,30 @@
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
+
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)
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * **onboarding:** rebuild the document handler when config_SpeedKit changes ([406b07a](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/406b07af2fb050dfb38b7fdfbcfc7b74ddfe6dd7))
20
+
21
+
22
+ ### Features
23
+
24
+ * **bundler:** bundle the install script with packjockel install-script ([a4d22d5](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/a4d22d525a148fcc1b2e24932af6571865f49dc7))
25
+ * **bundler:** run packjockel 3.2.0 for the install-script subcommand ([ff90fcb](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/ff90fcb37627dc2115293e5e96aea4403a12e128))
26
+ * **onboarding:** pass the feature flags of the customer to the packjockel install script ([976bcf2](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/976bcf2bd89b51b44ee8cfe73e4426af5aad60bf))
27
+
1
28
  # [4.44.0-beta.4](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.44.0-beta.3...v4.44.0-beta.4) (2026-10-14)
2
29
 
3
30
 
@@ -21,6 +21,23 @@ export interface PackjockelBundleRequest {
21
21
  target?: "es5" | "es6";
22
22
  minify?: boolean;
23
23
  }
24
+ export interface PackjockelInstallScriptRequest {
25
+ /** The config plugins, such as the `rum.js` load handler. */
26
+ plugins: string;
27
+ /** The Speed Kit config, which writes `SpeedKit.config`. */
28
+ config: string;
29
+ loader: string;
30
+ /** Set as `SpeedKit.config.installationId`. */
31
+ installationId: string;
32
+ /**
33
+ * The feature flags of the app. packjockel reads the flags it knows, such as `executeInIframe`, and
34
+ * ignores the others.
35
+ */
36
+ features?: Record<string, boolean>;
37
+ versions?: AssetVersions;
38
+ define?: Record<string, string>;
39
+ minify?: boolean;
40
+ }
24
41
  export interface PackjockelDocumentHandlerRequest {
25
42
  /** The document handler library; without it packjockel bundles the published one of `documentHandlerVersion`. */
26
43
  documentHandler?: string;
@@ -32,6 +49,14 @@ export interface PackjockelDocumentHandlerRequest {
32
49
  customStyle?: string;
33
50
  versions?: AssetVersions;
34
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
+ }
35
60
  /**
36
61
  * Bundles with the packjockel binary in embedded mode, so no packjockel server is needed.
37
62
  *
@@ -52,12 +77,27 @@ export declare class PackjockelService {
52
77
  * @returns the bundled code
53
78
  */
54
79
  bundle(request: PackjockelBundleRequest): Promise<string>;
80
+ /**
81
+ * Bundles the Speed Kit install script: the `SpeedKit` global, the plugins, the config, the
82
+ * installation (app, installation id) and the loader, in this order.
83
+ *
84
+ * @returns the install script
85
+ */
86
+ bundleInstallScript(request: PackjockelInstallScriptRequest): Promise<string>;
55
87
  /**
56
88
  * Bundles a document handler with its config, the embedded Speed Kit config and the default `post`.
57
89
  *
58
90
  * @returns the code of one CommonJS module, which exports `post`
59
91
  */
60
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>;
61
101
  /**
62
102
  * Runs packjockel in a scratch directory, which is removed afterwards.
63
103
  *
@@ -50,6 +50,32 @@ export class PackjockelService {
50
50
  return args;
51
51
  }, request.versions);
52
52
  }
53
+ /**
54
+ * Bundles the Speed Kit install script: the `SpeedKit` global, the plugins, the config, the
55
+ * installation (app, installation id) and the loader, in this order.
56
+ *
57
+ * @returns the install script
58
+ */
59
+ async bundleInstallScript(request) {
60
+ return this.run(async (directory) => {
61
+ const args = [
62
+ "bundle",
63
+ "install-script",
64
+ await writeInput(directory, "loader.js", request.loader),
65
+ `--plugins=${await writeInput(directory, "plugins.js", request.plugins)}`,
66
+ `--config=${await writeInput(directory, "config.js", request.config)}`,
67
+ `--installation-id=${request.installationId}`,
68
+ ];
69
+ if (request.features) {
70
+ args.push(`--features=${await writeInput(directory, "features.json", JSON.stringify(request.features))}`);
71
+ }
72
+ if (request.minify) {
73
+ args.push("--minify");
74
+ }
75
+ args.push(...keyValueFlags("--define", request.define));
76
+ return args;
77
+ }, request.versions);
78
+ }
53
79
  /**
54
80
  * Bundles a document handler with its config, the embedded Speed Kit config and the default `post`.
55
81
  *
@@ -78,6 +104,26 @@ export class PackjockelService {
78
104
  return args;
79
105
  }, request.versions);
80
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
+ }
81
127
  /**
82
128
  * Runs packjockel in a scratch directory, which is removed afterwards.
83
129
  *
@@ -81,6 +81,31 @@ describe("PackjockelService", () => {
81
81
  "config.js: SpeedKit.config = {}",
82
82
  ]);
83
83
  });
84
+ it("should bundle the install script with its loader, plugins and config", async () => {
85
+ const bundle = await service.bundleInstallScript({
86
+ plugins: "rum()",
87
+ config: "SpeedKit.config = {}",
88
+ loader: "load()",
89
+ installationId: "onboarding",
90
+ features: { executeInIframe: true },
91
+ versions: { speedKitVersion: "2.22.4" },
92
+ define: { APP: '"shop"' },
93
+ });
94
+ const { args, inputs } = await recorded();
95
+ expect(bundle.trim()).to.equal("bundled");
96
+ expect(args.slice(0, 2)).to.deep.equal(["bundle", "install-script"]);
97
+ expect(args).to.include("--installation-id=onboarding");
98
+ expect(args.some((arg) => arg.startsWith("--target")), "packjockel builds the install script for one browser gate").to.equal(false);
99
+ expect(args).to.include('--define=APP="shop"');
100
+ expect(args).to.include("--speed-kit-version=2.22.4");
101
+ expect(args).to.include("--embedded");
102
+ expect(inputs).to.deep.equal([
103
+ "loader.js: load()",
104
+ "plugins.js: rum()",
105
+ "config.js: SpeedKit.config = {}",
106
+ 'features.json: {"executeInIframe":true}',
107
+ ]);
108
+ });
84
109
  it("should bundle a document handler with every input it got", async () => {
85
110
  await service.bundleDocumentHandler({
86
111
  documentHandler: "var DocumentHandler = 1",
@@ -100,6 +125,24 @@ describe("PackjockelService", () => {
100
125
  "dynamicFetcherConfig.js: window.dynamicBlockConfig = {}",
101
126
  ]);
102
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
+ });
103
146
  it("should leave the document handler to packjockel without one", async () => {
104
147
  await service.bundleDocumentHandler({
105
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");
@@ -9,6 +9,8 @@ export declare class SpeedKitInstallContext {
9
9
  private skTemplate;
10
10
  constructor(customerConfig: CustomerConfig, configName: string, files: FileListInterface, bundler: BundleService, skTemplate: InstallSpeedKitJsTemplate);
11
11
  getSpeedKitInstallJs(): Promise<string>;
12
+ /** The boolean feature flags of the customer: packjockel rejects a request with any other value. */
13
+ private getFeatures;
12
14
  private prepareConfigLoadHandler;
13
15
  /** The Speed Kit config, with `delayRacedOrigin` set to 100 ms for the local documentHandler. */
14
16
  private getConfigSpeedKit;
@@ -32,26 +32,26 @@ export class SpeedKitInstallContext {
32
32
  .getByName(INTEGRATION_FILES.CUSTOM.DYNAMIC_FETCHER)
33
33
  .getContent(),
34
34
  });
35
- const entryPoints = {
36
- "rum.js": this.prepareConfigLoadHandler(),
37
- "config.js": configJs,
38
- // Like the install script of the server (packjockel!121), without skVersion and installationId:
39
- // a local run has no installation.
40
- ...(configPlugins && {
41
- "installation.js": "Object.assign(SpeedKit.config, { app: APP });",
42
- }),
43
- "loader.js": this.files
44
- .getByName(INTEGRATION_FILES.CUSTOM.LOADER)
45
- .getContent(),
46
- };
35
+ const loader = this.files
36
+ .getByName(INTEGRATION_FILES.CUSTOM.LOADER)
37
+ .getContent();
47
38
  if (configPlugins) {
48
- return this.bundler.packjockel.bundle({
49
- entryPoints,
39
+ return this.bundler.packjockel.bundleInstallScript({
40
+ plugins: this.prepareConfigLoadHandler(),
41
+ config: configJs,
42
+ loader,
43
+ // The local install script belongs to no deployed installation.
44
+ installationId: "onboarding",
45
+ features: this.getFeatures(),
50
46
  versions: this.customerConfig,
51
47
  define: { APP: JSON.stringify(this.customerConfig.app) },
52
- platform: "browser",
53
48
  });
54
49
  }
50
+ const entryPoints = {
51
+ "rum.js": this.prepareConfigLoadHandler(),
52
+ "config.js": configJs,
53
+ "loader.js": loader,
54
+ };
55
55
  return this.bundler.bundle({
56
56
  basePaths: IMPORT_PATHS,
57
57
  entryPoints,
@@ -63,6 +63,10 @@ export class SpeedKitInstallContext {
63
63
  },
64
64
  });
65
65
  }
66
+ /** The boolean feature flags of the customer: packjockel rejects a request with any other value. */
67
+ getFeatures() {
68
+ return Object.fromEntries(Object.entries(this.customerConfig.features ?? {}).filter((entry) => typeof entry[1] === "boolean"));
69
+ }
66
70
  prepareConfigLoadHandler() {
67
71
  return this.files
68
72
  .getByName(INTEGRATION_FILES.CONFIG.LOAD_HANDLER)
@@ -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
  }
@@ -70,7 +70,9 @@ export declare class FileWatcher {
70
70
  */
71
71
  private handleDynamicStyles;
72
72
  /**
73
- * fileWatcherCallback that will reinstall the serviceWorker
73
+ * fileWatcherCallback that will reinstall the serviceWorker.
74
+ * With the `enableSpeedKitConfigPlugins` feature, the document handler embeds `config_SpeedKit`,
75
+ * so a change to that file also rebuilds the document handler and drops its cache.
74
76
  *
75
77
  * @param file
76
78
  * @param page
@@ -1,5 +1,5 @@
1
1
  import { safe } from "../../../helpers/safe.js";
2
- import { FILE_TYPE, } from "../../integration-api/index.js";
2
+ import { FILE_TYPE, usesConfigPlugins, } from "../../integration-api/index.js";
3
3
  import { INTEGRATION_FILES } from "../../../models/files.js";
4
4
  import { race } from "../../../helpers/race.js";
5
5
  /**
@@ -153,7 +153,9 @@ export class FileWatcher {
153
153
  }, { signal });
154
154
  }
155
155
  /**
156
- * fileWatcherCallback that will reinstall the serviceWorker
156
+ * fileWatcherCallback that will reinstall the serviceWorker.
157
+ * With the `enableSpeedKitConfigPlugins` feature, the document handler embeds `config_SpeedKit`,
158
+ * so a change to that file also rebuilds the document handler and drops its cache.
157
159
  *
158
160
  * @param file
159
161
  * @param page
@@ -166,6 +168,11 @@ export class FileWatcher {
166
168
  // clear speed-kit-service-worker-caches and uninstall serviceWorker
167
169
  await this.safeClearPageBrowsersCacheStorage(page);
168
170
  await this.unregisterServiceWorker(page);
171
+ if (file.name === INTEGRATION_FILES.CONFIG.SPEED_KIT &&
172
+ usesConfigPlugins(this.customerConfig)) {
173
+ await this.documentHandler.buildDocumentHandler();
174
+ this.clearOrRefreshCache(page);
175
+ }
169
176
  // rebuild installResource
170
177
  await installResource.buildContent();
171
178
  // tell puppeteer to reinstall serviceworker on next navigate
@@ -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);
@@ -0,0 +1,67 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import { FileWatcher } from "../../file-events/file-watcher.js";
4
+ import { INTEGRATION_FILES } from "../../../../models/files.js";
5
+ /**
6
+ * Builds a FileWatcher with fakes and returns what it did on a change of `config_SpeedKit`.
7
+ *
8
+ * @param features the features of the customer config
9
+ */
10
+ async function changeSpeedKitConfig(features) {
11
+ const calls = [];
12
+ const callbacks = new Map();
13
+ const file = (name) => ({
14
+ name,
15
+ type: "file",
16
+ onChange: (callback) => callbacks.set(name, callback),
17
+ });
18
+ const files = {
19
+ hasFile: (name) => name === INTEGRATION_FILES.CONFIG.SPEED_KIT,
20
+ getByName: (name) => name === INTEGRATION_FILES.BUILD.INSTALL
21
+ ? {
22
+ buildContent: async () => calls.push("buildInstallResource"),
23
+ }
24
+ : file(name),
25
+ };
26
+ const page = {
27
+ url: () => "https://www.example.com/products/1",
28
+ target: () => ({
29
+ createCDPSession: async () => ({
30
+ send: async (method) => method === "CacheStorage.requestCacheNames" ? { caches: [] } : {},
31
+ }),
32
+ }),
33
+ };
34
+ const watcher = new FileWatcher({
35
+ writeWarning: () => undefined,
36
+ writeError: () => undefined,
37
+ }, { app: "example", features }, files, {
38
+ buildDocumentHandler: async () => calls.push("buildDocumentHandler"),
39
+ }, { domain: "https://www.example.com" }, { clear: () => calls.push("clearCache") });
40
+ watcher.addCallbackOnFileChange(page, async () => {
41
+ calls.push("reinstallServiceWorker");
42
+ }, new AbortController().signal);
43
+ await callbacks.get(INTEGRATION_FILES.CONFIG.SPEED_KIT)(file(INTEGRATION_FILES.CONFIG.SPEED_KIT));
44
+ return calls;
45
+ }
46
+ describe("FileWatcher", () => {
47
+ describe("on a change of config_SpeedKit", () => {
48
+ it("rebuilds the document handler when it embeds the config", async () => {
49
+ const calls = await changeSpeedKitConfig({
50
+ enableSpeedKitConfigPlugins: true,
51
+ });
52
+ expect(calls).to.deep.equal([
53
+ "buildDocumentHandler",
54
+ "clearCache",
55
+ "buildInstallResource",
56
+ "reinstallServiceWorker",
57
+ ]);
58
+ });
59
+ it("only reinstalls the service worker without config plugins", async () => {
60
+ const calls = await changeSpeedKitConfig(undefined);
61
+ expect(calls).to.deep.equal([
62
+ "buildInstallResource",
63
+ "reinstallServiceWorker",
64
+ ]);
65
+ });
66
+ });
67
+ });
@@ -1788,5 +1788,5 @@
1788
1788
  ]
1789
1789
  }
1790
1790
  },
1791
- "version": "4.44.0-beta.4"
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.4",
4
+ "version": "4.44.0-beta.6",
5
5
  "author": {
6
6
  "name": "Baqend.com",
7
7
  "email": "info@baqend.com"
@@ -110,7 +110,7 @@
110
110
  "@oclif/plugin-help": "^6.2.45",
111
111
  "@oclif/plugin-not-found": "^3.2.81",
112
112
  "@oclif/plugin-warn-if-update-available": "^3.1.61",
113
- "@speedkit/packjockel": "3.1.0",
113
+ "@speedkit/packjockel": "4.0.0",
114
114
  "@speedkit/rules": "^1.3.0-0",
115
115
  "baqend": "^4.2.5",
116
116
  "chalk": "^5.6.2",