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

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 (36) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/services/bundler/packjockel-service.d.ts +17 -1
  3. package/dist/services/bundler/packjockel-service.js +21 -1
  4. package/dist/services/bundler/spec/packjockel-service.spec.js +20 -2
  5. package/dist/services/deploy/handler/customer-config-handler.d.ts +9 -0
  6. package/dist/services/deploy/handler/customer-config-handler.js +40 -6
  7. package/dist/services/deploy/interface/install.d.ts +7 -1
  8. package/dist/services/deploy/mr/live-state-check.js +21 -2
  9. package/dist/services/deploy/policy/auto-deploy-policy.js +2 -0
  10. package/dist/services/deploy/policy/deploy-policy-model.d.ts +4 -0
  11. package/dist/services/deploy/policy/deploy-policy-model.js +4 -0
  12. package/dist/services/deploy/spec/handler/customer-config-handler.spec.d.ts +1 -0
  13. package/dist/services/deploy/spec/handler/customer-config-handler.spec.js +79 -0
  14. package/dist/services/deploy/spec/mr/live-state-check.spec.js +45 -4
  15. package/dist/services/deploy/spec/policy/auto-deploy-policy.spec.js +2 -0
  16. package/dist/services/document-handler-runtime/document-handler-browser-mock.d.ts +13 -0
  17. package/dist/services/document-handler-runtime/document-handler-browser-mock.js +69 -0
  18. package/dist/services/document-handler-runtime/document-handler-server.d.ts +11 -1
  19. package/dist/services/document-handler-runtime/document-handler-server.js +35 -4
  20. package/dist/services/document-handler-runtime/spec/document-handler-browser-mock.spec.d.ts +1 -0
  21. package/dist/services/document-handler-runtime/spec/document-handler-browser-mock.spec.js +34 -0
  22. package/dist/services/integration-api/integration-api-model.d.ts +2 -0
  23. package/dist/services/integration-api/spec/customer-config-file.spec.d.ts +1 -0
  24. package/dist/services/integration-api/spec/customer-config-file.spec.js +56 -0
  25. package/dist/services/integration-api/struct/customer-config-file.d.ts +15 -0
  26. package/dist/services/integration-api/struct/customer-config-file.js +42 -0
  27. package/dist/services/integration-api/struct/customer-config.d.ts +25 -2
  28. package/dist/services/integration-api/struct/customer-config.js +41 -4
  29. package/dist/services/integration-api/struct/speed-kit-config-file.d.ts +2 -0
  30. package/dist/services/integration-api/struct/speed-kit-config-file.js +4 -0
  31. package/dist/services/onboarding/fetch-events/speed-kit-service-worker-js.d.ts +3 -1
  32. package/dist/services/onboarding/fetch-events/speed-kit-service-worker-js.js +10 -2
  33. package/dist/services/onboarding/onboarding-service-factory.js +12 -2
  34. package/dist/services/pull/pull-service.js +23 -5
  35. package/oclif.manifest.json +1 -1
  36. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,30 @@
1
+ # [4.44.0-beta.7](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.44.0-beta.6...v4.44.0-beta.7) (2026-10-28)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **integration-api:** name the feature embeddedConfig like the installation stores it ([9a8504c](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/9a8504cf2801bf66dc84fdfaed1c87f128eea42e))
7
+
8
+
9
+ ### Features
10
+
11
+ * **deploy:** reset omitted features, and sync the version tags with the installation ([6f14f7f](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/6f14f7f2c4611469266f7671e939a0c603645204))
12
+ * **deploy:** sync the feature flags of config_customer.json with the installation ([1ef84b0](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/1ef84b0bb9cd35b26eed23a8227f696231ae0ea7))
13
+ * **integration-api:** name the RUM tag rumPluginsVersion like configPluginsVersion ([335cb60](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/335cb60140a2d97391999b35bfbec46304c6da6f))
14
+
15
+ # [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)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **onboarding:** run the document handler bundle in the browser mock of the server ([3547699](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/3547699ec9f26052793fabb88b202d8648b64c23))
21
+
22
+
23
+ ### Features
24
+
25
+ * **onboarding:** bundle the service worker with the embedded config for embedded_config ([9bb1ce0](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/9bb1ce0716693e3ff377a5c40e718cc025a65b37))
26
+ * **onboarding:** report a config that embedded_config cannot embed ([ddb792d](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/ddb792dd13f8aa21f56b3decd324a204fde90886))
27
+
1
28
  # [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
29
 
3
30
 
@@ -6,7 +6,7 @@
6
6
  export interface AssetVersions {
7
7
  /** Speed Kit: snippet, service worker and dynamic fetcher */
8
8
  speedKitVersion?: string;
9
- rumPluginVersion?: string;
9
+ rumPluginsVersion?: string;
10
10
  /** predictive preloading */
11
11
  ppVersion?: string;
12
12
  configPluginsVersion?: string;
@@ -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
  *
@@ -6,7 +6,7 @@ import { binaryPath } from "@speedkit/packjockel";
6
6
  import { PackjockelError } from "./error/packjockel-error.js";
7
7
  const VERSION_FLAGS = {
8
8
  speedKitVersion: "--speed-kit-version",
9
- rumPluginVersion: "--rum-plugin-version",
9
+ rumPluginsVersion: "--rum-plugin-version",
10
10
  ppVersion: "--pp-version",
11
11
  configPluginsVersion: "--config-plugins-version",
12
12
  documentHandlerVersion: "--document-handler-version",
@@ -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
  *
@@ -60,7 +60,7 @@ describe("PackjockelService", () => {
60
60
  it("should bundle the entry points in their order", async () => {
61
61
  const bundle = await service.bundle({
62
62
  entryPoints: { "rum.js": "rum()", "config.js": "SpeedKit.config = {}" },
63
- versions: { configPluginsVersion: "@release", rumPluginVersion: "" },
63
+ versions: { configPluginsVersion: "@release", rumPluginsVersion: "" },
64
64
  define: { APP: '"shop"' },
65
65
  platform: "browser",
66
66
  });
@@ -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()",
@@ -133,7 +151,7 @@ describe("PackjockelService", () => {
133
151
  versions: {
134
152
  documentHandlerVersion: "1.8.0",
135
153
  speedKitVersion: "2.22.4",
136
- rumPluginVersion: "@release",
154
+ rumPluginsVersion: "@release",
137
155
  },
138
156
  });
139
157
  const { args, inputs } = await recorded();
@@ -13,9 +13,18 @@ export default class CustomerConfigHandler implements DeployHandlerInterface {
13
13
  private cli;
14
14
  private builder;
15
15
  private policy;
16
+ /** The confirmed features that differ from the installation. */
17
+ private features;
18
+ /** The confirmed version tags that differ from the installation. */
19
+ private versions;
16
20
  constructor(customer: CustomerConfig, configApi: ConfigApiService, configName: string, diffService: DiffService, cli: CliServiceInterface, builder: InstallResourceBuilder, policy: DeployPolicyInterface);
17
21
  canHandle(type: FILE_TYPE): boolean;
18
22
  handle(files: CustomerConfigFile[]): Promise<void>;
19
23
  upload(files: CustomerConfigFile[]): Promise<void>;
24
+ /**
25
+ * The fields whose local value differs from the installation, once confirmed. A field that the
26
+ * config omits is `null`, so the diff shows its reset.
27
+ */
28
+ private confirmChanges;
20
29
  private handleMissingRemoteInstallResource;
21
30
  }
@@ -1,4 +1,4 @@
1
- import { FILE_TYPE, } from "../../integration-api/index.js";
1
+ import { changedFields, FILE_TYPE, VERSION_FIELDS, versionsOfConfig, versionsOfInstall, } from "../../integration-api/index.js";
2
2
  import chalk from "chalk";
3
3
  import { DeployQuestion } from "../policy/index.js";
4
4
  import { DeployAbortedError } from "../error/deploy-aborted-error.js";
@@ -10,6 +10,10 @@ export default class CustomerConfigHandler {
10
10
  cli;
11
11
  builder;
12
12
  policy;
13
+ /** The confirmed features that differ from the installation. */
14
+ features = {};
15
+ /** The confirmed version tags that differ from the installation. */
16
+ versions = {};
13
17
  constructor(customer, configApi, configName, diffService, cli, builder, policy) {
14
18
  this.customer = customer;
15
19
  this.configApi = configApi;
@@ -26,6 +30,8 @@ export default class CustomerConfigHandler {
26
30
  const installResource = await this.configApi.getActiveInstall(this.configName);
27
31
  const file = files[0];
28
32
  const config = file.config;
33
+ this.features = await this.confirmChanges(DeployQuestion.UpdateFeatures, "features", config.features, installResource?.features);
34
+ this.versions = await this.confirmChanges(DeployQuestion.UpdateVersions, "version tags", versionsOfConfig(config), versionsOfInstall(installResource));
29
35
  if (!installResource) {
30
36
  await this.handleMissingRemoteInstallResource(config);
31
37
  this.cli.write("with origins:", true);
@@ -58,12 +64,40 @@ export default class CustomerConfigHandler {
58
64
  async upload(files) {
59
65
  const file = files[0];
60
66
  const installResource = await this.builder.init(this.configName);
61
- if (file.shouldSkipFile()) {
62
- // if installResource already exists its possible to skip the origin update
63
- return;
67
+ const updatesFeatures = Object.keys(this.features).length > 0;
68
+ const updatesVersions = Object.keys(this.versions).length > 0;
69
+ if (updatesFeatures) {
70
+ installResource.features = {
71
+ ...installResource.features,
72
+ ...this.features,
73
+ };
74
+ }
75
+ for (const [tag, value] of Object.entries(this.versions)) {
76
+ installResource[VERSION_FIELDS[tag]] = value;
77
+ }
78
+ // if installResource already exists its possible to skip the origin update
79
+ if (!file.shouldSkipFile()) {
80
+ installResource.origins = file.config.origins;
81
+ }
82
+ if (updatesFeatures || updatesVersions || !file.shouldSkipFile()) {
83
+ this.builder.merge(installResource);
84
+ }
85
+ }
86
+ /**
87
+ * The fields whose local value differs from the installation, once confirmed. A field that the
88
+ * config omits is `null`, so the diff shows its reset.
89
+ */
90
+ async confirmChanges(question, label, local, live) {
91
+ const changed = changedFields(local, live);
92
+ if (Object.keys(changed).length === 0) {
93
+ return {};
94
+ }
95
+ this.cli.write(`will update ${label}:`, true);
96
+ for (const [name, value] of Object.entries(changed)) {
97
+ this.cli.code(`${name}: ${JSON.stringify(live?.[name] ?? null)} -> ${JSON.stringify(value)}`, true);
64
98
  }
65
- installResource.origins = file.config.origins;
66
- this.builder.merge(installResource);
99
+ const update = await this.policy.confirm(question, `Update ${label}?`, true);
100
+ return update ? changed : {};
67
101
  }
68
102
  async handleMissingRemoteInstallResource(config) {
69
103
  const configName = config?.name || this.configName;
@@ -6,9 +6,15 @@ export default interface Install extends Partial<InstallConfigs<string>> {
6
6
  createdAt?: Date;
7
7
  updatedAt?: Date;
8
8
  status?: string;
9
- swVersion?: string;
9
+ swVersion?: string | null;
10
+ rumVersion?: string | null;
11
+ ppVersion?: string | null;
12
+ configPluginsVersion?: string | null;
13
+ documentHandlerVersion?: string | null;
10
14
  domain: string;
11
15
  configVersion?: number;
12
16
  description?: string;
13
17
  origins?: string[];
18
+ /** The feature flags, under the field names the installation stores. */
19
+ features?: Record<string, unknown>;
14
20
  }
@@ -1,3 +1,4 @@
1
+ import { changedFields, versionsOfConfig, versionsOfInstall, } from "../../integration-api/index.js";
1
2
  import { InstallResourceToFileMapping } from "../../pull/index.js";
2
3
  /** How the live installation relates to the merge request. */
3
4
  export var LiveState;
@@ -13,6 +14,10 @@ export var LiveState;
13
14
  })(LiveState || (LiveState = {}));
14
15
  /** The origins are one file of the comparison, under the name of their file. */
15
16
  const ORIGINS = "config_customer(origins)";
17
+ /** The features are one file of the comparison, under the name of their file. */
18
+ const FEATURES = "config_customer(features)";
19
+ /** The version tags are one file of the comparison, under the name of their file. */
20
+ const VERSIONS = "config_customer(versions)";
16
21
  /**
17
22
  * Compares the live installation with the state before the merge request.
18
23
  *
@@ -57,6 +62,12 @@ export class LiveStateCheck {
57
62
  JSON.stringify([...right.origins].sort())) {
58
63
  differences.push(ORIGINS);
59
64
  }
65
+ if (Object.keys(changedFields(left.features, right.features)).length) {
66
+ differences.push(FEATURES);
67
+ }
68
+ if (Object.keys(changedFields(left.versions, right.versions)).length) {
69
+ differences.push(VERSIONS);
70
+ }
60
71
  return differences;
61
72
  }
62
73
  stateOfFiles(files) {
@@ -66,9 +77,12 @@ export class LiveStateCheck {
66
77
  contents[file.remoteKey] = file.getContent();
67
78
  }
68
79
  }
80
+ const config = files.getCustomerConfig()?.config;
69
81
  return {
70
82
  contents,
71
- origins: files.getCustomerConfig()?.config?.origins ?? [],
83
+ origins: config?.origins ?? [],
84
+ features: config?.features ?? {},
85
+ versions: versionsOfConfig(config),
72
86
  };
73
87
  }
74
88
  stateOfInstall(install) {
@@ -76,6 +90,11 @@ export class LiveStateCheck {
76
90
  for (const key of Object.keys(InstallResourceToFileMapping)) {
77
91
  contents[key] = install[key] ?? "";
78
92
  }
79
- return { contents, origins: install.origins ?? [] };
93
+ return {
94
+ contents,
95
+ origins: install.origins ?? [],
96
+ features: install.features ?? {},
97
+ versions: versionsOfInstall(install),
98
+ };
80
99
  }
81
100
  }
@@ -46,6 +46,8 @@ export class AutoDeployPolicy {
46
46
  // The reviewed change itself.
47
47
  case DeployQuestion.UpdateFile:
48
48
  case DeployQuestion.UpdateOrigins:
49
+ case DeployQuestion.UpdateFeatures:
50
+ case DeployQuestion.UpdateVersions:
49
51
  case DeployQuestion.DeleteInstallResourceKey:
50
52
  case DeployQuestion.UploadModules:
51
53
  case DeployQuestion.UploadServerConfig: {
@@ -9,6 +9,10 @@ export declare enum DeployQuestion {
9
9
  UpdateFile = "updateFile",
10
10
  /** Take over the local origins into the installation. */
11
11
  UpdateOrigins = "updateOrigins",
12
+ /** Take over the local feature flags into the installation. */
13
+ UpdateFeatures = "updateFeatures",
14
+ /** Take over the local version tags into the installation. */
15
+ UpdateVersions = "updateVersions",
12
16
  /** Create a configuration that does not exist in the app yet. */
13
17
  CreateConfig = "createConfig",
14
18
  /** Drop a resource whose local file is gone. */
@@ -10,6 +10,10 @@ export var DeployQuestion;
10
10
  DeployQuestion["UpdateFile"] = "updateFile";
11
11
  /** Take over the local origins into the installation. */
12
12
  DeployQuestion["UpdateOrigins"] = "updateOrigins";
13
+ /** Take over the local feature flags into the installation. */
14
+ DeployQuestion["UpdateFeatures"] = "updateFeatures";
15
+ /** Take over the local version tags into the installation. */
16
+ DeployQuestion["UpdateVersions"] = "updateVersions";
13
17
  /** Create a configuration that does not exist in the app yet. */
14
18
  DeployQuestion["CreateConfig"] = "createConfig";
15
19
  /** Drop a resource whose local file is gone. */
@@ -0,0 +1,79 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import CustomerConfigHandler from "../../handler/customer-config-handler.js";
4
+ import InstallResourceBuilder from "../../builder/install-resource-builder.js";
5
+ import { DiffService } from "../../../diff/index.js";
6
+ import { changedFields, } from "../../../integration-api/index.js";
7
+ import { DeployQuestion } from "../../policy/index.js";
8
+ const ORIGINS = ["https://www.example.com"];
9
+ /** A deploy of `features` against a live installation with the same origins. */
10
+ async function deploy(features, live, versions = {}, liveVersions = {}) {
11
+ const install = {
12
+ domain: "production",
13
+ configVersion: 1,
14
+ origins: [...ORIGINS],
15
+ features: live,
16
+ ...liveVersions,
17
+ };
18
+ const configApi = {
19
+ getActiveInstall: async () => structuredClone(install),
20
+ };
21
+ const questions = [];
22
+ const policy = {
23
+ confirm: async (question) => {
24
+ questions.push(question);
25
+ return true;
26
+ },
27
+ };
28
+ const cli = new Proxy({}, { get: () => () => undefined });
29
+ const builder = new InstallResourceBuilder(configApi);
30
+ let skipped = false;
31
+ const file = {
32
+ config: {
33
+ origins: [...ORIGINS],
34
+ features,
35
+ ...versions,
36
+ },
37
+ skipFile: () => (skipped = true),
38
+ shouldSkipFile: () => skipped,
39
+ };
40
+ const handler = new CustomerConfigHandler({}, configApi, "production", new DiffService({}), cli, builder, policy);
41
+ await handler.handle([file]);
42
+ await handler.upload([file]);
43
+ return { builder, questions };
44
+ }
45
+ describe("CustomerConfigHandler", () => {
46
+ it("uploads a changed feature although the origins are the same", async () => {
47
+ const { builder, questions } = await deploy({ embeddedConfig: true, enableSpeedKitConfigPlugins: null }, { embeddedConfig: false, suppressOriginNoStore: true });
48
+ expect(questions).to.deep.equal([DeployQuestion.UpdateFeatures]);
49
+ expect(builder.hasChanges()).to.equal(true);
50
+ // An omitted feature is null, so the deploy resets it.
51
+ expect(builder.getInstallResource().features).to.deep.equal({
52
+ embeddedConfig: true,
53
+ suppressOriginNoStore: null,
54
+ });
55
+ });
56
+ it("changes nothing while the installation has the features", async () => {
57
+ const { builder, questions } = await deploy({ embeddedConfig: true }, { embeddedConfig: true });
58
+ expect(questions).to.deep.equal([]);
59
+ expect(builder.hasChanges()).to.equal(false);
60
+ });
61
+ });
62
+ describe("CustomerConfigHandler version tags", () => {
63
+ it("stores a tag in its installation field, and resets an omitted one", async () => {
64
+ const { builder, questions } = await deploy({}, {}, { speedKitVersion: "2.22.4" }, { swVersion: "2.21.0", rumVersion: "@release" });
65
+ expect(questions).to.deep.equal([DeployQuestion.UpdateVersions]);
66
+ expect(builder.getInstallResource()).to.include({
67
+ swVersion: "2.22.4",
68
+ rumVersion: null,
69
+ });
70
+ });
71
+ });
72
+ describe("changedFields", () => {
73
+ it("resets a feature the config omits", () => {
74
+ expect(changedFields({ embeddedConfig: false, allowCaseSensitiveVariation: null }, { prefetchingOnDeploymentJob: true, allowCaseSensitiveVariation: null })).to.deep.equal({
75
+ embeddedConfig: false,
76
+ prefetchingOnDeploymentJob: null,
77
+ });
78
+ });
79
+ });
@@ -4,7 +4,7 @@ import { LiveState, LiveStateCheck } from "../../mr/live-state-check.js";
4
4
  import { DiffService } from "../../../diff/index.js";
5
5
  const ORIGINS = ["https://www.example.com"];
6
6
  /** A configuration of the install resource files it holds. */
7
- function configuration(files, origins = ORIGINS) {
7
+ function configuration(files, origins = ORIGINS, features) {
8
8
  const resources = Object.entries(files).map(([remoteKey, content]) => ({
9
9
  remoteKey,
10
10
  name: remoteKey,
@@ -13,11 +13,11 @@ function configuration(files, origins = ORIGINS) {
13
13
  }));
14
14
  return {
15
15
  getInstallResources: () => resources,
16
- getCustomerConfig: () => ({ config: { origins } }),
16
+ getCustomerConfig: () => ({ config: { origins, features } }),
17
17
  };
18
18
  }
19
- function installOf(files, origins = ORIGINS) {
20
- return { domain: "production", origins, ...files };
19
+ function installOf(files, origins = ORIGINS, features) {
20
+ return { domain: "production", origins, features, ...files };
21
21
  }
22
22
  const check = new LiveStateCheck(new DiffService({}));
23
23
  describe("LiveStateCheck", () => {
@@ -71,4 +71,45 @@ describe("LiveStateCheck", () => {
71
71
  const result = check.compare(base, base, null);
72
72
  expect(result.state).to.equal(LiveState.Missing);
73
73
  });
74
+ it("deploys a merge request that only turns on a feature", () => {
75
+ const base = configuration({ config: "same" }, ORIGINS, {
76
+ embeddedConfig: false,
77
+ });
78
+ const local = configuration({ config: "same" }, ORIGINS, {
79
+ embeddedConfig: true,
80
+ });
81
+ const live = installOf({ config: "same" }, ORIGINS, {
82
+ embeddedConfig: false,
83
+ });
84
+ expect(check.isUnchanged(base, local)).to.equal(false);
85
+ expect(check.compare(base, local, live).state).to.equal(LiveState.Reviewed);
86
+ });
87
+ it("names the features when live changed one", () => {
88
+ const features = { embeddedConfig: false };
89
+ const base = configuration({ config: "same" }, ORIGINS, features);
90
+ const local = configuration({ config: "after" }, ORIGINS, features);
91
+ const result = check.compare(base, local, installOf({ config: "same" }, ORIGINS, { embeddedConfig: true }));
92
+ expect(result.state).to.equal(LiveState.Drifted);
93
+ expect(result.driftedFiles).to.deep.equal(["config_customer(features)"]);
94
+ });
95
+ it("calls a feature that only live sets drift, because the deploy resets it", () => {
96
+ const base = configuration({ config: "before" });
97
+ const local = configuration({ config: "after" });
98
+ const result = check.compare(base, local, installOf({ config: "before" }, ORIGINS, {
99
+ suppressOriginNoStore: true,
100
+ embeddedConfig: null,
101
+ }));
102
+ expect(result.state).to.equal(LiveState.Drifted);
103
+ expect(result.driftedFiles).to.deep.equal(["config_customer(features)"]);
104
+ });
105
+ it("names the version tags when live pins another build", () => {
106
+ const base = configuration({ config: "before" });
107
+ const local = configuration({ config: "after" });
108
+ const result = check.compare(base, local, {
109
+ ...installOf({ config: "before" }),
110
+ swVersion: "2.21.0",
111
+ });
112
+ expect(result.state).to.equal(LiveState.Drifted);
113
+ expect(result.driftedFiles).to.deep.equal(["config_customer(versions)"]);
114
+ });
74
115
  });
@@ -5,6 +5,8 @@ import { DeployQuestion } from "../../policy/deploy-policy-model.js";
5
5
  const REVIEWED = [
6
6
  DeployQuestion.UpdateFile,
7
7
  DeployQuestion.UpdateOrigins,
8
+ DeployQuestion.UpdateFeatures,
9
+ DeployQuestion.UpdateVersions,
8
10
  DeployQuestion.DeleteInstallResourceKey,
9
11
  DeployQuestion.UploadInstallResource,
10
12
  DeployQuestion.UploadModules,
@@ -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", `embeddedConfig: the Speed Kit config reads "${read}" while it loads, so the server rejects it. Read it in a callback, or turn embeddedConfig 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
+ });
@@ -95,6 +95,8 @@ export interface SpeedKitConfigInterface extends InstallResourceInterface {
95
95
  export interface CustomerConfigInterface extends ConfigFileInterface {
96
96
  config: CustomerConfig;
97
97
  updateOrigins(origins: string[]): void;
98
+ updateFeatures(live?: Record<string, unknown>): boolean;
99
+ updateVersions(live: Record<string, unknown>): boolean;
98
100
  readonly configName: string;
99
101
  }
100
102
  export interface VirtualFileRecipe {
@@ -0,0 +1,56 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import { CustomerConfig, CustomerConfigFile, } from "../../integration-api/index.js";
4
+ function fileWith(production) {
5
+ const content = JSON.stringify({ production }, null, 2);
6
+ return new CustomerConfigFile("config_customer.json", "config_customer.json", content, CustomerConfig.createFrom(production, "production"), "production");
7
+ }
8
+ const BASE = {
9
+ app: "example-shop",
10
+ domain: "production",
11
+ origins: ["https://www.example.com"],
12
+ swPath: "/sw.js",
13
+ scope: "/",
14
+ };
15
+ describe("CustomerConfigFile.updateFeatures", () => {
16
+ it("takes over the features the installation sets", () => {
17
+ const file = fileWith({ ...BASE, features: { embeddedConfig: false } });
18
+ const changed = file.updateFeatures({
19
+ embeddedConfig: true,
20
+ prefetchingOnDeploymentJob: null,
21
+ });
22
+ expect(changed).to.equal(true);
23
+ expect(JSON.parse(file.getContent()).production.features).to.deep.equal({
24
+ embeddedConfig: true,
25
+ });
26
+ expect(file.config.features).to.deep.equal({ embeddedConfig: true });
27
+ });
28
+ it("drops the features when the installation sets none", () => {
29
+ const file = fileWith({ ...BASE, features: { embeddedConfig: true } });
30
+ expect(file.updateFeatures({ embeddedConfig: null })).to.equal(true);
31
+ expect(JSON.parse(file.getContent()).production).to.not.have.property("features");
32
+ });
33
+ it("leaves an equal file alone", () => {
34
+ const file = fileWith({ ...BASE, features: { embeddedConfig: true } });
35
+ const before = file.getContent();
36
+ expect(file.updateFeatures({ embeddedConfig: true })).to.equal(false);
37
+ expect(file.getContent()).to.equal(before);
38
+ });
39
+ });
40
+ describe("CustomerConfigFile.updateVersions", () => {
41
+ it("writes the tags of the installation and drops the ones at latest", () => {
42
+ const file = fileWith({ ...BASE, ppVersion: "1.2.0" });
43
+ const changed = file.updateVersions({
44
+ speedKitVersion: "2.22.4",
45
+ rumPluginsVersion: null,
46
+ ppVersion: null,
47
+ configPluginsVersion: null,
48
+ documentHandlerVersion: null,
49
+ });
50
+ const production = JSON.parse(file.getContent()).production;
51
+ expect(changed).to.equal(true);
52
+ expect(production.speedKitVersion).to.equal("2.22.4");
53
+ expect(production).to.not.have.property("ppVersion");
54
+ expect(file.config.speedKitVersion).to.equal("2.22.4");
55
+ });
56
+ });
@@ -1,4 +1,5 @@
1
1
  import { CustomerConfig, File, CustomerConfigInterface, FILE_TYPE } from "../integration-api-model.js";
2
+ import { VersionTag } from "./customer-config.js";
2
3
  export declare class CustomerConfigFile extends File implements CustomerConfigInterface {
3
4
  config: CustomerConfig;
4
5
  readonly configName: string;
@@ -7,5 +8,19 @@ export declare class CustomerConfigFile extends File implements CustomerConfigIn
7
8
  constructor(name: string, path: string, content: string, config: CustomerConfig, configName: string, testApp?: string);
8
9
  setContent(content: string): void;
9
10
  updateOrigins(origins: string[]): void;
11
+ /**
12
+ * Takes over the features the installation sets. The file then holds exactly these, and none
13
+ * when the installation sets none.
14
+ *
15
+ * @returns whether the features changed
16
+ */
17
+ updateFeatures(live?: Record<string, unknown>): boolean;
18
+ /**
19
+ * Takes over the version tags of the installation. A tag the installation leaves at `latest` is
20
+ * removed from the file.
21
+ *
22
+ * @returns whether a tag changed
23
+ */
24
+ updateVersions(live: Record<VersionTag, unknown>): boolean;
10
25
  private updateConfigByContent;
11
26
  }
@@ -2,6 +2,7 @@ import { CustomerConfig, File, FILE_TYPE, } from "../integration-api-model.js";
2
2
  import { safe } from "../../../helpers/safe.js";
3
3
  import CustomerConfigError from "../error/customer-config-error.js";
4
4
  import { isSame } from "../array-helper.js";
5
+ import { declaredFields, versionsOfConfig, } from "./customer-config.js";
5
6
  export class CustomerConfigFile extends File {
6
7
  config;
7
8
  configName;
@@ -28,6 +29,47 @@ export class CustomerConfigFile extends File {
28
29
  configContent[this.configName].origins = origins;
29
30
  this.setContent(JSON.stringify(configContent, null, 2));
30
31
  }
32
+ /**
33
+ * Takes over the features the installation sets. The file then holds exactly these, and none
34
+ * when the installation sets none.
35
+ *
36
+ * @returns whether the features changed
37
+ */
38
+ updateFeatures(live) {
39
+ const features = declaredFields(live);
40
+ if (JSON.stringify(declaredFields(this.config.features)) ===
41
+ JSON.stringify(features)) {
42
+ return false;
43
+ }
44
+ const configContent = JSON.parse(this.getContent());
45
+ if (Object.keys(features).length > 0) {
46
+ configContent[this.configName].features = features;
47
+ }
48
+ else {
49
+ delete configContent[this.configName].features;
50
+ }
51
+ this.setContent(JSON.stringify(configContent, null, 2));
52
+ return true;
53
+ }
54
+ /**
55
+ * Takes over the version tags of the installation. A tag the installation leaves at `latest` is
56
+ * removed from the file.
57
+ *
58
+ * @returns whether a tag changed
59
+ */
60
+ updateVersions(live) {
61
+ if (JSON.stringify(versionsOfConfig(this.config)) === JSON.stringify(live)) {
62
+ return false;
63
+ }
64
+ const configContent = JSON.parse(this.getContent());
65
+ const others = Object.entries(configContent[this.configName]).filter(([key]) => !(key in live));
66
+ configContent[this.configName] = {
67
+ ...Object.fromEntries(others),
68
+ ...declaredFields(live),
69
+ };
70
+ this.setContent(JSON.stringify(configContent, null, 2));
71
+ return true;
72
+ }
31
73
  updateConfigByContent() {
32
74
  const configsResult = safe(() => {
33
75
  return JSON.parse(this.getContent());
@@ -1,6 +1,7 @@
1
1
  import type { AssetVersions } from "../../bundler/index.js";
2
2
  /**
3
- * The installation features of a config. `null` leaves a feature at its default.
3
+ * The installation features of a config, under the field names the installation stores. `sk deploy` sends
4
+ * them and `sk pull` writes them back. An omitted feature is `null`, so a deploy resets it.
4
5
  */
5
6
  export interface CustomerFeatures {
6
7
  /**
@@ -9,8 +10,30 @@ export interface CustomerFeatures {
9
10
  * writes `SpeedKit.config`.
10
11
  */
11
12
  enableSpeedKitConfigPlugins?: boolean | null;
13
+ /** The server embeds the config into the service worker as well. */
14
+ embeddedConfig?: boolean | null;
12
15
  [feature: string]: unknown;
13
16
  }
17
+ /** The fields that are set, without the `null` ones. */
18
+ export declare function declaredFields(features?: Record<string, unknown> | null): Record<string, unknown>;
19
+ /**
20
+ * The fields whose value in `local` differs from `live`, with the value of `local`. A field that either
21
+ * side omits is `null`.
22
+ */
23
+ export declare function changedFields(local?: Record<string, unknown> | null, live?: Record<string, unknown> | null): Record<string, unknown>;
24
+ /** Each version tag of a config, with the field of the installation that stores it. */
25
+ export declare const VERSION_FIELDS: {
26
+ readonly speedKitVersion: "swVersion";
27
+ readonly rumPluginsVersion: "rumVersion";
28
+ readonly ppVersion: "ppVersion";
29
+ readonly configPluginsVersion: "configPluginsVersion";
30
+ readonly documentHandlerVersion: "documentHandlerVersion";
31
+ };
32
+ export type VersionTag = keyof typeof VERSION_FIELDS;
33
+ /** The version tags of a config. A blank or omitted tag is `null`, which means `latest`. */
34
+ export declare function versionsOfConfig(config?: Partial<Record<VersionTag, unknown>> | null): Record<VersionTag, unknown>;
35
+ /** The version tags an installation stores, under the names of the config. */
36
+ export declare function versionsOfInstall(install?: object | null): Record<VersionTag, unknown>;
14
37
  export interface CustomerConfigs {
15
38
  production: CustomerConfig;
16
39
  [configName: string]: CustomerConfig;
@@ -42,7 +65,7 @@ export declare class CustomerConfig {
42
65
  */
43
66
  readonly speedKitVersion?: string;
44
67
  /** The tag of RUM for the `enableSpeedKitConfigPlugins` feature, see {@link speedKitVersion}. */
45
- readonly rumPluginVersion?: string;
68
+ readonly rumPluginsVersion?: string;
46
69
  /** The tag of predictive preloading for the `enableSpeedKitConfigPlugins` feature, see {@link speedKitVersion}. */
47
70
  readonly ppVersion?: string;
48
71
  /** The tag of the speed-kit-config plugins for the `enableSpeedKitConfigPlugins` feature, see {@link speedKitVersion}. */
@@ -1,4 +1,41 @@
1
1
  import CustomerConfigError from "../error/customer-config-error.js";
2
+ /** The fields that are set, without the `null` ones. */
3
+ export function declaredFields(features) {
4
+ return Object.fromEntries(Object.entries(features ?? {}).filter(([, value]) => value !== null && value !== undefined));
5
+ }
6
+ /**
7
+ * The fields whose value in `local` differs from `live`, with the value of `local`. A field that either
8
+ * side omits is `null`.
9
+ */
10
+ export function changedFields(local, live) {
11
+ const names = new Set([
12
+ ...Object.keys(local ?? {}),
13
+ ...Object.keys(live ?? {}),
14
+ ]);
15
+ return Object.fromEntries([...names]
16
+ .map((name) => [name, local?.[name] ?? null])
17
+ .filter(([name, value]) => JSON.stringify(value) !== JSON.stringify(live?.[name] ?? null)));
18
+ }
19
+ /** Each version tag of a config, with the field of the installation that stores it. */
20
+ export const VERSION_FIELDS = {
21
+ speedKitVersion: "swVersion",
22
+ rumPluginsVersion: "rumVersion",
23
+ ppVersion: "ppVersion",
24
+ configPluginsVersion: "configPluginsVersion",
25
+ documentHandlerVersion: "documentHandlerVersion",
26
+ };
27
+ /** The version tags of a config. A blank or omitted tag is `null`, which means `latest`. */
28
+ export function versionsOfConfig(config) {
29
+ return Object.fromEntries(Object.keys(VERSION_FIELDS).map((tag) => [tag, config?.[tag] || null]));
30
+ }
31
+ /** The version tags an installation stores, under the names of the config. */
32
+ export function versionsOfInstall(install) {
33
+ const fields = (install ?? {});
34
+ return Object.fromEntries(Object.entries(VERSION_FIELDS).map(([tag, field]) => [
35
+ tag,
36
+ fields[field] || null,
37
+ ]));
38
+ }
2
39
  export class CustomerConfig {
3
40
  app;
4
41
  origins;
@@ -26,7 +63,7 @@ export class CustomerConfig {
26
63
  */
27
64
  speedKitVersion;
28
65
  /** The tag of RUM for the `enableSpeedKitConfigPlugins` feature, see {@link speedKitVersion}. */
29
- rumPluginVersion;
66
+ rumPluginsVersion;
30
67
  /** The tag of predictive preloading for the `enableSpeedKitConfigPlugins` feature, see {@link speedKitVersion}. */
31
68
  ppVersion;
32
69
  /** The tag of the speed-kit-config plugins for the `enableSpeedKitConfigPlugins` feature, see {@link speedKitVersion}. */
@@ -52,17 +89,17 @@ export class CustomerConfig {
52
89
  this.needsCustomerApproval = needsCustomerApproval;
53
90
  this.features = features;
54
91
  this.speedKitVersion = versions.speedKitVersion;
55
- this.rumPluginVersion = versions.rumPluginVersion;
92
+ this.rumPluginsVersion = versions.rumPluginsVersion;
56
93
  this.ppVersion = versions.ppVersion;
57
94
  this.configPluginsVersion = versions.configPluginsVersion;
58
95
  this.documentHandlerVersion = versions.documentHandlerVersion;
59
96
  }
60
97
  static createFrom(configFile, configName) {
61
- const { app, origins, domain, swPath, scope, appDomain, installPath, installParams, name, forceInstall, chromeFlags, dependencies, needsCustomerApproval, features, speedKitVersion, rumPluginVersion, ppVersion, configPluginsVersion, documentHandlerVersion, } = configFile;
98
+ const { app, origins, domain, swPath, scope, appDomain, installPath, installParams, name, forceInstall, chromeFlags, dependencies, needsCustomerApproval, features, speedKitVersion, rumPluginsVersion, ppVersion, configPluginsVersion, documentHandlerVersion, } = configFile;
62
99
  return new CustomerConfig(new RequiredParameter("app", app).isString().getValue(), new RequiredParameter("origins", origins).isArray().getValue(), domain, new RequiredParameter("swPath", swPath).isString().getValue(), new RequiredParameter("scope", scope).isString().getValue(), appDomain || `${app}.app.baqend.com`, installPath ||
63
100
  `https://${app}.app.baqend.com/v1/speedkit/install.js?d=${name || configName}`, installParams || 'async="" crossorigin="anonymous"', name, forceInstall || false, chromeFlags, dependencies || {}, needsCustomerApproval || false, features || {}, {
64
101
  speedKitVersion,
65
- rumPluginVersion,
102
+ rumPluginsVersion,
66
103
  ppVersion,
67
104
  configPluginsVersion,
68
105
  documentHandlerVersion,
@@ -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 `embeddedConfig` 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 `embeddedConfig` feature: the service worker embeds the config too. */
226
+ export function embedsConfigInServiceWorker(customer) {
227
+ return (usesConfigPlugins(customer) && customer.features?.embeddedConfig === 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);
@@ -1,4 +1,4 @@
1
- import { InstallResourceFile, } from "../integration-api/index.js";
1
+ import { InstallResourceFile, versionsOfInstall, } from "../integration-api/index.js";
2
2
  import { InstallResourceToFileMapping } from "./index.js";
3
3
  import { safe } from "../../helpers/safe.js";
4
4
  import { execSync } from "node:child_process";
@@ -107,13 +107,31 @@ export class PullService {
107
107
  async handleConfigCustomer(installResource) {
108
108
  const customerConfigFile = this.fileList.getCustomerConfig();
109
109
  const config = customerConfigFile.config;
110
- if (JSON.stringify(installResource.origins.sort()) !==
111
- JSON.stringify(config.origins.sort())) {
110
+ const updatesOrigins = JSON.stringify(installResource.origins.sort()) !==
111
+ JSON.stringify(config.origins.sort());
112
+ if (updatesOrigins) {
112
113
  this.cli.writeWarning(`update: config_customer(origins)`);
113
114
  customerConfigFile.updateOrigins(installResource.origins);
115
+ }
116
+ else {
117
+ this.cli.writeSuccess("equal, skip: config_customer(origins)");
118
+ }
119
+ const updatesFeatures = customerConfigFile.updateFeatures(installResource.features);
120
+ if (updatesFeatures) {
121
+ this.cli.writeWarning(`update: config_customer(features)`);
122
+ }
123
+ else {
124
+ this.cli.writeSuccess("equal, skip: config_customer(features)");
125
+ }
126
+ const updatesVersions = customerConfigFile.updateVersions(versionsOfInstall(installResource));
127
+ if (updatesVersions) {
128
+ this.cli.writeWarning(`update: config_customer(versions)`);
129
+ }
130
+ else {
131
+ this.cli.writeSuccess("equal, skip: config_customer(versions)");
132
+ }
133
+ if (updatesOrigins || updatesFeatures || updatesVersions) {
114
134
  await customerConfigFile.updateFile();
115
- return;
116
135
  }
117
- this.cli.writeSuccess("equal, skip: config_customer(origins)");
118
136
  }
119
137
  }
@@ -1788,5 +1788,5 @@
1788
1788
  ]
1789
1789
  }
1790
1790
  },
1791
- "version": "4.44.0-beta.5"
1791
+ "version": "4.44.0-beta.7"
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.7",
5
5
  "author": {
6
6
  "name": "Baqend.com",
7
7
  "email": "info@baqend.com"