@sdeverywhere/plugin-check 0.1.4 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/sde-check.js +60 -0
- package/dist/index.cjs +64 -37
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +60 -39
- package/dist/index.js.map +1 -1
- package/package.json +13 -6
- package/template-bundle/src/bundle.ts +1 -9
- package/template-bundle/src/empty-model-spec.ts +2 -0
- package/template-report/index.html +10 -0
- package/template-report/package.json +1 -1
- package/template-report/src/env.d.ts +1 -0
- package/template-report/src/index.ts +144 -13
- package/template-report/tsconfig.json +2 -2
- package/template-tests/src/index.ts +2 -5
- package/template-tests/tsconfig.json +3 -2
package/bin/sde-check.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* This is the entrypoint for the `sde-check` CLI, which provides commands
|
|
5
|
+
* that work in conjunction with `@sdeverywhere/plugin-check`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { copyFileSync, existsSync, mkdirSync } from 'fs'
|
|
9
|
+
import { join as joinPath } from 'path'
|
|
10
|
+
|
|
11
|
+
function printUsage() {
|
|
12
|
+
console.log()
|
|
13
|
+
console.log('Usage:')
|
|
14
|
+
console.log(' sim-check baseline --save\t\tcopy the latest bundle to the `baselines` directory')
|
|
15
|
+
// console.log(' sim-check baseline --clear-all\tremove all bundles from the `baselines` directory')
|
|
16
|
+
console.log()
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function timestamp() {
|
|
20
|
+
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(len, chr)
|
|
21
|
+
|
|
22
|
+
const d = new Date()
|
|
23
|
+
const year = d.getFullYear()
|
|
24
|
+
const month = padL(d.getMonth() + 1)
|
|
25
|
+
const day = padL(d.getDate())
|
|
26
|
+
const hours = padL(d.getHours())
|
|
27
|
+
const minutes = padL(d.getMinutes())
|
|
28
|
+
const seconds = padL(d.getSeconds())
|
|
29
|
+
|
|
30
|
+
return `${year}-${month}-${day}--${hours}-${minutes}-${seconds}`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const args = process.argv.slice(2)
|
|
34
|
+
if (args.length !== 2 || args[0] !== 'baseline') {
|
|
35
|
+
printUsage()
|
|
36
|
+
process.exit(1)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (args[1] !== '--save') {
|
|
40
|
+
printUsage()
|
|
41
|
+
process.exit(1)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// TODO: For now we make a number of assumptions (e.g., that the bundle will be copied to
|
|
45
|
+
// the `baselines` directory under the current working directory, that the bundle filename
|
|
46
|
+
// will contain the current timestamp); should make these configurable
|
|
47
|
+
const prepDir = joinPath(process.cwd(), 'sde-prep')
|
|
48
|
+
const srcBundleFile = joinPath(prepDir, 'check-bundle.js')
|
|
49
|
+
if (!existsSync(srcBundleFile)) {
|
|
50
|
+
console.error(`ERROR: No 'check-bundle.js' file found in 'sde-prep' directory`)
|
|
51
|
+
process.exit(1)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const baselinesDir = joinPath(process.cwd(), 'baselines')
|
|
55
|
+
if (!existsSync(baselinesDir)) {
|
|
56
|
+
mkdirSync(baselinesDir, { recursive: true })
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const dstBundleFile = joinPath(baselinesDir, `${timestamp()}.js`)
|
|
60
|
+
copyFileSync(srcBundleFile, dstBundleFile)
|
package/dist/index.cjs
CHANGED
|
@@ -2,22 +2,8 @@ var __create = Object.create;
|
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
6
5
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
6
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
9
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
10
|
-
var __spreadValues = (a, b) => {
|
|
11
|
-
for (var prop in b || (b = {}))
|
|
12
|
-
if (__hasOwnProp.call(b, prop))
|
|
13
|
-
__defNormalProp(a, prop, b[prop]);
|
|
14
|
-
if (__getOwnPropSymbols)
|
|
15
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
16
|
-
if (__propIsEnum.call(b, prop))
|
|
17
|
-
__defNormalProp(a, prop, b[prop]);
|
|
18
|
-
}
|
|
19
|
-
return a;
|
|
20
|
-
};
|
|
21
7
|
var __export = (target, all) => {
|
|
22
8
|
for (var name in all)
|
|
23
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -30,7 +16,10 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
30
16
|
}
|
|
31
17
|
return to;
|
|
32
18
|
};
|
|
33
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
21
|
+
mod
|
|
22
|
+
));
|
|
34
23
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
35
24
|
|
|
36
25
|
// src/index.ts
|
|
@@ -44,6 +33,7 @@ module.exports = __toCommonJS(src_exports);
|
|
|
44
33
|
var import_path4 = require("path");
|
|
45
34
|
var import_url4 = require("url");
|
|
46
35
|
var import_vite = require("vite");
|
|
36
|
+
var import_chokidar = __toESM(require("chokidar"), 1);
|
|
47
37
|
var import_check_core2 = require("@sdeverywhere/check-core");
|
|
48
38
|
|
|
49
39
|
// src/run-suite.ts
|
|
@@ -162,6 +152,7 @@ function printPerfStats(context, compareConfig, report) {
|
|
|
162
152
|
}
|
|
163
153
|
|
|
164
154
|
// src/vite-config-for-bundle.ts
|
|
155
|
+
var import_fs = require("fs");
|
|
165
156
|
var import_path = require("path");
|
|
166
157
|
var import_url = require("url");
|
|
167
158
|
var import_plugin_node_resolve = require("@rollup/plugin-node-resolve");
|
|
@@ -187,22 +178,36 @@ function sdeNameForVensimVarName(varName) {
|
|
|
187
178
|
var import_meta = {};
|
|
188
179
|
var __filename = (0, import_url.fileURLToPath)(import_meta.url);
|
|
189
180
|
var __dirname = (0, import_path.dirname)(__filename);
|
|
190
|
-
function injectModelSpec(modelSpec) {
|
|
181
|
+
function injectModelSpec(prepDir, modelSpec) {
|
|
191
182
|
const inputSpecs = modelSpec.inputs.map((i) => {
|
|
192
|
-
return
|
|
193
|
-
varId: sdeNameForVensimVarName(i.varName)
|
|
194
|
-
|
|
183
|
+
return {
|
|
184
|
+
varId: sdeNameForVensimVarName(i.varName),
|
|
185
|
+
...i
|
|
186
|
+
};
|
|
195
187
|
});
|
|
196
188
|
const outputSpecs = modelSpec.outputs.map((o) => {
|
|
197
|
-
return
|
|
198
|
-
varId: sdeNameForVensimVarName(o.varName)
|
|
199
|
-
|
|
189
|
+
return {
|
|
190
|
+
varId: sdeNameForVensimVarName(o.varName),
|
|
191
|
+
...o
|
|
192
|
+
};
|
|
200
193
|
});
|
|
194
|
+
function stagedFileSize(filename) {
|
|
195
|
+
const path = (0, import_path.join)(prepDir, "staged", "model", filename);
|
|
196
|
+
if ((0, import_fs.existsSync)(path)) {
|
|
197
|
+
return (0, import_fs.statSync)(path).size;
|
|
198
|
+
} else {
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const modelSizeInBytes = stagedFileSize("wasm-model.js");
|
|
203
|
+
const dataSizeInBytes = stagedFileSize("static-data.ts");
|
|
201
204
|
const moduleSrc = `
|
|
202
205
|
export const startTime = ${modelSpec.startTime};
|
|
203
206
|
export const endTime = ${modelSpec.endTime};
|
|
204
207
|
export const inputSpecs = ${JSON.stringify(inputSpecs)};
|
|
205
208
|
export const outputSpecs = ${JSON.stringify(outputSpecs)};
|
|
209
|
+
export const modelSizeInBytes = ${modelSizeInBytes};
|
|
210
|
+
export const dataSizeInBytes = ${dataSizeInBytes};
|
|
206
211
|
`;
|
|
207
212
|
const virtualModuleId = "virtual:model-spec";
|
|
208
213
|
const resolvedVirtualModuleId = "\0" + virtualModuleId;
|
|
@@ -250,7 +255,7 @@ async function createViteConfigForBundle(prepDir, modelSpec) {
|
|
|
250
255
|
]
|
|
251
256
|
},
|
|
252
257
|
plugins: [
|
|
253
|
-
injectModelSpec(modelSpec)
|
|
258
|
+
injectModelSpec(prepDir, modelSpec)
|
|
254
259
|
],
|
|
255
260
|
build: {
|
|
256
261
|
outDir,
|
|
@@ -283,12 +288,17 @@ let __non_webpack_require__ = () => {
|
|
|
283
288
|
// src/vite-config-for-report.ts
|
|
284
289
|
var import_path2 = require("path");
|
|
285
290
|
var import_url2 = require("url");
|
|
291
|
+
var import_plugin_replace = __toESM(require("@rollup/plugin-replace"), 1);
|
|
286
292
|
var import_meta2 = {};
|
|
287
293
|
var __filename2 = (0, import_url2.fileURLToPath)(import_meta2.url);
|
|
288
294
|
var __dirname2 = (0, import_path2.dirname)(__filename2);
|
|
289
|
-
function createViteConfigForReport(options, prepDir, currentBundleName, currentBundlePath, testConfigPath, suiteSummary) {
|
|
295
|
+
function createViteConfigForReport(options, projDir, prepDir, currentBundleName, currentBundlePath, testConfigPath, suiteSummary) {
|
|
290
296
|
var _a;
|
|
291
297
|
const root = (0, import_path2.resolve)(__dirname2, "..", "template-report");
|
|
298
|
+
const templateSrcDir = (0, import_path2.resolve)(root, "src");
|
|
299
|
+
const relProjDir = (0, import_path2.relative)(templateSrcDir, projDir);
|
|
300
|
+
const relProjDirPath = relProjDir.replaceAll("\\", "/");
|
|
301
|
+
const baselinesPath = `${relProjDirPath}/baselines/*.js`;
|
|
292
302
|
let reportPath;
|
|
293
303
|
if (options == null ? void 0 : options.reportPath) {
|
|
294
304
|
reportPath = options.reportPath;
|
|
@@ -348,7 +358,14 @@ function createViteConfigForReport(options, prepDir, currentBundleName, currentB
|
|
|
348
358
|
__BASELINE_NAME__: JSON.stringify(((_a = options == null ? void 0 : options.baseline) == null ? void 0 : _a.name) || ""),
|
|
349
359
|
__CURRENT_NAME__: JSON.stringify(currentBundleName)
|
|
350
360
|
},
|
|
351
|
-
plugins: [
|
|
361
|
+
plugins: [
|
|
362
|
+
(0, import_plugin_replace.default)({
|
|
363
|
+
preventAssignment: true,
|
|
364
|
+
values: {
|
|
365
|
+
__BASELINE_BUNDLES_PATH__: JSON.stringify(baselinesPath)
|
|
366
|
+
}
|
|
367
|
+
})
|
|
368
|
+
],
|
|
352
369
|
build: {
|
|
353
370
|
outDir,
|
|
354
371
|
assetsDir: "",
|
|
@@ -378,8 +395,6 @@ function createViteConfigForReport(options, prepDir, currentBundleName, currentB
|
|
|
378
395
|
// src/vite-config-for-tests.ts
|
|
379
396
|
var import_path3 = require("path");
|
|
380
397
|
var import_url3 = require("url");
|
|
381
|
-
var import_vite_plugin_glob = __toESM(require("vite-plugin-glob"), 1);
|
|
382
|
-
var import_plugin_replace = __toESM(require("@rollup/plugin-replace"), 1);
|
|
383
398
|
var import_meta3 = {};
|
|
384
399
|
var __filename3 = (0, import_url3.fileURLToPath)(import_meta3.url);
|
|
385
400
|
var __dirname3 = (0, import_path3.dirname)(__filename3);
|
|
@@ -394,15 +409,9 @@ function createViteConfigForTests(projDir, prepDir, mode) {
|
|
|
394
409
|
configFile: false,
|
|
395
410
|
root,
|
|
396
411
|
clearScreen: false,
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
values: {
|
|
401
|
-
__YAML_PATH__: JSON.stringify(yamlPath)
|
|
402
|
-
}
|
|
403
|
-
}),
|
|
404
|
-
(0, import_vite_plugin_glob.default)()
|
|
405
|
-
],
|
|
412
|
+
define: {
|
|
413
|
+
__YAML_PATH__: JSON.stringify(yamlPath)
|
|
414
|
+
},
|
|
406
415
|
build: {
|
|
407
416
|
outDir,
|
|
408
417
|
emptyOutDir: false,
|
|
@@ -436,6 +445,16 @@ var CheckPlugin = class {
|
|
|
436
445
|
const viteConfig = this.createViteConfigForReport(config, testOptions, void 0);
|
|
437
446
|
const server = await (0, import_vite.createServer)(viteConfig);
|
|
438
447
|
await server.listen();
|
|
448
|
+
const baselinesDir = "baselines";
|
|
449
|
+
const watcher = import_chokidar.default.watch(baselinesDir, {
|
|
450
|
+
cwd: config.rootDir,
|
|
451
|
+
ignoreInitial: true,
|
|
452
|
+
awaitWriteFinish: {
|
|
453
|
+
stabilityThreshold: 200
|
|
454
|
+
}
|
|
455
|
+
});
|
|
456
|
+
watcher.on("add", () => server.restart());
|
|
457
|
+
watcher.on("unlink", () => server.restart());
|
|
439
458
|
}
|
|
440
459
|
async postBuild(context, modelSpec) {
|
|
441
460
|
var _a, _b;
|
|
@@ -521,7 +540,15 @@ var CheckPlugin = class {
|
|
|
521
540
|
};
|
|
522
541
|
}
|
|
523
542
|
createViteConfigForReport(config, testOptions, suiteSummary) {
|
|
524
|
-
return createViteConfigForReport(
|
|
543
|
+
return createViteConfigForReport(
|
|
544
|
+
this.options,
|
|
545
|
+
config.rootDir,
|
|
546
|
+
config.prepDir,
|
|
547
|
+
testOptions.currentBundleName,
|
|
548
|
+
testOptions.currentBundlePath,
|
|
549
|
+
testOptions.testConfigPath,
|
|
550
|
+
suiteSummary
|
|
551
|
+
);
|
|
525
552
|
}
|
|
526
553
|
};
|
|
527
554
|
function relativeToSourcePath(filePath) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/plugin.ts","../src/run-suite.ts","../src/vite-config-for-bundle.ts","../src/var-names.ts","../src/vite-config-for-report.ts","../src/vite-config-for-tests.ts"],"sourcesContent":["// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nexport type { CheckBundle, CheckPluginOptions } from './options'\nexport { checkPlugin } from './plugin'\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, join as joinPath, relative } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, ViteDevServer } from 'vite'\nimport { build, createServer } from 'vite'\n\nimport type { BuildContext, ModelSpec, Plugin, ResolvedConfig } from '@sdeverywhere/build'\n\nimport type { Bundle, SuiteSummary } from '@sdeverywhere/check-core'\nimport { createConfig } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\nimport { runTestSuite } from './run-suite'\nimport { createViteConfigForBundle } from './vite-config-for-bundle'\nimport { createViteConfigForReport } from './vite-config-for-report'\nimport { createViteConfigForTests } from './vite-config-for-tests'\n\nexport function checkPlugin(options?: CheckPluginOptions): Plugin {\n return new CheckPlugin(options)\n}\n\ninterface TestOptions {\n currentBundleName: string\n currentBundlePath: string\n testConfigPath: string\n}\n\nclass CheckPlugin implements Plugin {\n private firstBuild = true\n\n constructor(private readonly options?: CheckPluginOptions) {}\n\n async watch(config: ResolvedConfig): Promise<void> {\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so generate a default config in watch mode.\n // The test template uses import.meta.importGlob so that checks are re-run\n // automatically when the *.check.yaml files are changed.\n await this.genTestConfig(config, 'watch')\n }\n\n // For development mode, run Vite in dev mode so that it serves the\n // model-check report locally (with live reload enabled). When a model\n // test file is changed, the tests will be re-run in the browser.\n const testOptions = this.resolveTestOptions(config)\n const viteConfig = this.createViteConfigForReport(config, testOptions, undefined)\n const server: ViteDevServer = await createServer(viteConfig)\n await server.listen()\n }\n\n // TODO: Note that this plugin runs as a `postBuild` step because it currently\n // needs to run after other plugins, and those plugins need to run after the\n // staged files are copied to their final destination(s). We should probably\n // make it configurable so that it can either be run as a `postGenerate` or a\n // `postBuild` step.\n async postBuild(context: BuildContext, modelSpec: ModelSpec): Promise<boolean> {\n const firstBuild = this.firstBuild\n this.firstBuild = false\n\n // For both production builds and local development, generate default bundle\n // in this post-build step each time a source file is changed\n // TODO: We could potentially use watch mode for the bundle similar to\n // what we do for the test config, but the bundle depends on the ModelSpec,\n // which currently isn't made available to the `watch` function\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so generate a default bundle\n context.log('info', 'Generating model check bundle...')\n await this.genCurrentBundle(context.config, modelSpec)\n }\n\n // For production builds (and for the initial build in local development mode),\n // generate default test config in this post-build step\n if (this.options?.testConfigPath === undefined) {\n if (context.config.mode === 'production' || firstBuild) {\n // Test config was not provided, so generate a default config\n context.log('info', 'Generating model check test configuration...')\n await this.genTestConfig(context.config, 'build')\n }\n }\n\n if (context.config.mode === 'production') {\n // For production builds, run the model checks/comparisons, and then\n // inject the results into the generated report\n const testOptions = this.resolveTestOptions(context.config)\n return this.runChecks(context, testOptions)\n } else {\n // Nothing to do here in dev mode; the dev server will refresh and\n // re-run the tests in the browser when changes are detected\n return true\n }\n }\n\n private async genCurrentBundle(config: ResolvedConfig, modelSpec: ModelSpec): Promise<void> {\n const prepDir = config.prepDir\n const viteConfig = await createViteConfigForBundle(prepDir, modelSpec)\n await build(viteConfig)\n }\n\n private async genTestConfig(config: ResolvedConfig, mode: 'build' | 'watch'): Promise<void> {\n const rootDir = config.rootDir\n const prepDir = config.prepDir\n const viteConfig = createViteConfigForTests(rootDir, prepDir, mode)\n await build(viteConfig)\n }\n\n private async runChecks(context: BuildContext, testOptions: TestOptions): Promise<boolean> {\n context.log('info', 'Running model checks...')\n\n // Load the bundles used by the model check/compare configuration. We\n // always initialize the \"current\" bundle.\n const moduleR = await import(relativeToSourcePath(testOptions.currentBundlePath))\n const bundleR = moduleR.createBundle() as Bundle\n const nameR = testOptions.currentBundleName\n\n // Only initialize the \"baseline\" bundle if it is defined and the version\n // is the same as the \"current\" one. If the baseline bundle has a different\n // version, we will skip the comparison tests and only run the checks on the\n // current bundle.\n let bundleL: Bundle\n let nameL: string\n if (this.options?.baseline) {\n const moduleL = await import(relativeToSourcePath(this.options.baseline.path))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rawBundleL: any = moduleL.createBundle() as any\n if (rawBundleL.version === bundleR.version) {\n bundleL = rawBundleL as Bundle\n nameL = this.options.baseline.name\n }\n }\n\n // Get the model check/compare configuration\n const testConfigModule = await import(relativeToSourcePath(testOptions.testConfigPath))\n const checkOptions = await testConfigModule.getConfigOptions(bundleL, bundleR, {\n nameL,\n nameR\n })\n\n // Run the suite of checks and comparisons\n const checkConfig = await createConfig(checkOptions)\n const result = await runTestSuite(context, checkConfig, /*verbose=*/ false)\n\n // Build the report (using Vite)\n context.log('info', 'Building model check report')\n const viteConfig = this.createViteConfigForReport(context.config, testOptions, result.suiteSummary)\n await build(viteConfig)\n\n // context.log('info', 'Done!')\n\n return result.allChecksPassed\n }\n\n private resolveTestOptions(config: ResolvedConfig): TestOptions {\n let currentBundleName: string\n let currentBundlePath: string\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so use a generated bundle\n currentBundleName = 'current'\n currentBundlePath = joinPath(config.prepDir, 'check-bundle.js')\n } else {\n // Use the provided bundle\n currentBundleName = this.options.current.name\n currentBundlePath = this.options.current.path\n }\n\n let testConfigPath: string\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so use a generated config\n testConfigPath = joinPath(config.prepDir, 'check-tests.js')\n } else {\n // Use the provided test config\n testConfigPath = this.options.testConfigPath\n }\n\n return {\n currentBundleName,\n currentBundlePath,\n testConfigPath\n }\n }\n\n private createViteConfigForReport(\n config: ResolvedConfig,\n testOptions: TestOptions,\n suiteSummary: SuiteSummary | undefined\n ): InlineConfig {\n return createViteConfigForReport(\n this.options,\n config.prepDir,\n testOptions.currentBundleName,\n testOptions.currentBundlePath,\n testOptions.testConfigPath,\n suiteSummary\n )\n }\n}\n\n/**\n * Return a Unix-style path (e.g. '../../foo.js') that is relative to the directory of\n * the current source file. This can be used to construct a path that is safe for\n * dynamic import on either Unix or Windows.\n *\n * @param filePath The path to make relative.\n */\nfunction relativeToSourcePath(filePath: string): string {\n const srcDir = dirname(fileURLToPath(import.meta.url))\n const relPath = relative(srcDir, filePath)\n return relPath.replaceAll('\\\\', '/')\n}\n","// Copyright (c) 2021-2022 Climate Interactive / New Venture Fund\n\nimport { performance } from 'perf_hooks'\n\nimport pico from 'picocolors'\n\nimport type { BuildContext } from '@sdeverywhere/build'\n\nimport type {\n Config,\n CompareReport,\n PerfReport,\n RunSuiteCallbacks,\n CheckReport,\n CheckStatus,\n CompareConfig,\n CheckTestReport,\n SuiteSummary\n} from '@sdeverywhere/check-core'\nimport {\n datasetMessage,\n predicateMessage,\n runSuite,\n scenarioMessage,\n suiteSummaryFromReport\n} from '@sdeverywhere/check-core'\n\nexport interface RunTestSuiteResult {\n allChecksPassed: boolean\n suiteSummary: SuiteSummary\n}\n\n/**\n * Runs the test suite.\n */\nexport async function runTestSuite(\n context: BuildContext,\n config: Config,\n verbose: boolean\n): Promise<RunTestSuiteResult> {\n return new Promise((resolve, reject) => {\n const t0 = performance.now()\n let lastPctByInc: number\n const callbacks: RunSuiteCallbacks = {\n onProgress: progress => {\n const pct = Math.round(progress * 100)\n const pctByInc = Math.floor(pct / 5) * 5\n if (lastPctByInc === undefined || pctByInc > lastPctByInc) {\n lastPctByInc = pctByInc\n context.log('info', `${pctByInc}%`)\n }\n },\n onComplete: report => {\n try {\n const t1 = performance.now()\n const elapsed = ((t1 - t0) / 1000).toFixed(1)\n context.log('info', `\\nTest suite completed in ${elapsed}s`)\n\n // Print check summary to the console\n const allChecksPassed = printCheckSummary(context, report.checkReport, verbose)\n\n if (report.compareReport) {\n // Print the perf stats to the console\n printPerfStats(context, config.compare, report.compareReport)\n }\n\n // Convert check and compare reports to terse form that only includes\n // failed/errored checks or comparisons with differences\n // TODO: The terse form was originally used when we had to write the\n // results to a JSON file and then read them back in when building\n // the report, but we no longer use that intermediate file, so there's\n // less reason to use the terse form (since it requires the web app\n // code to reconstruct the results). But for now, we will continue\n // to use the terse form, and later we can update the app code.\n const suiteSummary = suiteSummaryFromReport(report)\n\n resolve({\n allChecksPassed,\n suiteSummary\n })\n } catch (e) {\n reject(e)\n }\n },\n onError: error => {\n reject(error)\n }\n }\n runSuite(config, callbacks)\n })\n}\n\nfunction printCheckSummary(context: BuildContext, checkReport: CheckReport, verbose: boolean): boolean {\n function printResult(indent: number, status: CheckStatus, text: string): void {\n if (!verbose && status === 'passed' && indent > 1) {\n return\n }\n let statusChar: string\n switch (status) {\n case 'passed':\n statusChar = '✓'\n break\n case 'failed':\n statusChar = '✗'\n break\n case 'error':\n statusChar = '‼'\n break\n default:\n statusChar = ''\n break\n }\n const msg = `${' '.repeat(indent)}${statusChar} ${text}`\n context.log('info', status === 'passed' ? pico.green(msg) : pico.red(msg))\n }\n\n function bold(s: string): string {\n return pico.bold(s)\n }\n\n function printTest(test: CheckTestReport): void {\n const msg = `${test.name}${verbose || test.status !== 'passed' ? ':' : ''}`\n printResult(1, test.status, msg)\n }\n\n let allPassed = true\n context.log('info', '\\nCheck results:')\n for (const group of checkReport.groups) {\n context.log('info', `\\n${group.name}`)\n\n for (const test of group.tests) {\n if (test.status !== 'passed') {\n allPassed = false\n }\n printTest(test)\n\n for (const scenario of test.scenarios) {\n printResult(3, scenario.status, scenarioMessage(scenario, bold))\n\n for (const dataset of scenario.datasets) {\n printResult(5, dataset.status, datasetMessage(dataset, bold))\n\n for (const predicate of dataset.predicates) {\n printResult(7, predicate.result.status, predicateMessage(predicate, bold))\n }\n }\n }\n }\n }\n context.log('info', '')\n\n return allPassed\n}\n\nfunction stat(label: string, n: number): string {\n return `${label}=${n.toFixed(1)}ms`\n}\n\nfunction printPerfReportLine(context: BuildContext, perfReport: PerfReport): void {\n const avg = stat('avg', perfReport.avgTime)\n const min = stat('min', perfReport.minTime)\n const max = stat('max', perfReport.maxTime)\n context.log('info', ` ${avg} ${min} ${max}`)\n}\n\nfunction printPerfStats(context: BuildContext, compareConfig: CompareConfig, report: CompareReport): void {\n context.log('info', '\\nPerformance stats:')\n context.log('info', ` ${compareConfig.bundleL.name}:`)\n printPerfReportLine(context, report.perfReportL)\n context.log('info', ` ${compareConfig.bundleR.name}:`)\n printPerfReportLine(context, report.perfReportR)\n context.log('info', '')\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport type { ModelSpec } from '@sdeverywhere/build'\nimport { dirname, join as joinPath, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, Plugin as VitePlugin } from 'vite'\nimport { nodeResolve } from '@rollup/plugin-node-resolve'\n\nimport { sdeNameForVensimVarName } from './var-names'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\n/**\n * This is a virtual module plugin used to inject model-specific configuration\n * values into the generated worker bundle.\n *\n * This follows the \"Virtual Modules Convention\" described here:\n * https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention\n *\n * TODO: This could be simplified by using `vite-plugin-virtual` but that\n * doesn't seem to be working correctly in an ESM setting\n */\nfunction injectModelSpec(modelSpec: ModelSpec): VitePlugin {\n // Include the SDE variable ID with each spec\n const inputSpecs = modelSpec.inputs.map(i => {\n return {\n varId: sdeNameForVensimVarName(i.varName),\n ...i\n }\n })\n const outputSpecs = modelSpec.outputs.map(o => {\n return {\n varId: sdeNameForVensimVarName(o.varName),\n ...o\n }\n })\n\n const moduleSrc = `\nexport const startTime = ${modelSpec.startTime};\nexport const endTime = ${modelSpec.endTime};\nexport const inputSpecs = ${JSON.stringify(inputSpecs)};\nexport const outputSpecs = ${JSON.stringify(outputSpecs)};\n`\n\n const virtualModuleId = 'virtual:model-spec'\n const resolvedVirtualModuleId = '\\0' + virtualModuleId\n\n return {\n name: 'vite-plugin-virtual-custom',\n resolveId(id: string) {\n if (id === virtualModuleId) {\n return resolvedVirtualModuleId\n }\n },\n load(id: string) {\n if (id === resolvedVirtualModuleId) {\n return moduleSrc\n }\n }\n }\n}\n\nexport async function createViteConfigForBundle(prepDir: string, modelSpec: ModelSpec): Promise<InlineConfig> {\n // Use `template-bundle` as the root directory for the bundle project\n const root = resolvePath(__dirname, '..', 'template-bundle')\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n // Use the model worker from the staged directory\n // TODO: Make this configurable?\n const modelWorkerPath = joinPath(prepDir, 'staged', 'model', 'worker.js?raw')\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n // Configure path aliases\n resolve: {\n alias: [\n // Inject the configured model worker\n {\n find: '@_model_worker_',\n replacement: modelWorkerPath\n },\n\n // XXX: Prevent Vite from using the `browser` section of `threads/package.json`\n // since we want to force the use of the general module (under dist-esm) that chooses\n // the correct implementation (Web Worker vs worker_threads) at runtime. Currently\n // Vite's library mode is browser focused, so using a `customResolver` seems to be\n // the easiest way to prevent Vite from picking up the `browser` exports.\n {\n find: 'threads',\n replacement: 'threads',\n customResolver: async function (source, importer, options) {\n // Note that we need to use `resolveId.call` here in order to provide the\n // right `this` context, which provides Rollup plugin functionality\n const customResolver = nodeResolve({ browser: false })\n const resolved = await customResolver.resolveId.call(this, source, importer, options)\n // Force the use of the `dist-esm` variant of the threads.js package\n if (source === 'threads/worker') {\n return resolved.id.replace('worker.mjs', 'dist-esm/worker/index.js')\n } else {\n return resolved.id.replace('index.mjs', 'dist-esm/index.js')\n }\n }\n }\n ]\n },\n\n plugins: [\n // Use a virtual module plugin to inject the model spec values\n injectModelSpec(modelSpec)\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-bundle.js'\n },\n\n rollupOptions: {\n // Don't transform Node imports used by threads.js\n external: ['events', 'os', 'path', 'url'],\n\n // XXX: Insert custom code at the top of the generated bundle that defines\n // the special `__non_webpack_require__` function that is used by threads.js\n // in its Node implementation. This import ensures that threads.js uses\n // the native `worker_threads` implementation when using the bundle in a\n // Node environment. When importing the bundle for use in the browser,\n // Vite will transform this import into an empty module (it does not seem\n // to be necessary to define a polyfill).\n output: {\n banner: `\nimport * as worker_threads from 'worker_threads'\nlet __non_webpack_require__ = () => {\n return worker_threads;\n};\n`\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\n/**\n * Helper function that converts a Vensim variable or subscript name\n * into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nfunction sdeNameForVensimName(name: string): string {\n return (\n '_' +\n name\n .trim()\n .replace(/\"/g, '_')\n .replace(/\\s+!$/g, '!')\n .replace(/\\s/g, '_')\n .replace(/,/g, '_')\n .replace(/-/g, '_')\n .replace(/\\./g, '_')\n .replace(/\\$/g, '_')\n .replace(/'/g, '_')\n .replace(/&/g, '_')\n .replace(/%/g, '_')\n .replace(/\\//g, '_')\n .replace(/\\|/g, '_')\n .toLowerCase()\n )\n}\n\n/**\n * Helper function that converts a Vensim variable name (possibly containing\n * subscripts) into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nexport function sdeNameForVensimVarName(varName: string): string {\n const m = varName.match(/([^[]+)(?:\\[([^\\]]+)\\])?/)\n if (!m) {\n throw new Error(`Invalid Vensim name: ${varName}`)\n }\n let id = sdeNameForVensimName(m[1])\n if (m[2]) {\n const subscripts = m[2].split(',').map(x => sdeNameForVensimName(x))\n id += `[${subscripts.join('][')}]`\n }\n\n return id\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, join as joinPath, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { Alias, InlineConfig } from 'vite'\n\nimport type { SuiteSummary } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForReport(\n options: CheckPluginOptions | undefined,\n prepDir: string,\n currentBundleName: string,\n currentBundlePath: string,\n testConfigPath: string,\n suiteSummary: SuiteSummary | undefined\n): InlineConfig {\n // Use `template-report` as the root directory for the report project\n const root = resolvePath(__dirname, '..', 'template-report')\n\n // Calculate output directory relative to the template root\n let reportPath: string\n if (options?.reportPath) {\n reportPath = options.reportPath\n } else {\n reportPath = joinPath(prepDir, 'check-report')\n }\n const outDir = relative(root, reportPath)\n\n // Convert the suite summary to JSON, which is what the app currently expects\n const suiteSummaryJson = suiteSummary ? JSON.stringify(suiteSummary) : ''\n\n const alias = (find: string, replacement: string) => {\n return {\n find,\n replacement\n } as Alias\n }\n\n // XXX: This provides custom handling for Node built-ins such as 'events' that are\n // referenced by the check bundle (specifically in the Node implementation of\n // threads.js). These are not actually used in the browser, so we just need\n // to provide no-op polyfills for these.\n const noopPolyfillAlias = (find: string) => {\n return {\n find,\n replacement: '/polyfills/noop-polyfills.ts'\n } as Alias\n }\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Use `.` as the base directory (instead of the default `/`); this controls\n // how the path to the js/css files are generated in `index.html`\n base: '',\n\n // Use a custom cache directory under `prepDir`, as otherwise Vite will use\n // `packages/plugin-check/template-report/node_modules/.vite`, and we want to\n // avoid generating files in `template-report` (which should be read-only)\n cacheDir: joinPath(prepDir, '.vite-check-report'),\n\n // Load static files from `static` (instead of the default `public`)\n // publicDir: 'static',\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO\n // logLevel: 'silent',\n\n optimizeDeps: {\n // Prevent Vite from examining other html files when scanning entrypoints\n // for dependency optimization\n entries: ['index.html'],\n\n // XXX: When plugin-check is installed via pnpm, the Vite dev server seems\n // to have no trouble resolving other dependencies using the optimizeDeps\n // mechanism. However, this fails when the package is installed via yarn\n // or npm (probably due to the fact that the `template-report` directory\n // is located under the top-level `node_modules` directory); in the browser,\n // there will be \"import not found\" errors for the packages referenced below.\n // As a terrible workaround, explicitly include the direct dependencies so\n // that Vite optimizes them; this works for pnpm, yarn, and npm. We should\n // find a less fragile solution.\n include: [\n // from check-core\n 'assert-never',\n 'ajv',\n 'neverthrow',\n 'yaml',\n // from check-ui-shell\n 'fontfaceobserver',\n 'copy-text-to-clipboard',\n 'chart.js'\n ],\n\n exclude: [\n // XXX: The threads.js implementation references `tiny-worker` as an optional\n // dependency, but it doesn't get used at runtime, so we can just exclude it\n // so that Vite doesn't complain in dev mode\n 'tiny-worker',\n\n // XXX: Similarly, chart.js treats `moment` as an optional dependency, but we\n // don't use it at runtime; we need to exclude it here, otherwise Vite will\n // complain about missing dependencies in dev mode\n 'moment'\n ]\n },\n\n // Configure path aliases\n resolve: {\n alias: [\n // Use the configured \"baseline\" bundle if defined, otherwise use the \"empty\" bundle\n // (which will cause comparison tests to be skipped)\n alias('@_baseline_bundle_', options?.baseline ? options.baseline.path : '/src/empty-bundle.ts'),\n\n // Use the configured \"current\" bundle\n alias('@_current_bundle_', currentBundlePath),\n\n // Use the configured test config file\n alias('@_test_config_', testConfigPath),\n\n // Make the overlay use the `messages.html` file that is written to the prep directory\n alias('@_prep_', prepDir),\n\n // XXX: Include no-op polyfills for these modules that are used in the Node-specific\n // implementation of threads.js; this allows us to use one bundle that works in both\n // Node and browser environments\n noopPolyfillAlias('events'),\n noopPolyfillAlias('os'),\n noopPolyfillAlias('path'),\n noopPolyfillAlias('url')\n ]\n },\n\n // Inject special values into the generated JS\n define: {\n // Inject the summary JSON into the build\n __SUITE_SUMMARY_JSON__: JSON.stringify(suiteSummaryJson),\n\n // Inject the baseline branch name\n __BASELINE_NAME__: JSON.stringify(options?.baseline?.name || ''),\n\n // Inject the current branch name\n __CURRENT_NAME__: JSON.stringify(currentBundleName)\n },\n\n plugins: [\n // Use `vite-plugin-glob` instead of Vite's built-in `import.meta.globEager`\n // because the plugin does a better job of handling HMR when the yaml files\n // are outside of the `template-report` app root directory.\n // globPlugin(),\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n\n // Write js/css files to `public` (instead of the default `<outDir>/assets`)\n assetsDir: '',\n\n rollupOptions: {\n output: {\n // XXX: Prevent vite from creating a separate `vendor.js` file\n manualChunks: undefined\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n },\n\n server: {\n // Run the dev server at `localhost:8081` by default\n port: options?.serverPort || 8081,\n\n // Open the app in the browser by default\n open: '/index.html',\n\n // XXX: Add a small delay, otherwise on macOS we sometimes get multiple\n // change events when a file is saved just once. That is a relatively\n // harmless issue except that it causes redundant messages in the console\n // and can cause extra churn when refreshing the app.\n watch: {\n awaitWriteFinish: {\n stabilityThreshold: 100\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig } from 'vite'\nimport globPlugin from 'vite-plugin-glob'\nimport replace from '@rollup/plugin-replace'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForTests(projDir: string, prepDir: string, mode: 'build' | 'watch'): InlineConfig {\n // Use `template-tests` as the root directory for the tests project\n const root = resolvePath(__dirname, '..', 'template-tests')\n\n // Include `*.check.yaml` files under the configured project root directory. This\n // glob path apparently must be a relative path (relative to the `template-tests/src`\n // directory where the glob is used).\n const templateSrcDir = resolvePath(root, 'src')\n const relProjDir = relative(templateSrcDir, projDir)\n // XXX: The glob pattern must use forward slashes only, so on Windows we need to\n // convert backslashes to slashes\n const relProjDirPath = relProjDir.replaceAll('\\\\', '/')\n // TODO: Use yamlPath from options\n const yamlPath = `${relProjDirPath}/**/*.check.yaml`\n\n // // Read the `package.json` for the template project\n // const pkgPath = resolvePath(root, 'package.json')\n // const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n plugins: [\n // Inject special values into the generated JS\n // TODO: We currently have to use `@rollup/plugin-replace` instead of Vite's\n // built-in `define` feature because the latter does not seem to run before\n // the glob plugin, and that requires the glob to be injected as a literal;\n // `plugin-replace` seems to work as long as we order it before `plugin-glob`.\n // Maybe we can switch back to `define` once we move to Vite 3.x.\n replace({\n preventAssignment: true,\n values: {\n // Inject the glob pattern for matching check yaml files\n __YAML_PATH__: JSON.stringify(yamlPath)\n }\n }),\n\n // Use `vite-plugin-glob` instead of Vite's built-in `import.meta.globEager`\n // because the plugin does a better job of handling HMR when the yaml files\n // are outside of the `template-report` app root directory.\n globPlugin()\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-tests.js'\n },\n\n // Enable watch mode if requested\n watch: mode === 'watch' && {},\n\n rollupOptions: {\n // Prevent dependencies from being included in packaged library\n // TODO: For now we include check-core in the packaged library so that its\n // dependencies are correctly resolved at runtime. Ideally this would only\n // include a couple functions that are used for defining tests, but Vite 2.x\n // does not implement tree shaking for ES libraries, which means the generated\n // library is much larger than it needs to be. Once we upgrade to Vite 3.x,\n // the generated library should be smaller; see related fix:\n // https://github.com/vitejs/vite/pull/8737\n // external: Object.keys(pkg.dependencies)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,mBAAoD;AACpD,kBAA8B;AAG9B,kBAAoC;AAKpC,yBAA6B;;;ACT7B,wBAA4B;AAE5B,wBAAiB;AAejB,wBAMO;AAUP,4BACE,SACA,QACA,SAC6B;AAC7B,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,KAAK,8BAAY,IAAI;AAC3B,QAAI;AACJ,UAAM,YAA+B;AAAA,MACnC,YAAY,cAAY;AACtB,cAAM,MAAM,KAAK,MAAM,WAAW,GAAG;AACrC,cAAM,WAAW,KAAK,MAAM,MAAM,CAAC,IAAI;AACvC,YAAI,iBAAiB,UAAa,WAAW,cAAc;AACzD,yBAAe;AACf,kBAAQ,IAAI,QAAQ,GAAG,WAAW;AAAA,QACpC;AAAA,MACF;AAAA,MACA,YAAY,YAAU;AACpB,YAAI;AACF,gBAAM,KAAK,8BAAY,IAAI;AAC3B,gBAAM,UAAY,OAAK,MAAM,KAAM,QAAQ,CAAC;AAC5C,kBAAQ,IAAI,QAAQ;AAAA,0BAA6B,UAAU;AAG3D,gBAAM,kBAAkB,kBAAkB,SAAS,OAAO,aAAa,OAAO;AAE9E,cAAI,OAAO,eAAe;AAExB,2BAAe,SAAS,OAAO,SAAS,OAAO,aAAa;AAAA,UAC9D;AAUA,gBAAM,eAAe,8CAAuB,MAAM;AAElD,kBAAQ;AAAA,YACN;AAAA,YACA;AAAA,UACF,CAAC;AAAA,QACH,SAAS,GAAP;AACA,iBAAO,CAAC;AAAA,QACV;AAAA,MACF;AAAA,MACA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,uBAAS,OAAO,SAAS,iBAAiB;AAAA,IAChE,OAAO;AAEL,0BAAoB,KAAK,QAAQ,QAAQ;AACzC,0BAAoB,KAAK,QAAQ,QAAQ;AAAA,IAC3C;AAEA,QAAI;AACJ,QAAI,YAAK,YAAL,mBAAc,oBAAmB,QAAW;AAE9C,uBAAiB,uBAAS,OAAO,SAAS,gBAAgB;AAAA,IAC5D,OAAO;AAEL,uBAAiB,KAAK,QAAQ;AAAA,IAChC;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,AAAQ,0BACN,QACA,aACA,cACc;AACd,WAAO,0BACL,KAAK,SACL,OAAO,SACP,YAAY,mBACZ,YAAY,mBACZ,YAAY,gBACZ,YACF;AAAA,EACF;AACF;AASA,8BAA8B,UAA0B;AACtD,QAAM,SAAS,0BAAQ,+BAAc,aAAY,GAAG,CAAC;AACrD,QAAM,UAAU,2BAAS,QAAQ,QAAQ;AACzC,SAAO,QAAQ,WAAW,MAAM,GAAG;AACrC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/plugin.ts","../src/run-suite.ts","../src/vite-config-for-bundle.ts","../src/var-names.ts","../src/vite-config-for-report.ts","../src/vite-config-for-tests.ts"],"sourcesContent":["// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nexport type { CheckBundle, CheckPluginOptions } from './options'\nexport { checkPlugin } from './plugin'\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, join as joinPath, relative } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, ViteDevServer } from 'vite'\nimport { build, createServer } from 'vite'\n\nimport chokidar from 'chokidar'\n\nimport type { BuildContext, ModelSpec, Plugin, ResolvedConfig } from '@sdeverywhere/build'\n\nimport type { Bundle, SuiteSummary } from '@sdeverywhere/check-core'\nimport { createConfig } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\nimport { runTestSuite } from './run-suite'\nimport { createViteConfigForBundle } from './vite-config-for-bundle'\nimport { createViteConfigForReport } from './vite-config-for-report'\nimport { createViteConfigForTests } from './vite-config-for-tests'\n\nexport function checkPlugin(options?: CheckPluginOptions): Plugin {\n return new CheckPlugin(options)\n}\n\ninterface TestOptions {\n currentBundleName: string\n currentBundlePath: string\n testConfigPath: string\n}\n\nclass CheckPlugin implements Plugin {\n private firstBuild = true\n\n constructor(private readonly options?: CheckPluginOptions) {}\n\n async watch(config: ResolvedConfig): Promise<void> {\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so generate a default config in watch mode.\n // The test template uses import.meta.glob so that checks are re-run\n // automatically when the *.check.yaml files are changed.\n await this.genTestConfig(config, 'watch')\n }\n\n // For development mode, run Vite in dev mode so that it serves the\n // model-check report locally (with live reload enabled). When a model\n // test file is changed, the tests will be re-run in the browser.\n const testOptions = this.resolveTestOptions(config)\n const viteConfig = this.createViteConfigForReport(config, testOptions, undefined)\n const server: ViteDevServer = await createServer(viteConfig)\n await server.listen()\n\n // XXX: Currently Vite doesn't reload the page if a file is added/removed\n // in the baselines directory (Vite's import.meta.glob handling doesn't\n // seem to do this automatically), so as a workaround, watch the baselines\n // directory and restart the server if files are added/removed\n // TODO: The same problem also applies to the glob for `.check.yaml` files\n // in the test config, so we should also reload if files match/unmatch\n // the `.check.yaml` glob\n // TODO: Use the baselines directory from the config\n const baselinesDir = 'baselines'\n const watcher = chokidar.watch(baselinesDir, {\n // Watch paths are resolved relative to the project root directory\n cwd: config.rootDir,\n // Don't send initial \"file added\" events\n ignoreInitial: true,\n // XXX: Include a delay, otherwise on macOS we sometimes get multiple\n // change events when a file is saved just once\n awaitWriteFinish: {\n stabilityThreshold: 200\n }\n })\n watcher.on('add', () => server.restart())\n watcher.on('unlink', () => server.restart())\n }\n\n // TODO: Note that this plugin runs as a `postBuild` step because it currently\n // needs to run after other plugins, and those plugins need to run after the\n // staged files are copied to their final destination(s). We should probably\n // make it configurable so that it can either be run as a `postGenerate` or a\n // `postBuild` step.\n async postBuild(context: BuildContext, modelSpec: ModelSpec): Promise<boolean> {\n const firstBuild = this.firstBuild\n this.firstBuild = false\n\n // For both production builds and local development, generate default bundle\n // in this post-build step each time a source file is changed\n // TODO: We could potentially use watch mode for the bundle similar to\n // what we do for the test config, but the bundle depends on the ModelSpec,\n // which currently isn't made available to the `watch` function\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so generate a default bundle\n context.log('info', 'Generating model check bundle...')\n await this.genCurrentBundle(context.config, modelSpec)\n }\n\n // For production builds (and for the initial build in local development mode),\n // generate default test config in this post-build step\n if (this.options?.testConfigPath === undefined) {\n if (context.config.mode === 'production' || firstBuild) {\n // Test config was not provided, so generate a default config\n context.log('info', 'Generating model check test configuration...')\n await this.genTestConfig(context.config, 'build')\n }\n }\n\n if (context.config.mode === 'production') {\n // For production builds, run the model checks/comparisons, and then\n // inject the results into the generated report\n const testOptions = this.resolveTestOptions(context.config)\n return this.runChecks(context, testOptions)\n } else {\n // Nothing to do here in dev mode; the dev server will refresh and\n // re-run the tests in the browser when changes are detected\n return true\n }\n }\n\n private async genCurrentBundle(config: ResolvedConfig, modelSpec: ModelSpec): Promise<void> {\n const prepDir = config.prepDir\n const viteConfig = await createViteConfigForBundle(prepDir, modelSpec)\n await build(viteConfig)\n }\n\n private async genTestConfig(config: ResolvedConfig, mode: 'build' | 'watch'): Promise<void> {\n const rootDir = config.rootDir\n const prepDir = config.prepDir\n const viteConfig = createViteConfigForTests(rootDir, prepDir, mode)\n await build(viteConfig)\n }\n\n private async runChecks(context: BuildContext, testOptions: TestOptions): Promise<boolean> {\n context.log('info', 'Running model checks...')\n\n // Load the bundles used by the model check/compare configuration. We\n // always initialize the \"current\" bundle.\n const moduleR = await import(relativeToSourcePath(testOptions.currentBundlePath))\n const bundleR = moduleR.createBundle() as Bundle\n const nameR = testOptions.currentBundleName\n\n // Only initialize the \"baseline\" bundle if it is defined and the version\n // is the same as the \"current\" one. If the baseline bundle has a different\n // version, we will skip the comparison tests and only run the checks on the\n // current bundle.\n let bundleL: Bundle\n let nameL: string\n if (this.options?.baseline) {\n const moduleL = await import(relativeToSourcePath(this.options.baseline.path))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rawBundleL: any = moduleL.createBundle() as any\n if (rawBundleL.version === bundleR.version) {\n bundleL = rawBundleL as Bundle\n nameL = this.options.baseline.name\n }\n }\n\n // Get the model check/compare configuration\n const testConfigModule = await import(relativeToSourcePath(testOptions.testConfigPath))\n const checkOptions = await testConfigModule.getConfigOptions(bundleL, bundleR, {\n nameL,\n nameR\n })\n\n // Run the suite of checks and comparisons\n const checkConfig = await createConfig(checkOptions)\n const result = await runTestSuite(context, checkConfig, /*verbose=*/ false)\n\n // Build the report (using Vite)\n context.log('info', 'Building model check report')\n const viteConfig = this.createViteConfigForReport(context.config, testOptions, result.suiteSummary)\n await build(viteConfig)\n\n // context.log('info', 'Done!')\n\n return result.allChecksPassed\n }\n\n private resolveTestOptions(config: ResolvedConfig): TestOptions {\n let currentBundleName: string\n let currentBundlePath: string\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so use a generated bundle\n currentBundleName = 'current'\n currentBundlePath = joinPath(config.prepDir, 'check-bundle.js')\n } else {\n // Use the provided bundle\n currentBundleName = this.options.current.name\n currentBundlePath = this.options.current.path\n }\n\n let testConfigPath: string\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so use a generated config\n testConfigPath = joinPath(config.prepDir, 'check-tests.js')\n } else {\n // Use the provided test config\n testConfigPath = this.options.testConfigPath\n }\n\n return {\n currentBundleName,\n currentBundlePath,\n testConfigPath\n }\n }\n\n private createViteConfigForReport(\n config: ResolvedConfig,\n testOptions: TestOptions,\n suiteSummary: SuiteSummary | undefined\n ): InlineConfig {\n return createViteConfigForReport(\n this.options,\n config.rootDir,\n config.prepDir,\n testOptions.currentBundleName,\n testOptions.currentBundlePath,\n testOptions.testConfigPath,\n suiteSummary\n )\n }\n}\n\n/**\n * Return a Unix-style path (e.g. '../../foo.js') that is relative to the directory of\n * the current source file. This can be used to construct a path that is safe for\n * dynamic import on either Unix or Windows.\n *\n * @param filePath The path to make relative.\n */\nfunction relativeToSourcePath(filePath: string): string {\n const srcDir = dirname(fileURLToPath(import.meta.url))\n const relPath = relative(srcDir, filePath)\n return relPath.replaceAll('\\\\', '/')\n}\n","// Copyright (c) 2021-2022 Climate Interactive / New Venture Fund\n\nimport { performance } from 'perf_hooks'\n\nimport pico from 'picocolors'\n\nimport type { BuildContext } from '@sdeverywhere/build'\n\nimport type {\n Config,\n CompareReport,\n PerfReport,\n RunSuiteCallbacks,\n CheckReport,\n CheckStatus,\n CompareConfig,\n CheckTestReport,\n SuiteSummary\n} from '@sdeverywhere/check-core'\nimport {\n datasetMessage,\n predicateMessage,\n runSuite,\n scenarioMessage,\n suiteSummaryFromReport\n} from '@sdeverywhere/check-core'\n\nexport interface RunTestSuiteResult {\n allChecksPassed: boolean\n suiteSummary: SuiteSummary\n}\n\n/**\n * Runs the test suite.\n */\nexport async function runTestSuite(\n context: BuildContext,\n config: Config,\n verbose: boolean\n): Promise<RunTestSuiteResult> {\n return new Promise((resolve, reject) => {\n const t0 = performance.now()\n let lastPctByInc: number\n const callbacks: RunSuiteCallbacks = {\n onProgress: progress => {\n const pct = Math.round(progress * 100)\n const pctByInc = Math.floor(pct / 5) * 5\n if (lastPctByInc === undefined || pctByInc > lastPctByInc) {\n lastPctByInc = pctByInc\n context.log('info', `${pctByInc}%`)\n }\n },\n onComplete: report => {\n try {\n const t1 = performance.now()\n const elapsed = ((t1 - t0) / 1000).toFixed(1)\n context.log('info', `\\nTest suite completed in ${elapsed}s`)\n\n // Print check summary to the console\n const allChecksPassed = printCheckSummary(context, report.checkReport, verbose)\n\n if (report.compareReport) {\n // Print the perf stats to the console\n printPerfStats(context, config.compare, report.compareReport)\n }\n\n // Convert check and compare reports to terse form that only includes\n // failed/errored checks or comparisons with differences\n // TODO: The terse form was originally used when we had to write the\n // results to a JSON file and then read them back in when building\n // the report, but we no longer use that intermediate file, so there's\n // less reason to use the terse form (since it requires the web app\n // code to reconstruct the results). But for now, we will continue\n // to use the terse form, and later we can update the app code.\n const suiteSummary = suiteSummaryFromReport(report)\n\n resolve({\n allChecksPassed,\n suiteSummary\n })\n } catch (e) {\n reject(e)\n }\n },\n onError: error => {\n reject(error)\n }\n }\n runSuite(config, callbacks)\n })\n}\n\nfunction printCheckSummary(context: BuildContext, checkReport: CheckReport, verbose: boolean): boolean {\n function printResult(indent: number, status: CheckStatus, text: string): void {\n if (!verbose && status === 'passed' && indent > 1) {\n return\n }\n let statusChar: string\n switch (status) {\n case 'passed':\n statusChar = '✓'\n break\n case 'failed':\n statusChar = '✗'\n break\n case 'error':\n statusChar = '‼'\n break\n default:\n statusChar = ''\n break\n }\n const msg = `${' '.repeat(indent)}${statusChar} ${text}`\n context.log('info', status === 'passed' ? pico.green(msg) : pico.red(msg))\n }\n\n function bold(s: string): string {\n return pico.bold(s)\n }\n\n function printTest(test: CheckTestReport): void {\n const msg = `${test.name}${verbose || test.status !== 'passed' ? ':' : ''}`\n printResult(1, test.status, msg)\n }\n\n let allPassed = true\n context.log('info', '\\nCheck results:')\n for (const group of checkReport.groups) {\n context.log('info', `\\n${group.name}`)\n\n for (const test of group.tests) {\n if (test.status !== 'passed') {\n allPassed = false\n }\n printTest(test)\n\n for (const scenario of test.scenarios) {\n printResult(3, scenario.status, scenarioMessage(scenario, bold))\n\n for (const dataset of scenario.datasets) {\n printResult(5, dataset.status, datasetMessage(dataset, bold))\n\n for (const predicate of dataset.predicates) {\n printResult(7, predicate.result.status, predicateMessage(predicate, bold))\n }\n }\n }\n }\n }\n context.log('info', '')\n\n return allPassed\n}\n\nfunction stat(label: string, n: number): string {\n return `${label}=${n.toFixed(1)}ms`\n}\n\nfunction printPerfReportLine(context: BuildContext, perfReport: PerfReport): void {\n const avg = stat('avg', perfReport.avgTime)\n const min = stat('min', perfReport.minTime)\n const max = stat('max', perfReport.maxTime)\n context.log('info', ` ${avg} ${min} ${max}`)\n}\n\nfunction printPerfStats(context: BuildContext, compareConfig: CompareConfig, report: CompareReport): void {\n context.log('info', '\\nPerformance stats:')\n context.log('info', ` ${compareConfig.bundleL.name}:`)\n printPerfReportLine(context, report.perfReportL)\n context.log('info', ` ${compareConfig.bundleR.name}:`)\n printPerfReportLine(context, report.perfReportR)\n context.log('info', '')\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { existsSync, statSync } from 'fs'\nimport { dirname, join as joinPath, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, Plugin as VitePlugin } from 'vite'\nimport { nodeResolve } from '@rollup/plugin-node-resolve'\n\nimport type { ModelSpec } from '@sdeverywhere/build'\n\nimport { sdeNameForVensimVarName } from './var-names'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\n/**\n * This is a virtual module plugin used to inject model-specific configuration\n * values into the generated worker bundle.\n *\n * This follows the \"Virtual Modules Convention\" described here:\n * https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention\n *\n * TODO: This could be simplified by using `vite-plugin-virtual` but that\n * doesn't seem to be working correctly in an ESM setting\n */\nfunction injectModelSpec(prepDir: string, modelSpec: ModelSpec): VitePlugin {\n // Include the SDE variable ID with each spec\n const inputSpecs = modelSpec.inputs.map(i => {\n return {\n varId: sdeNameForVensimVarName(i.varName),\n ...i\n }\n })\n const outputSpecs = modelSpec.outputs.map(o => {\n return {\n varId: sdeNameForVensimVarName(o.varName),\n ...o\n }\n })\n\n function stagedFileSize(filename: string): number {\n const path = joinPath(prepDir, 'staged', 'model', filename)\n if (existsSync(path)) {\n return statSync(path).size\n } else {\n return 0\n }\n }\n\n // The size (in bytes) of the `wasm-model.js` file\n // TODO: Ideally we would measure the size of the raw WASM binary, but currently\n // we inline it as a base64 blob inside the JS file, so we take the size of the\n // whole JS file as the second best option\n const modelSizeInBytes = stagedFileSize('wasm-model.js')\n\n // The size (in bytes) of the `static-data.ts` file\n // TODO: Ideally we would measure the size of the minified JS file here, or\n // at least ignore things like whitespace\n const dataSizeInBytes = stagedFileSize('static-data.ts')\n\n const moduleSrc = `\nexport const startTime = ${modelSpec.startTime};\nexport const endTime = ${modelSpec.endTime};\nexport const inputSpecs = ${JSON.stringify(inputSpecs)};\nexport const outputSpecs = ${JSON.stringify(outputSpecs)};\nexport const modelSizeInBytes = ${modelSizeInBytes};\nexport const dataSizeInBytes = ${dataSizeInBytes};\n`\n\n const virtualModuleId = 'virtual:model-spec'\n const resolvedVirtualModuleId = '\\0' + virtualModuleId\n\n return {\n name: 'vite-plugin-virtual-custom',\n resolveId(id: string) {\n if (id === virtualModuleId) {\n return resolvedVirtualModuleId\n }\n },\n load(id: string) {\n if (id === resolvedVirtualModuleId) {\n return moduleSrc\n }\n }\n }\n}\n\nexport async function createViteConfigForBundle(prepDir: string, modelSpec: ModelSpec): Promise<InlineConfig> {\n // Use `template-bundle` as the root directory for the bundle project\n const root = resolvePath(__dirname, '..', 'template-bundle')\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n // Use the model worker from the staged directory\n // TODO: Make this configurable?\n const modelWorkerPath = joinPath(prepDir, 'staged', 'model', 'worker.js?raw')\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n // Configure path aliases\n resolve: {\n alias: [\n // Inject the configured model worker\n {\n find: '@_model_worker_',\n replacement: modelWorkerPath\n },\n\n // XXX: Prevent Vite from using the `browser` section of `threads/package.json`\n // since we want to force the use of the general module (under dist-esm) that chooses\n // the correct implementation (Web Worker vs worker_threads) at runtime. Currently\n // Vite's library mode is browser focused, so using a `customResolver` seems to be\n // the easiest way to prevent Vite from picking up the `browser` exports.\n {\n find: 'threads',\n replacement: 'threads',\n customResolver: async function (source, importer, options) {\n // Note that we need to use `resolveId.call` here in order to provide the\n // right `this` context, which provides Rollup plugin functionality\n const customResolver = nodeResolve({ browser: false })\n const resolved = await customResolver.resolveId.call(this, source, importer, options)\n // Force the use of the `dist-esm` variant of the threads.js package\n if (source === 'threads/worker') {\n return resolved.id.replace('worker.mjs', 'dist-esm/worker/index.js')\n } else {\n return resolved.id.replace('index.mjs', 'dist-esm/index.js')\n }\n }\n }\n ]\n },\n\n plugins: [\n // Use a virtual module plugin to inject the model spec values\n injectModelSpec(prepDir, modelSpec)\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-bundle.js'\n },\n\n rollupOptions: {\n // Don't transform Node imports used by threads.js\n external: ['events', 'os', 'path', 'url'],\n\n // XXX: Insert custom code at the top of the generated bundle that defines\n // the special `__non_webpack_require__` function that is used by threads.js\n // in its Node implementation. This import ensures that threads.js uses\n // the native `worker_threads` implementation when using the bundle in a\n // Node environment. When importing the bundle for use in the browser,\n // Vite will transform this import into an empty module (it does not seem\n // to be necessary to define a polyfill).\n output: {\n banner: `\nimport * as worker_threads from 'worker_threads'\nlet __non_webpack_require__ = () => {\n return worker_threads;\n};\n`\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\n/**\n * Helper function that converts a Vensim variable or subscript name\n * into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nfunction sdeNameForVensimName(name: string): string {\n return (\n '_' +\n name\n .trim()\n .replace(/\"/g, '_')\n .replace(/\\s+!$/g, '!')\n .replace(/\\s/g, '_')\n .replace(/,/g, '_')\n .replace(/-/g, '_')\n .replace(/\\./g, '_')\n .replace(/\\$/g, '_')\n .replace(/'/g, '_')\n .replace(/&/g, '_')\n .replace(/%/g, '_')\n .replace(/\\//g, '_')\n .replace(/\\|/g, '_')\n .toLowerCase()\n )\n}\n\n/**\n * Helper function that converts a Vensim variable name (possibly containing\n * subscripts) into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nexport function sdeNameForVensimVarName(varName: string): string {\n const m = varName.match(/([^[]+)(?:\\[([^\\]]+)\\])?/)\n if (!m) {\n throw new Error(`Invalid Vensim name: ${varName}`)\n }\n let id = sdeNameForVensimName(m[1])\n if (m[2]) {\n const subscripts = m[2].split(',').map(x => sdeNameForVensimName(x))\n id += `[${subscripts.join('][')}]`\n }\n\n return id\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, join as joinPath, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { Alias, InlineConfig, PluginOption } from 'vite'\nimport replace from '@rollup/plugin-replace'\n\nimport type { SuiteSummary } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForReport(\n options: CheckPluginOptions | undefined,\n projDir: string,\n prepDir: string,\n currentBundleName: string,\n currentBundlePath: string,\n testConfigPath: string,\n suiteSummary: SuiteSummary | undefined\n): InlineConfig {\n // Use `template-report` as the root directory for the report project\n const root = resolvePath(__dirname, '..', 'template-report')\n\n // Include `baselines/*.js` files under the configured project root directory. This\n // glob path apparently must be a relative path (relative to the `template-report/src`\n // directory where the glob is used).\n const templateSrcDir = resolvePath(root, 'src')\n const relProjDir = relative(templateSrcDir, projDir)\n // XXX: The glob pattern must use forward slashes only, so on Windows we need to\n // convert backslashes to slashes\n const relProjDirPath = relProjDir.replaceAll('\\\\', '/')\n // TODO: Use baselinesDir from options\n const baselinesPath = `${relProjDirPath}/baselines/*.js`\n\n // Calculate output directory relative to the template root\n let reportPath: string\n if (options?.reportPath) {\n reportPath = options.reportPath\n } else {\n reportPath = joinPath(prepDir, 'check-report')\n }\n const outDir = relative(root, reportPath)\n\n // Convert the suite summary to JSON, which is what the app currently expects\n const suiteSummaryJson = suiteSummary ? JSON.stringify(suiteSummary) : ''\n\n const alias = (find: string, replacement: string) => {\n return {\n find,\n replacement\n } as Alias\n }\n\n // XXX: This provides custom handling for Node built-ins such as 'events' that are\n // referenced by the check bundle (specifically in the Node implementation of\n // threads.js). These are not actually used in the browser, so we just need\n // to provide no-op polyfills for these.\n const noopPolyfillAlias = (find: string) => {\n return {\n find,\n replacement: '/polyfills/noop-polyfills.ts'\n } as Alias\n }\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Use `.` as the base directory (instead of the default `/`); this controls\n // how the path to the js/css files are generated in `index.html`\n base: '',\n\n // Use a custom cache directory under `prepDir`, as otherwise Vite will use\n // `packages/plugin-check/template-report/node_modules/.vite`, and we want to\n // avoid generating files in `template-report` (which should be read-only)\n cacheDir: joinPath(prepDir, '.vite-check-report'),\n\n // Load static files from `static` (instead of the default `public`)\n // publicDir: 'static',\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO\n // logLevel: 'silent',\n\n optimizeDeps: {\n // Prevent Vite from examining other html files when scanning entrypoints\n // for dependency optimization\n entries: ['index.html'],\n\n // XXX: When plugin-check is installed via pnpm, the Vite dev server seems\n // to have no trouble resolving other dependencies using the optimizeDeps\n // mechanism. However, this fails when the package is installed via yarn\n // or npm (probably due to the fact that the `template-report` directory\n // is located under the top-level `node_modules` directory); in the browser,\n // there will be \"import not found\" errors for the packages referenced below.\n // As a terrible workaround, explicitly include the direct dependencies so\n // that Vite optimizes them; this works for pnpm, yarn, and npm. We should\n // find a less fragile solution.\n include: [\n // from check-core\n 'assert-never',\n 'ajv',\n 'neverthrow',\n 'yaml',\n // from check-ui-shell\n 'fontfaceobserver',\n 'copy-text-to-clipboard',\n 'chart.js'\n ],\n\n exclude: [\n // XXX: The threads.js implementation references `tiny-worker` as an optional\n // dependency, but it doesn't get used at runtime, so we can just exclude it\n // so that Vite doesn't complain in dev mode\n 'tiny-worker',\n\n // XXX: Similarly, chart.js treats `moment` as an optional dependency, but we\n // don't use it at runtime; we need to exclude it here, otherwise Vite will\n // complain about missing dependencies in dev mode\n 'moment'\n ]\n },\n\n // Configure path aliases\n resolve: {\n alias: [\n // Use the configured \"baseline\" bundle if defined, otherwise use the \"empty\" bundle\n // (which will cause comparison tests to be skipped)\n alias('@_baseline_bundle_', options?.baseline ? options.baseline.path : '/src/empty-bundle.ts'),\n\n // Use the configured \"current\" bundle\n alias('@_current_bundle_', currentBundlePath),\n\n // Use the configured test config file\n alias('@_test_config_', testConfigPath),\n\n // Make the overlay use the `messages.html` file that is written to the prep directory\n alias('@_prep_', prepDir),\n\n // XXX: Include no-op polyfills for these modules that are used in the Node-specific\n // implementation of threads.js; this allows us to use one bundle that works in both\n // Node and browser environments\n noopPolyfillAlias('events'),\n noopPolyfillAlias('os'),\n noopPolyfillAlias('path'),\n noopPolyfillAlias('url')\n ]\n },\n\n // Inject special values into the generated JS\n define: {\n // Inject the summary JSON into the build\n __SUITE_SUMMARY_JSON__: JSON.stringify(suiteSummaryJson),\n\n // Inject the baseline branch name\n __BASELINE_NAME__: JSON.stringify(options?.baseline?.name || ''),\n\n // Inject the current branch name\n __CURRENT_NAME__: JSON.stringify(currentBundleName)\n },\n\n plugins: [\n // Inject special values into the generated JS\n // TODO: We currently have to use `@rollup/plugin-replace` instead of Vite's\n // built-in `define` feature because the latter does not seem to run before\n // the glob handler (which requires the glob to be injected as a literal)\n replace({\n preventAssignment: true,\n values: {\n // Inject the path for baseline bundles\n __BASELINE_BUNDLES_PATH__: JSON.stringify(baselinesPath)\n }\n }) as PluginOption\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n\n // Write js/css files to `public` (instead of the default `<outDir>/assets`)\n assetsDir: '',\n\n rollupOptions: {\n output: {\n // XXX: Prevent vite from creating a separate `vendor.js` file\n manualChunks: undefined\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n },\n\n server: {\n // Run the dev server at `localhost:8081` by default\n port: options?.serverPort || 8081,\n\n // Open the app in the browser by default\n open: '/index.html',\n\n // XXX: Add a small delay, otherwise on macOS we sometimes get multiple\n // change events when a file is saved just once. That is a relatively\n // harmless issue except that it causes redundant messages in the console\n // and can cause extra churn when refreshing the app.\n watch: {\n awaitWriteFinish: {\n stabilityThreshold: 100\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig } from 'vite'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForTests(projDir: string, prepDir: string, mode: 'build' | 'watch'): InlineConfig {\n // Use `template-tests` as the root directory for the tests project\n const root = resolvePath(__dirname, '..', 'template-tests')\n\n // Include `*.check.yaml` files under the configured project root directory. This\n // glob path apparently must be a relative path (relative to the `template-tests/src`\n // directory where the glob is used).\n const templateSrcDir = resolvePath(root, 'src')\n const relProjDir = relative(templateSrcDir, projDir)\n // XXX: The glob pattern must use forward slashes only, so on Windows we need to\n // convert backslashes to slashes\n const relProjDirPath = relProjDir.replaceAll('\\\\', '/')\n // TODO: Use yamlPath from options\n const yamlPath = `${relProjDirPath}/**/*.check.yaml`\n\n // // Read the `package.json` for the template project\n // const pkgPath = resolvePath(root, 'package.json')\n // const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n // Inject special values into the generated JS\n define: {\n // Inject the glob pattern for matching check yaml files\n __YAML_PATH__: JSON.stringify(yamlPath)\n },\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-tests.js'\n },\n\n // Enable watch mode if requested\n watch: mode === 'watch' && {},\n\n rollupOptions: {\n // Prevent dependencies from being included in packaged library\n // TODO: For now we include check-core in the packaged library so that its\n // dependencies are correctly resolved at runtime. Ideally this would only\n // include a couple functions that are used for defining tests, but Vite 2.x\n // does not implement tree shaking for ES libraries, which means the generated\n // library is much larger than it needs to be. Once we upgrade to Vite 3.x,\n // the generated library should be smaller; see related fix:\n // https://github.com/vitejs/vite/pull/8737\n // external: Object.keys(pkg.dependencies)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAAA,eAAoD;AACpD,IAAAC,cAA8B;AAG9B,kBAAoC;AAEpC,sBAAqB;AAKrB,IAAAC,qBAA6B;;;ACX7B,wBAA4B;AAE5B,wBAAiB;AAejB,wBAMO;AAUP,eAAsB,aACpB,SACA,QACA,SAC6B;AAC7B,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,KAAK,8BAAY,IAAI;AAC3B,QAAI;AACJ,UAAM,YAA+B;AAAA,MACnC,YAAY,cAAY;AACtB,cAAM,MAAM,KAAK,MAAM,WAAW,GAAG;AACrC,cAAM,WAAW,KA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SAAS,SAAS;AAAA,MAC7E;AAAA,MACA;AAAA,IACF,CAAC;AAGD,UAAM,cAAc,UAAM,iCAAa,YAAY;AACnD,UAAM,SAAS,MAAM,aAAa,SAAS,aAA0B,KAAK;AAG1E,YAAQ,IAAI,QAAQ,6BAA6B;AACjD,UAAM,aAAa,KAAK,0BAA0B,QAAQ,QAAQ,aAAa,OAAO,YAAY;AAClG,cAAM,mBAAM,UAAU;AAItB,WAAO,OAAO;AAAA,EAChB;AAAA,EAEQ,mBAAmB,QAAqC;AAjLlE;AAkLI,QAAI;AACJ,QAAI;AACJ,UAAI,UAAK,YAAL,mBAAc,aAAY,QAAW;AAEvC,0BAAoB;AACpB,8BAAoB,aAAAC,MAAS,OAAO,SAAS,iBAAiB;AAAA,IAChE,OAAO;AAEL,0BAAoB,KAAK,QAAQ,QAAQ;AACzC,0BAAoB,KAAK,QAAQ,QAAQ;AAAA,IAC3C;AAEA,QAAI;AACJ,UAAI,UAAK,YAAL,mBAAc,oBAAmB,QAAW;AAE9C,2BAAiB,aAAAA,MAAS,OAAO,SAAS,gBAAgB;AAAA,IAC5D,OAAO;AAEL,uBAAiB,KAAK,QAAQ;AAAA,IAChC;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,0BACN,QACA,aACA,cACc;AACd,WAAO;AAAA,MACL,KAAK;AAAA,MACL,OAAO;AAAA,MACP,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,YAAY;AAAA,MACZ,YAAY;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AASA,SAAS,qBAAqB,UAA0B;AACtD,QAAM,aAAS,0BAAQ,2BAAcF,aAAY,GAAG,CAAC;AACrD,QAAM,cAAU,uBAAS,QAAQ,QAAQ;AACzC,SAAO,QAAQ,WAAW,MAAM,GAAG;AACrC;","names":["import_path","import_url","import_check_core","pico","joinPath","resolvePath","import_path","import_url","import_meta","__filename","__dirname","resolvePath","joinPath","replace","import_path","import_url","import_meta","__filename","__dirname","resolvePath","import_meta","chokidar","joinPath"]}
|
package/dist/index.js
CHANGED
|
@@ -1,24 +1,8 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
3
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
4
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
-
var __spreadValues = (a, b) => {
|
|
7
|
-
for (var prop in b || (b = {}))
|
|
8
|
-
if (__hasOwnProp.call(b, prop))
|
|
9
|
-
__defNormalProp(a, prop, b[prop]);
|
|
10
|
-
if (__getOwnPropSymbols)
|
|
11
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
12
|
-
if (__propIsEnum.call(b, prop))
|
|
13
|
-
__defNormalProp(a, prop, b[prop]);
|
|
14
|
-
}
|
|
15
|
-
return a;
|
|
16
|
-
};
|
|
17
|
-
|
|
18
1
|
// src/plugin.ts
|
|
19
2
|
import { dirname as dirname4, join as joinPath3, relative as relative4 } from "path";
|
|
20
3
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
21
4
|
import { build, createServer } from "vite";
|
|
5
|
+
import chokidar from "chokidar";
|
|
22
6
|
import { createConfig } from "@sdeverywhere/check-core";
|
|
23
7
|
|
|
24
8
|
// src/run-suite.ts
|
|
@@ -143,6 +127,7 @@ function printPerfStats(context, compareConfig, report) {
|
|
|
143
127
|
}
|
|
144
128
|
|
|
145
129
|
// src/vite-config-for-bundle.ts
|
|
130
|
+
import { existsSync, statSync } from "fs";
|
|
146
131
|
import { dirname, join as joinPath, relative, resolve as resolvePath } from "path";
|
|
147
132
|
import { fileURLToPath } from "url";
|
|
148
133
|
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
|
@@ -167,22 +152,36 @@ function sdeNameForVensimVarName(varName) {
|
|
|
167
152
|
// src/vite-config-for-bundle.ts
|
|
168
153
|
var __filename = fileURLToPath(import.meta.url);
|
|
169
154
|
var __dirname = dirname(__filename);
|
|
170
|
-
function injectModelSpec(modelSpec) {
|
|
155
|
+
function injectModelSpec(prepDir, modelSpec) {
|
|
171
156
|
const inputSpecs = modelSpec.inputs.map((i) => {
|
|
172
|
-
return
|
|
173
|
-
varId: sdeNameForVensimVarName(i.varName)
|
|
174
|
-
|
|
157
|
+
return {
|
|
158
|
+
varId: sdeNameForVensimVarName(i.varName),
|
|
159
|
+
...i
|
|
160
|
+
};
|
|
175
161
|
});
|
|
176
162
|
const outputSpecs = modelSpec.outputs.map((o) => {
|
|
177
|
-
return
|
|
178
|
-
varId: sdeNameForVensimVarName(o.varName)
|
|
179
|
-
|
|
163
|
+
return {
|
|
164
|
+
varId: sdeNameForVensimVarName(o.varName),
|
|
165
|
+
...o
|
|
166
|
+
};
|
|
180
167
|
});
|
|
168
|
+
function stagedFileSize(filename) {
|
|
169
|
+
const path = joinPath(prepDir, "staged", "model", filename);
|
|
170
|
+
if (existsSync(path)) {
|
|
171
|
+
return statSync(path).size;
|
|
172
|
+
} else {
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const modelSizeInBytes = stagedFileSize("wasm-model.js");
|
|
177
|
+
const dataSizeInBytes = stagedFileSize("static-data.ts");
|
|
181
178
|
const moduleSrc = `
|
|
182
179
|
export const startTime = ${modelSpec.startTime};
|
|
183
180
|
export const endTime = ${modelSpec.endTime};
|
|
184
181
|
export const inputSpecs = ${JSON.stringify(inputSpecs)};
|
|
185
182
|
export const outputSpecs = ${JSON.stringify(outputSpecs)};
|
|
183
|
+
export const modelSizeInBytes = ${modelSizeInBytes};
|
|
184
|
+
export const dataSizeInBytes = ${dataSizeInBytes};
|
|
186
185
|
`;
|
|
187
186
|
const virtualModuleId = "virtual:model-spec";
|
|
188
187
|
const resolvedVirtualModuleId = "\0" + virtualModuleId;
|
|
@@ -230,7 +229,7 @@ async function createViteConfigForBundle(prepDir, modelSpec) {
|
|
|
230
229
|
]
|
|
231
230
|
},
|
|
232
231
|
plugins: [
|
|
233
|
-
injectModelSpec(modelSpec)
|
|
232
|
+
injectModelSpec(prepDir, modelSpec)
|
|
234
233
|
],
|
|
235
234
|
build: {
|
|
236
235
|
outDir,
|
|
@@ -263,11 +262,16 @@ let __non_webpack_require__ = () => {
|
|
|
263
262
|
// src/vite-config-for-report.ts
|
|
264
263
|
import { dirname as dirname2, relative as relative2, join as joinPath2, resolve as resolvePath2 } from "path";
|
|
265
264
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
265
|
+
import replace from "@rollup/plugin-replace";
|
|
266
266
|
var __filename2 = fileURLToPath2(import.meta.url);
|
|
267
267
|
var __dirname2 = dirname2(__filename2);
|
|
268
|
-
function createViteConfigForReport(options, prepDir, currentBundleName, currentBundlePath, testConfigPath, suiteSummary) {
|
|
268
|
+
function createViteConfigForReport(options, projDir, prepDir, currentBundleName, currentBundlePath, testConfigPath, suiteSummary) {
|
|
269
269
|
var _a;
|
|
270
270
|
const root = resolvePath2(__dirname2, "..", "template-report");
|
|
271
|
+
const templateSrcDir = resolvePath2(root, "src");
|
|
272
|
+
const relProjDir = relative2(templateSrcDir, projDir);
|
|
273
|
+
const relProjDirPath = relProjDir.replaceAll("\\", "/");
|
|
274
|
+
const baselinesPath = `${relProjDirPath}/baselines/*.js`;
|
|
271
275
|
let reportPath;
|
|
272
276
|
if (options == null ? void 0 : options.reportPath) {
|
|
273
277
|
reportPath = options.reportPath;
|
|
@@ -327,7 +331,14 @@ function createViteConfigForReport(options, prepDir, currentBundleName, currentB
|
|
|
327
331
|
__BASELINE_NAME__: JSON.stringify(((_a = options == null ? void 0 : options.baseline) == null ? void 0 : _a.name) || ""),
|
|
328
332
|
__CURRENT_NAME__: JSON.stringify(currentBundleName)
|
|
329
333
|
},
|
|
330
|
-
plugins: [
|
|
334
|
+
plugins: [
|
|
335
|
+
replace({
|
|
336
|
+
preventAssignment: true,
|
|
337
|
+
values: {
|
|
338
|
+
__BASELINE_BUNDLES_PATH__: JSON.stringify(baselinesPath)
|
|
339
|
+
}
|
|
340
|
+
})
|
|
341
|
+
],
|
|
331
342
|
build: {
|
|
332
343
|
outDir,
|
|
333
344
|
assetsDir: "",
|
|
@@ -357,8 +368,6 @@ function createViteConfigForReport(options, prepDir, currentBundleName, currentB
|
|
|
357
368
|
// src/vite-config-for-tests.ts
|
|
358
369
|
import { dirname as dirname3, relative as relative3, resolve as resolvePath3 } from "path";
|
|
359
370
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
360
|
-
import globPlugin from "vite-plugin-glob";
|
|
361
|
-
import replace from "@rollup/plugin-replace";
|
|
362
371
|
var __filename3 = fileURLToPath3(import.meta.url);
|
|
363
372
|
var __dirname3 = dirname3(__filename3);
|
|
364
373
|
function createViteConfigForTests(projDir, prepDir, mode) {
|
|
@@ -372,15 +381,9 @@ function createViteConfigForTests(projDir, prepDir, mode) {
|
|
|
372
381
|
configFile: false,
|
|
373
382
|
root,
|
|
374
383
|
clearScreen: false,
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
values: {
|
|
379
|
-
__YAML_PATH__: JSON.stringify(yamlPath)
|
|
380
|
-
}
|
|
381
|
-
}),
|
|
382
|
-
globPlugin()
|
|
383
|
-
],
|
|
384
|
+
define: {
|
|
385
|
+
__YAML_PATH__: JSON.stringify(yamlPath)
|
|
386
|
+
},
|
|
384
387
|
build: {
|
|
385
388
|
outDir,
|
|
386
389
|
emptyOutDir: false,
|
|
@@ -413,6 +416,16 @@ var CheckPlugin = class {
|
|
|
413
416
|
const viteConfig = this.createViteConfigForReport(config, testOptions, void 0);
|
|
414
417
|
const server = await createServer(viteConfig);
|
|
415
418
|
await server.listen();
|
|
419
|
+
const baselinesDir = "baselines";
|
|
420
|
+
const watcher = chokidar.watch(baselinesDir, {
|
|
421
|
+
cwd: config.rootDir,
|
|
422
|
+
ignoreInitial: true,
|
|
423
|
+
awaitWriteFinish: {
|
|
424
|
+
stabilityThreshold: 200
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
watcher.on("add", () => server.restart());
|
|
428
|
+
watcher.on("unlink", () => server.restart());
|
|
416
429
|
}
|
|
417
430
|
async postBuild(context, modelSpec) {
|
|
418
431
|
var _a, _b;
|
|
@@ -498,7 +511,15 @@ var CheckPlugin = class {
|
|
|
498
511
|
};
|
|
499
512
|
}
|
|
500
513
|
createViteConfigForReport(config, testOptions, suiteSummary) {
|
|
501
|
-
return createViteConfigForReport(
|
|
514
|
+
return createViteConfigForReport(
|
|
515
|
+
this.options,
|
|
516
|
+
config.rootDir,
|
|
517
|
+
config.prepDir,
|
|
518
|
+
testOptions.currentBundleName,
|
|
519
|
+
testOptions.currentBundlePath,
|
|
520
|
+
testOptions.testConfigPath,
|
|
521
|
+
suiteSummary
|
|
522
|
+
);
|
|
502
523
|
}
|
|
503
524
|
};
|
|
504
525
|
function relativeToSourcePath(filePath) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugin.ts","../src/run-suite.ts","../src/vite-config-for-bundle.ts","../src/var-names.ts","../src/vite-config-for-report.ts","../src/vite-config-for-tests.ts"],"sourcesContent":["// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, join as joinPath, relative } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, ViteDevServer } from 'vite'\nimport { build, createServer } from 'vite'\n\nimport type { BuildContext, ModelSpec, Plugin, ResolvedConfig } from '@sdeverywhere/build'\n\nimport type { Bundle, SuiteSummary } from '@sdeverywhere/check-core'\nimport { createConfig } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\nimport { runTestSuite } from './run-suite'\nimport { createViteConfigForBundle } from './vite-config-for-bundle'\nimport { createViteConfigForReport } from './vite-config-for-report'\nimport { createViteConfigForTests } from './vite-config-for-tests'\n\nexport function checkPlugin(options?: CheckPluginOptions): Plugin {\n return new CheckPlugin(options)\n}\n\ninterface TestOptions {\n currentBundleName: string\n currentBundlePath: string\n testConfigPath: string\n}\n\nclass CheckPlugin implements Plugin {\n private firstBuild = true\n\n constructor(private readonly options?: CheckPluginOptions) {}\n\n async watch(config: ResolvedConfig): Promise<void> {\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so generate a default config in watch mode.\n // The test template uses import.meta.importGlob so that checks are re-run\n // automatically when the *.check.yaml files are changed.\n await this.genTestConfig(config, 'watch')\n }\n\n // For development mode, run Vite in dev mode so that it serves the\n // model-check report locally (with live reload enabled). When a model\n // test file is changed, the tests will be re-run in the browser.\n const testOptions = this.resolveTestOptions(config)\n const viteConfig = this.createViteConfigForReport(config, testOptions, undefined)\n const server: ViteDevServer = await createServer(viteConfig)\n await server.listen()\n }\n\n // TODO: Note that this plugin runs as a `postBuild` step because it currently\n // needs to run after other plugins, and those plugins need to run after the\n // staged files are copied to their final destination(s). We should probably\n // make it configurable so that it can either be run as a `postGenerate` or a\n // `postBuild` step.\n async postBuild(context: BuildContext, modelSpec: ModelSpec): Promise<boolean> {\n const firstBuild = this.firstBuild\n this.firstBuild = false\n\n // For both production builds and local development, generate default bundle\n // in this post-build step each time a source file is changed\n // TODO: We could potentially use watch mode for the bundle similar to\n // what we do for the test config, but the bundle depends on the ModelSpec,\n // which currently isn't made available to the `watch` function\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so generate a default bundle\n context.log('info', 'Generating model check bundle...')\n await this.genCurrentBundle(context.config, modelSpec)\n }\n\n // For production builds (and for the initial build in local development mode),\n // generate default test config in this post-build step\n if (this.options?.testConfigPath === undefined) {\n if (context.config.mode === 'production' || firstBuild) {\n // Test config was not provided, so generate a default config\n context.log('info', 'Generating model check test configuration...')\n await this.genTestConfig(context.config, 'build')\n }\n }\n\n if (context.config.mode === 'production') {\n // For production builds, run the model checks/comparisons, and then\n // inject the results into the generated report\n const testOptions = this.resolveTestOptions(context.config)\n return this.runChecks(context, testOptions)\n } else {\n // Nothing to do here in dev mode; the dev server will refresh and\n // re-run the tests in the browser when changes are detected\n return true\n }\n }\n\n private async genCurrentBundle(config: ResolvedConfig, modelSpec: ModelSpec): Promise<void> {\n const prepDir = config.prepDir\n const viteConfig = await createViteConfigForBundle(prepDir, modelSpec)\n await build(viteConfig)\n }\n\n private async genTestConfig(config: ResolvedConfig, mode: 'build' | 'watch'): Promise<void> {\n const rootDir = config.rootDir\n const prepDir = config.prepDir\n const viteConfig = createViteConfigForTests(rootDir, prepDir, mode)\n await build(viteConfig)\n }\n\n private async runChecks(context: BuildContext, testOptions: TestOptions): Promise<boolean> {\n context.log('info', 'Running model checks...')\n\n // Load the bundles used by the model check/compare configuration. We\n // always initialize the \"current\" bundle.\n const moduleR = await import(relativeToSourcePath(testOptions.currentBundlePath))\n const bundleR = moduleR.createBundle() as Bundle\n const nameR = testOptions.currentBundleName\n\n // Only initialize the \"baseline\" bundle if it is defined and the version\n // is the same as the \"current\" one. If the baseline bundle has a different\n // version, we will skip the comparison tests and only run the checks on the\n // current bundle.\n let bundleL: Bundle\n let nameL: string\n if (this.options?.baseline) {\n const moduleL = await import(relativeToSourcePath(this.options.baseline.path))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rawBundleL: any = moduleL.createBundle() as any\n if (rawBundleL.version === bundleR.version) {\n bundleL = rawBundleL as Bundle\n nameL = this.options.baseline.name\n }\n }\n\n // Get the model check/compare configuration\n const testConfigModule = await import(relativeToSourcePath(testOptions.testConfigPath))\n const checkOptions = await testConfigModule.getConfigOptions(bundleL, bundleR, {\n nameL,\n nameR\n })\n\n // Run the suite of checks and comparisons\n const checkConfig = await createConfig(checkOptions)\n const result = await runTestSuite(context, checkConfig, /*verbose=*/ false)\n\n // Build the report (using Vite)\n context.log('info', 'Building model check report')\n const viteConfig = this.createViteConfigForReport(context.config, testOptions, result.suiteSummary)\n await build(viteConfig)\n\n // context.log('info', 'Done!')\n\n return result.allChecksPassed\n }\n\n private resolveTestOptions(config: ResolvedConfig): TestOptions {\n let currentBundleName: string\n let currentBundlePath: string\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so use a generated bundle\n currentBundleName = 'current'\n currentBundlePath = joinPath(config.prepDir, 'check-bundle.js')\n } else {\n // Use the provided bundle\n currentBundleName = this.options.current.name\n currentBundlePath = this.options.current.path\n }\n\n let testConfigPath: string\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so use a generated config\n testConfigPath = joinPath(config.prepDir, 'check-tests.js')\n } else {\n // Use the provided test config\n testConfigPath = this.options.testConfigPath\n }\n\n return {\n currentBundleName,\n currentBundlePath,\n testConfigPath\n }\n }\n\n private createViteConfigForReport(\n config: ResolvedConfig,\n testOptions: TestOptions,\n suiteSummary: SuiteSummary | undefined\n ): InlineConfig {\n return createViteConfigForReport(\n this.options,\n config.prepDir,\n testOptions.currentBundleName,\n testOptions.currentBundlePath,\n testOptions.testConfigPath,\n suiteSummary\n )\n }\n}\n\n/**\n * Return a Unix-style path (e.g. '../../foo.js') that is relative to the directory of\n * the current source file. This can be used to construct a path that is safe for\n * dynamic import on either Unix or Windows.\n *\n * @param filePath The path to make relative.\n */\nfunction relativeToSourcePath(filePath: string): string {\n const srcDir = dirname(fileURLToPath(import.meta.url))\n const relPath = relative(srcDir, filePath)\n return relPath.replaceAll('\\\\', '/')\n}\n","// Copyright (c) 2021-2022 Climate Interactive / New Venture Fund\n\nimport { performance } from 'perf_hooks'\n\nimport pico from 'picocolors'\n\nimport type { BuildContext } from '@sdeverywhere/build'\n\nimport type {\n Config,\n CompareReport,\n PerfReport,\n RunSuiteCallbacks,\n CheckReport,\n CheckStatus,\n CompareConfig,\n CheckTestReport,\n SuiteSummary\n} from '@sdeverywhere/check-core'\nimport {\n datasetMessage,\n predicateMessage,\n runSuite,\n scenarioMessage,\n suiteSummaryFromReport\n} from '@sdeverywhere/check-core'\n\nexport interface RunTestSuiteResult {\n allChecksPassed: boolean\n suiteSummary: SuiteSummary\n}\n\n/**\n * Runs the test suite.\n */\nexport async function runTestSuite(\n context: BuildContext,\n config: Config,\n verbose: boolean\n): Promise<RunTestSuiteResult> {\n return new Promise((resolve, reject) => {\n const t0 = performance.now()\n let lastPctByInc: number\n const callbacks: RunSuiteCallbacks = {\n onProgress: progress => {\n const pct = Math.round(progress * 100)\n const pctByInc = Math.floor(pct / 5) * 5\n if (lastPctByInc === undefined || pctByInc > lastPctByInc) {\n lastPctByInc = pctByInc\n context.log('info', `${pctByInc}%`)\n }\n },\n onComplete: report => {\n try {\n const t1 = performance.now()\n const elapsed = ((t1 - t0) / 1000).toFixed(1)\n context.log('info', `\\nTest suite completed in ${elapsed}s`)\n\n // Print check summary to the console\n const allChecksPassed = printCheckSummary(context, report.checkReport, verbose)\n\n if (report.compareReport) {\n // Print the perf stats to the console\n printPerfStats(context, config.compare, report.compareReport)\n }\n\n // Convert check and compare reports to terse form that only includes\n // failed/errored checks or comparisons with differences\n // TODO: The terse form was originally used when we had to write the\n // results to a JSON file and then read them back in when building\n // the report, but we no longer use that intermediate file, so there's\n // less reason to use the terse form (since it requires the web app\n // code to reconstruct the results). But for now, we will continue\n // to use the terse form, and later we can update the app code.\n const suiteSummary = suiteSummaryFromReport(report)\n\n resolve({\n allChecksPassed,\n suiteSummary\n })\n } catch (e) {\n reject(e)\n }\n },\n onError: error => {\n reject(error)\n }\n }\n runSuite(config, callbacks)\n })\n}\n\nfunction printCheckSummary(context: BuildContext, checkReport: CheckReport, verbose: boolean): boolean {\n function printResult(indent: number, status: CheckStatus, text: string): void {\n if (!verbose && status === 'passed' && indent > 1) {\n return\n }\n let statusChar: string\n switch (status) {\n case 'passed':\n statusChar = '✓'\n break\n case 'failed':\n statusChar = '✗'\n break\n case 'error':\n statusChar = '‼'\n break\n default:\n statusChar = ''\n break\n }\n const msg = `${' '.repeat(indent)}${statusChar} ${text}`\n context.log('info', status === 'passed' ? pico.green(msg) : pico.red(msg))\n }\n\n function bold(s: string): string {\n return pico.bold(s)\n }\n\n function printTest(test: CheckTestReport): void {\n const msg = `${test.name}${verbose || test.status !== 'passed' ? ':' : ''}`\n printResult(1, test.status, msg)\n }\n\n let allPassed = true\n context.log('info', '\\nCheck results:')\n for (const group of checkReport.groups) {\n context.log('info', `\\n${group.name}`)\n\n for (const test of group.tests) {\n if (test.status !== 'passed') {\n allPassed = false\n }\n printTest(test)\n\n for (const scenario of test.scenarios) {\n printResult(3, scenario.status, scenarioMessage(scenario, bold))\n\n for (const dataset of scenario.datasets) {\n printResult(5, dataset.status, datasetMessage(dataset, bold))\n\n for (const predicate of dataset.predicates) {\n printResult(7, predicate.result.status, predicateMessage(predicate, bold))\n }\n }\n }\n }\n }\n context.log('info', '')\n\n return allPassed\n}\n\nfunction stat(label: string, n: number): string {\n return `${label}=${n.toFixed(1)}ms`\n}\n\nfunction printPerfReportLine(context: BuildContext, perfReport: PerfReport): void {\n const avg = stat('avg', perfReport.avgTime)\n const min = stat('min', perfReport.minTime)\n const max = stat('max', perfReport.maxTime)\n context.log('info', ` ${avg} ${min} ${max}`)\n}\n\nfunction printPerfStats(context: BuildContext, compareConfig: CompareConfig, report: CompareReport): void {\n context.log('info', '\\nPerformance stats:')\n context.log('info', ` ${compareConfig.bundleL.name}:`)\n printPerfReportLine(context, report.perfReportL)\n context.log('info', ` ${compareConfig.bundleR.name}:`)\n printPerfReportLine(context, report.perfReportR)\n context.log('info', '')\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport type { ModelSpec } from '@sdeverywhere/build'\nimport { dirname, join as joinPath, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, Plugin as VitePlugin } from 'vite'\nimport { nodeResolve } from '@rollup/plugin-node-resolve'\n\nimport { sdeNameForVensimVarName } from './var-names'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\n/**\n * This is a virtual module plugin used to inject model-specific configuration\n * values into the generated worker bundle.\n *\n * This follows the \"Virtual Modules Convention\" described here:\n * https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention\n *\n * TODO: This could be simplified by using `vite-plugin-virtual` but that\n * doesn't seem to be working correctly in an ESM setting\n */\nfunction injectModelSpec(modelSpec: ModelSpec): VitePlugin {\n // Include the SDE variable ID with each spec\n const inputSpecs = modelSpec.inputs.map(i => {\n return {\n varId: sdeNameForVensimVarName(i.varName),\n ...i\n }\n })\n const outputSpecs = modelSpec.outputs.map(o => {\n return {\n varId: sdeNameForVensimVarName(o.varName),\n ...o\n }\n })\n\n const moduleSrc = `\nexport const startTime = ${modelSpec.startTime};\nexport const endTime = ${modelSpec.endTime};\nexport const inputSpecs = ${JSON.stringify(inputSpecs)};\nexport const outputSpecs = ${JSON.stringify(outputSpecs)};\n`\n\n const virtualModuleId = 'virtual:model-spec'\n const resolvedVirtualModuleId = '\\0' + virtualModuleId\n\n return {\n name: 'vite-plugin-virtual-custom',\n resolveId(id: string) {\n if (id === virtualModuleId) {\n return resolvedVirtualModuleId\n }\n },\n load(id: string) {\n if (id === resolvedVirtualModuleId) {\n return moduleSrc\n }\n }\n }\n}\n\nexport async function createViteConfigForBundle(prepDir: string, modelSpec: ModelSpec): Promise<InlineConfig> {\n // Use `template-bundle` as the root directory for the bundle project\n const root = resolvePath(__dirname, '..', 'template-bundle')\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n // Use the model worker from the staged directory\n // TODO: Make this configurable?\n const modelWorkerPath = joinPath(prepDir, 'staged', 'model', 'worker.js?raw')\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n // Configure path aliases\n resolve: {\n alias: [\n // Inject the configured model worker\n {\n find: '@_model_worker_',\n replacement: modelWorkerPath\n },\n\n // XXX: Prevent Vite from using the `browser` section of `threads/package.json`\n // since we want to force the use of the general module (under dist-esm) that chooses\n // the correct implementation (Web Worker vs worker_threads) at runtime. Currently\n // Vite's library mode is browser focused, so using a `customResolver` seems to be\n // the easiest way to prevent Vite from picking up the `browser` exports.\n {\n find: 'threads',\n replacement: 'threads',\n customResolver: async function (source, importer, options) {\n // Note that we need to use `resolveId.call` here in order to provide the\n // right `this` context, which provides Rollup plugin functionality\n const customResolver = nodeResolve({ browser: false })\n const resolved = await customResolver.resolveId.call(this, source, importer, options)\n // Force the use of the `dist-esm` variant of the threads.js package\n if (source === 'threads/worker') {\n return resolved.id.replace('worker.mjs', 'dist-esm/worker/index.js')\n } else {\n return resolved.id.replace('index.mjs', 'dist-esm/index.js')\n }\n }\n }\n ]\n },\n\n plugins: [\n // Use a virtual module plugin to inject the model spec values\n injectModelSpec(modelSpec)\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-bundle.js'\n },\n\n rollupOptions: {\n // Don't transform Node imports used by threads.js\n external: ['events', 'os', 'path', 'url'],\n\n // XXX: Insert custom code at the top of the generated bundle that defines\n // the special `__non_webpack_require__` function that is used by threads.js\n // in its Node implementation. This import ensures that threads.js uses\n // the native `worker_threads` implementation when using the bundle in a\n // Node environment. When importing the bundle for use in the browser,\n // Vite will transform this import into an empty module (it does not seem\n // to be necessary to define a polyfill).\n output: {\n banner: `\nimport * as worker_threads from 'worker_threads'\nlet __non_webpack_require__ = () => {\n return worker_threads;\n};\n`\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\n/**\n * Helper function that converts a Vensim variable or subscript name\n * into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nfunction sdeNameForVensimName(name: string): string {\n return (\n '_' +\n name\n .trim()\n .replace(/\"/g, '_')\n .replace(/\\s+!$/g, '!')\n .replace(/\\s/g, '_')\n .replace(/,/g, '_')\n .replace(/-/g, '_')\n .replace(/\\./g, '_')\n .replace(/\\$/g, '_')\n .replace(/'/g, '_')\n .replace(/&/g, '_')\n .replace(/%/g, '_')\n .replace(/\\//g, '_')\n .replace(/\\|/g, '_')\n .toLowerCase()\n )\n}\n\n/**\n * Helper function that converts a Vensim variable name (possibly containing\n * subscripts) into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nexport function sdeNameForVensimVarName(varName: string): string {\n const m = varName.match(/([^[]+)(?:\\[([^\\]]+)\\])?/)\n if (!m) {\n throw new Error(`Invalid Vensim name: ${varName}`)\n }\n let id = sdeNameForVensimName(m[1])\n if (m[2]) {\n const subscripts = m[2].split(',').map(x => sdeNameForVensimName(x))\n id += `[${subscripts.join('][')}]`\n }\n\n return id\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, join as joinPath, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { Alias, InlineConfig } from 'vite'\n\nimport type { SuiteSummary } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForReport(\n options: CheckPluginOptions | undefined,\n prepDir: string,\n currentBundleName: string,\n currentBundlePath: string,\n testConfigPath: string,\n suiteSummary: SuiteSummary | undefined\n): InlineConfig {\n // Use `template-report` as the root directory for the report project\n const root = resolvePath(__dirname, '..', 'template-report')\n\n // Calculate output directory relative to the template root\n let reportPath: string\n if (options?.reportPath) {\n reportPath = options.reportPath\n } else {\n reportPath = joinPath(prepDir, 'check-report')\n }\n const outDir = relative(root, reportPath)\n\n // Convert the suite summary to JSON, which is what the app currently expects\n const suiteSummaryJson = suiteSummary ? JSON.stringify(suiteSummary) : ''\n\n const alias = (find: string, replacement: string) => {\n return {\n find,\n replacement\n } as Alias\n }\n\n // XXX: This provides custom handling for Node built-ins such as 'events' that are\n // referenced by the check bundle (specifically in the Node implementation of\n // threads.js). These are not actually used in the browser, so we just need\n // to provide no-op polyfills for these.\n const noopPolyfillAlias = (find: string) => {\n return {\n find,\n replacement: '/polyfills/noop-polyfills.ts'\n } as Alias\n }\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Use `.` as the base directory (instead of the default `/`); this controls\n // how the path to the js/css files are generated in `index.html`\n base: '',\n\n // Use a custom cache directory under `prepDir`, as otherwise Vite will use\n // `packages/plugin-check/template-report/node_modules/.vite`, and we want to\n // avoid generating files in `template-report` (which should be read-only)\n cacheDir: joinPath(prepDir, '.vite-check-report'),\n\n // Load static files from `static` (instead of the default `public`)\n // publicDir: 'static',\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO\n // logLevel: 'silent',\n\n optimizeDeps: {\n // Prevent Vite from examining other html files when scanning entrypoints\n // for dependency optimization\n entries: ['index.html'],\n\n // XXX: When plugin-check is installed via pnpm, the Vite dev server seems\n // to have no trouble resolving other dependencies using the optimizeDeps\n // mechanism. However, this fails when the package is installed via yarn\n // or npm (probably due to the fact that the `template-report` directory\n // is located under the top-level `node_modules` directory); in the browser,\n // there will be \"import not found\" errors for the packages referenced below.\n // As a terrible workaround, explicitly include the direct dependencies so\n // that Vite optimizes them; this works for pnpm, yarn, and npm. We should\n // find a less fragile solution.\n include: [\n // from check-core\n 'assert-never',\n 'ajv',\n 'neverthrow',\n 'yaml',\n // from check-ui-shell\n 'fontfaceobserver',\n 'copy-text-to-clipboard',\n 'chart.js'\n ],\n\n exclude: [\n // XXX: The threads.js implementation references `tiny-worker` as an optional\n // dependency, but it doesn't get used at runtime, so we can just exclude it\n // so that Vite doesn't complain in dev mode\n 'tiny-worker',\n\n // XXX: Similarly, chart.js treats `moment` as an optional dependency, but we\n // don't use it at runtime; we need to exclude it here, otherwise Vite will\n // complain about missing dependencies in dev mode\n 'moment'\n ]\n },\n\n // Configure path aliases\n resolve: {\n alias: [\n // Use the configured \"baseline\" bundle if defined, otherwise use the \"empty\" bundle\n // (which will cause comparison tests to be skipped)\n alias('@_baseline_bundle_', options?.baseline ? options.baseline.path : '/src/empty-bundle.ts'),\n\n // Use the configured \"current\" bundle\n alias('@_current_bundle_', currentBundlePath),\n\n // Use the configured test config file\n alias('@_test_config_', testConfigPath),\n\n // Make the overlay use the `messages.html` file that is written to the prep directory\n alias('@_prep_', prepDir),\n\n // XXX: Include no-op polyfills for these modules that are used in the Node-specific\n // implementation of threads.js; this allows us to use one bundle that works in both\n // Node and browser environments\n noopPolyfillAlias('events'),\n noopPolyfillAlias('os'),\n noopPolyfillAlias('path'),\n noopPolyfillAlias('url')\n ]\n },\n\n // Inject special values into the generated JS\n define: {\n // Inject the summary JSON into the build\n __SUITE_SUMMARY_JSON__: JSON.stringify(suiteSummaryJson),\n\n // Inject the baseline branch name\n __BASELINE_NAME__: JSON.stringify(options?.baseline?.name || ''),\n\n // Inject the current branch name\n __CURRENT_NAME__: JSON.stringify(currentBundleName)\n },\n\n plugins: [\n // Use `vite-plugin-glob` instead of Vite's built-in `import.meta.globEager`\n // because the plugin does a better job of handling HMR when the yaml files\n // are outside of the `template-report` app root directory.\n // globPlugin(),\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n\n // Write js/css files to `public` (instead of the default `<outDir>/assets`)\n assetsDir: '',\n\n rollupOptions: {\n output: {\n // XXX: Prevent vite from creating a separate `vendor.js` file\n manualChunks: undefined\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n },\n\n server: {\n // Run the dev server at `localhost:8081` by default\n port: options?.serverPort || 8081,\n\n // Open the app in the browser by default\n open: '/index.html',\n\n // XXX: Add a small delay, otherwise on macOS we sometimes get multiple\n // change events when a file is saved just once. That is a relatively\n // harmless issue except that it causes redundant messages in the console\n // and can cause extra churn when refreshing the app.\n watch: {\n awaitWriteFinish: {\n stabilityThreshold: 100\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig } from 'vite'\nimport globPlugin from 'vite-plugin-glob'\nimport replace from '@rollup/plugin-replace'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForTests(projDir: string, prepDir: string, mode: 'build' | 'watch'): InlineConfig {\n // Use `template-tests` as the root directory for the tests project\n const root = resolvePath(__dirname, '..', 'template-tests')\n\n // Include `*.check.yaml` files under the configured project root directory. This\n // glob path apparently must be a relative path (relative to the `template-tests/src`\n // directory where the glob is used).\n const templateSrcDir = resolvePath(root, 'src')\n const relProjDir = relative(templateSrcDir, projDir)\n // XXX: The glob pattern must use forward slashes only, so on Windows we need to\n // convert backslashes to slashes\n const relProjDirPath = relProjDir.replaceAll('\\\\', '/')\n // TODO: Use yamlPath from options\n const yamlPath = `${relProjDirPath}/**/*.check.yaml`\n\n // // Read the `package.json` for the template project\n // const pkgPath = resolvePath(root, 'package.json')\n // const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n plugins: [\n // Inject special values into the generated JS\n // TODO: We currently have to use `@rollup/plugin-replace` instead of Vite's\n // built-in `define` feature because the latter does not seem to run before\n // the glob plugin, and that requires the glob to be injected as a literal;\n // `plugin-replace` seems to work as long as we order it before `plugin-glob`.\n // Maybe we can switch back to `define` once we move to Vite 3.x.\n replace({\n preventAssignment: true,\n values: {\n // Inject the glob pattern for matching check yaml files\n __YAML_PATH__: JSON.stringify(yamlPath)\n }\n }),\n\n // Use `vite-plugin-glob` instead of Vite's built-in `import.meta.globEager`\n // because the plugin does a better job of handling HMR when the yaml files\n // are outside of the `template-report` app root directory.\n globPlugin()\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-tests.js'\n },\n\n // Enable watch mode if requested\n watch: mode === 'watch' && {},\n\n rollupOptions: {\n // Prevent dependencies from being included in packaged library\n // TODO: For now we include check-core in the packaged library so that its\n // dependencies are correctly resolved at runtime. Ideally this would only\n // include a couple functions that are used for defining tests, but Vite 2.x\n // does not implement tree shaking for ES libraries, which means the generated\n // library is much larger than it needs to be. Once we upgrade to Vite 3.x,\n // the generated library should be smaller; see related fix:\n // https://github.com/vitejs/vite/pull/8737\n // external: Object.keys(pkg.dependencies)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAEA;AACA;AAGA;AAKA;;;ACTA;AAEA;AAeA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,4BACE,SACA,QACA,SAC6B;AAC7B,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,KAAK,YAAY,IAAI;AAC3B,QAAI;AACJ,UAAM,YAA+B;AAAA,MACnC,YAAY,cAAY;AACtB,cAAM,MAAM,KAAK,MAAM,WAAW,GAAG;AACrC,cAAM,W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e,MAAM,iBAAiB,iBAAiB,SAAS,SAAS;AAAA,MAC7E;AAAA,MACA;AAAA,IACF,CAAC;AAGD,UAAM,cAAc,MAAM,aAAa,YAAY;AACnD,UAAM,SAAS,MAAM,aAAa,SAAS,aAA0B,KAAK;AAG1E,YAAQ,IAAI,QAAQ,6BAA6B;AACjD,UAAM,aAAa,KAAK,0BAA0B,QAAQ,QAAQ,aAAa,OAAO,YAAY;AAClG,UAAM,MAAM,UAAU;AAItB,WAAO,OAAO;AAAA,EAChB;AAAA,EAEA,AAAQ,mBAAmB,QAAqC;AAxJlE;AAyJI,QAAI;AACJ,QAAI;AACJ,QAAI,YAAK,YAAL,mBAAc,aAAY,QAAW;AAEvC,0BAAoB;AACpB,0BAAoB,UAAS,OAAO,SAAS,iBAAiB;AAAA,IAChE,OAAO;AAEL,0BAAoB,KAAK,QAAQ,QAAQ;AACzC,0BAAoB,KAAK,QAAQ,QAAQ;AAAA,IAC3C;AAEA,QAAI;AACJ,QAAI,YAAK,YAAL,mBAAc,oBAAmB,QAAW;AAE9C,uBAAiB,UAAS,OAAO,SAAS,gBAAgB;AAAA,IAC5D,OAAO;AAEL,uBAAiB,KAAK,QAAQ;AAAA,IAChC;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,AAAQ,0BACN,QACA,aACA,cACc;AACd,WAAO,0BACL,KAAK,SACL,OAAO,SACP,YAAY,mBACZ,YAAY,mBACZ,YAAY,gBACZ,YACF;AAAA,EACF;AACF;AASA,8BAA8B,UAA0B;AACtD,QAAM,SAAS,SAAQ,eAAc,YAAY,GAAG,CAAC;AACrD,QAAM,UAAU,UAAS,QAAQ,QAAQ;AACzC,SAAO,QAAQ,WAAW,MAAM,GAAG;AACrC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/plugin.ts","../src/run-suite.ts","../src/vite-config-for-bundle.ts","../src/var-names.ts","../src/vite-config-for-report.ts","../src/vite-config-for-tests.ts"],"sourcesContent":["// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, join as joinPath, relative } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, ViteDevServer } from 'vite'\nimport { build, createServer } from 'vite'\n\nimport chokidar from 'chokidar'\n\nimport type { BuildContext, ModelSpec, Plugin, ResolvedConfig } from '@sdeverywhere/build'\n\nimport type { Bundle, SuiteSummary } from '@sdeverywhere/check-core'\nimport { createConfig } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\nimport { runTestSuite } from './run-suite'\nimport { createViteConfigForBundle } from './vite-config-for-bundle'\nimport { createViteConfigForReport } from './vite-config-for-report'\nimport { createViteConfigForTests } from './vite-config-for-tests'\n\nexport function checkPlugin(options?: CheckPluginOptions): Plugin {\n return new CheckPlugin(options)\n}\n\ninterface TestOptions {\n currentBundleName: string\n currentBundlePath: string\n testConfigPath: string\n}\n\nclass CheckPlugin implements Plugin {\n private firstBuild = true\n\n constructor(private readonly options?: CheckPluginOptions) {}\n\n async watch(config: ResolvedConfig): Promise<void> {\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so generate a default config in watch mode.\n // The test template uses import.meta.glob so that checks are re-run\n // automatically when the *.check.yaml files are changed.\n await this.genTestConfig(config, 'watch')\n }\n\n // For development mode, run Vite in dev mode so that it serves the\n // model-check report locally (with live reload enabled). When a model\n // test file is changed, the tests will be re-run in the browser.\n const testOptions = this.resolveTestOptions(config)\n const viteConfig = this.createViteConfigForReport(config, testOptions, undefined)\n const server: ViteDevServer = await createServer(viteConfig)\n await server.listen()\n\n // XXX: Currently Vite doesn't reload the page if a file is added/removed\n // in the baselines directory (Vite's import.meta.glob handling doesn't\n // seem to do this automatically), so as a workaround, watch the baselines\n // directory and restart the server if files are added/removed\n // TODO: The same problem also applies to the glob for `.check.yaml` files\n // in the test config, so we should also reload if files match/unmatch\n // the `.check.yaml` glob\n // TODO: Use the baselines directory from the config\n const baselinesDir = 'baselines'\n const watcher = chokidar.watch(baselinesDir, {\n // Watch paths are resolved relative to the project root directory\n cwd: config.rootDir,\n // Don't send initial \"file added\" events\n ignoreInitial: true,\n // XXX: Include a delay, otherwise on macOS we sometimes get multiple\n // change events when a file is saved just once\n awaitWriteFinish: {\n stabilityThreshold: 200\n }\n })\n watcher.on('add', () => server.restart())\n watcher.on('unlink', () => server.restart())\n }\n\n // TODO: Note that this plugin runs as a `postBuild` step because it currently\n // needs to run after other plugins, and those plugins need to run after the\n // staged files are copied to their final destination(s). We should probably\n // make it configurable so that it can either be run as a `postGenerate` or a\n // `postBuild` step.\n async postBuild(context: BuildContext, modelSpec: ModelSpec): Promise<boolean> {\n const firstBuild = this.firstBuild\n this.firstBuild = false\n\n // For both production builds and local development, generate default bundle\n // in this post-build step each time a source file is changed\n // TODO: We could potentially use watch mode for the bundle similar to\n // what we do for the test config, but the bundle depends on the ModelSpec,\n // which currently isn't made available to the `watch` function\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so generate a default bundle\n context.log('info', 'Generating model check bundle...')\n await this.genCurrentBundle(context.config, modelSpec)\n }\n\n // For production builds (and for the initial build in local development mode),\n // generate default test config in this post-build step\n if (this.options?.testConfigPath === undefined) {\n if (context.config.mode === 'production' || firstBuild) {\n // Test config was not provided, so generate a default config\n context.log('info', 'Generating model check test configuration...')\n await this.genTestConfig(context.config, 'build')\n }\n }\n\n if (context.config.mode === 'production') {\n // For production builds, run the model checks/comparisons, and then\n // inject the results into the generated report\n const testOptions = this.resolveTestOptions(context.config)\n return this.runChecks(context, testOptions)\n } else {\n // Nothing to do here in dev mode; the dev server will refresh and\n // re-run the tests in the browser when changes are detected\n return true\n }\n }\n\n private async genCurrentBundle(config: ResolvedConfig, modelSpec: ModelSpec): Promise<void> {\n const prepDir = config.prepDir\n const viteConfig = await createViteConfigForBundle(prepDir, modelSpec)\n await build(viteConfig)\n }\n\n private async genTestConfig(config: ResolvedConfig, mode: 'build' | 'watch'): Promise<void> {\n const rootDir = config.rootDir\n const prepDir = config.prepDir\n const viteConfig = createViteConfigForTests(rootDir, prepDir, mode)\n await build(viteConfig)\n }\n\n private async runChecks(context: BuildContext, testOptions: TestOptions): Promise<boolean> {\n context.log('info', 'Running model checks...')\n\n // Load the bundles used by the model check/compare configuration. We\n // always initialize the \"current\" bundle.\n const moduleR = await import(relativeToSourcePath(testOptions.currentBundlePath))\n const bundleR = moduleR.createBundle() as Bundle\n const nameR = testOptions.currentBundleName\n\n // Only initialize the \"baseline\" bundle if it is defined and the version\n // is the same as the \"current\" one. If the baseline bundle has a different\n // version, we will skip the comparison tests and only run the checks on the\n // current bundle.\n let bundleL: Bundle\n let nameL: string\n if (this.options?.baseline) {\n const moduleL = await import(relativeToSourcePath(this.options.baseline.path))\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rawBundleL: any = moduleL.createBundle() as any\n if (rawBundleL.version === bundleR.version) {\n bundleL = rawBundleL as Bundle\n nameL = this.options.baseline.name\n }\n }\n\n // Get the model check/compare configuration\n const testConfigModule = await import(relativeToSourcePath(testOptions.testConfigPath))\n const checkOptions = await testConfigModule.getConfigOptions(bundleL, bundleR, {\n nameL,\n nameR\n })\n\n // Run the suite of checks and comparisons\n const checkConfig = await createConfig(checkOptions)\n const result = await runTestSuite(context, checkConfig, /*verbose=*/ false)\n\n // Build the report (using Vite)\n context.log('info', 'Building model check report')\n const viteConfig = this.createViteConfigForReport(context.config, testOptions, result.suiteSummary)\n await build(viteConfig)\n\n // context.log('info', 'Done!')\n\n return result.allChecksPassed\n }\n\n private resolveTestOptions(config: ResolvedConfig): TestOptions {\n let currentBundleName: string\n let currentBundlePath: string\n if (this.options?.current === undefined) {\n // Path to current bundle was not provided, so use a generated bundle\n currentBundleName = 'current'\n currentBundlePath = joinPath(config.prepDir, 'check-bundle.js')\n } else {\n // Use the provided bundle\n currentBundleName = this.options.current.name\n currentBundlePath = this.options.current.path\n }\n\n let testConfigPath: string\n if (this.options?.testConfigPath === undefined) {\n // Test config was not provided, so use a generated config\n testConfigPath = joinPath(config.prepDir, 'check-tests.js')\n } else {\n // Use the provided test config\n testConfigPath = this.options.testConfigPath\n }\n\n return {\n currentBundleName,\n currentBundlePath,\n testConfigPath\n }\n }\n\n private createViteConfigForReport(\n config: ResolvedConfig,\n testOptions: TestOptions,\n suiteSummary: SuiteSummary | undefined\n ): InlineConfig {\n return createViteConfigForReport(\n this.options,\n config.rootDir,\n config.prepDir,\n testOptions.currentBundleName,\n testOptions.currentBundlePath,\n testOptions.testConfigPath,\n suiteSummary\n )\n }\n}\n\n/**\n * Return a Unix-style path (e.g. '../../foo.js') that is relative to the directory of\n * the current source file. This can be used to construct a path that is safe for\n * dynamic import on either Unix or Windows.\n *\n * @param filePath The path to make relative.\n */\nfunction relativeToSourcePath(filePath: string): string {\n const srcDir = dirname(fileURLToPath(import.meta.url))\n const relPath = relative(srcDir, filePath)\n return relPath.replaceAll('\\\\', '/')\n}\n","// Copyright (c) 2021-2022 Climate Interactive / New Venture Fund\n\nimport { performance } from 'perf_hooks'\n\nimport pico from 'picocolors'\n\nimport type { BuildContext } from '@sdeverywhere/build'\n\nimport type {\n Config,\n CompareReport,\n PerfReport,\n RunSuiteCallbacks,\n CheckReport,\n CheckStatus,\n CompareConfig,\n CheckTestReport,\n SuiteSummary\n} from '@sdeverywhere/check-core'\nimport {\n datasetMessage,\n predicateMessage,\n runSuite,\n scenarioMessage,\n suiteSummaryFromReport\n} from '@sdeverywhere/check-core'\n\nexport interface RunTestSuiteResult {\n allChecksPassed: boolean\n suiteSummary: SuiteSummary\n}\n\n/**\n * Runs the test suite.\n */\nexport async function runTestSuite(\n context: BuildContext,\n config: Config,\n verbose: boolean\n): Promise<RunTestSuiteResult> {\n return new Promise((resolve, reject) => {\n const t0 = performance.now()\n let lastPctByInc: number\n const callbacks: RunSuiteCallbacks = {\n onProgress: progress => {\n const pct = Math.round(progress * 100)\n const pctByInc = Math.floor(pct / 5) * 5\n if (lastPctByInc === undefined || pctByInc > lastPctByInc) {\n lastPctByInc = pctByInc\n context.log('info', `${pctByInc}%`)\n }\n },\n onComplete: report => {\n try {\n const t1 = performance.now()\n const elapsed = ((t1 - t0) / 1000).toFixed(1)\n context.log('info', `\\nTest suite completed in ${elapsed}s`)\n\n // Print check summary to the console\n const allChecksPassed = printCheckSummary(context, report.checkReport, verbose)\n\n if (report.compareReport) {\n // Print the perf stats to the console\n printPerfStats(context, config.compare, report.compareReport)\n }\n\n // Convert check and compare reports to terse form that only includes\n // failed/errored checks or comparisons with differences\n // TODO: The terse form was originally used when we had to write the\n // results to a JSON file and then read them back in when building\n // the report, but we no longer use that intermediate file, so there's\n // less reason to use the terse form (since it requires the web app\n // code to reconstruct the results). But for now, we will continue\n // to use the terse form, and later we can update the app code.\n const suiteSummary = suiteSummaryFromReport(report)\n\n resolve({\n allChecksPassed,\n suiteSummary\n })\n } catch (e) {\n reject(e)\n }\n },\n onError: error => {\n reject(error)\n }\n }\n runSuite(config, callbacks)\n })\n}\n\nfunction printCheckSummary(context: BuildContext, checkReport: CheckReport, verbose: boolean): boolean {\n function printResult(indent: number, status: CheckStatus, text: string): void {\n if (!verbose && status === 'passed' && indent > 1) {\n return\n }\n let statusChar: string\n switch (status) {\n case 'passed':\n statusChar = '✓'\n break\n case 'failed':\n statusChar = '✗'\n break\n case 'error':\n statusChar = '‼'\n break\n default:\n statusChar = ''\n break\n }\n const msg = `${' '.repeat(indent)}${statusChar} ${text}`\n context.log('info', status === 'passed' ? pico.green(msg) : pico.red(msg))\n }\n\n function bold(s: string): string {\n return pico.bold(s)\n }\n\n function printTest(test: CheckTestReport): void {\n const msg = `${test.name}${verbose || test.status !== 'passed' ? ':' : ''}`\n printResult(1, test.status, msg)\n }\n\n let allPassed = true\n context.log('info', '\\nCheck results:')\n for (const group of checkReport.groups) {\n context.log('info', `\\n${group.name}`)\n\n for (const test of group.tests) {\n if (test.status !== 'passed') {\n allPassed = false\n }\n printTest(test)\n\n for (const scenario of test.scenarios) {\n printResult(3, scenario.status, scenarioMessage(scenario, bold))\n\n for (const dataset of scenario.datasets) {\n printResult(5, dataset.status, datasetMessage(dataset, bold))\n\n for (const predicate of dataset.predicates) {\n printResult(7, predicate.result.status, predicateMessage(predicate, bold))\n }\n }\n }\n }\n }\n context.log('info', '')\n\n return allPassed\n}\n\nfunction stat(label: string, n: number): string {\n return `${label}=${n.toFixed(1)}ms`\n}\n\nfunction printPerfReportLine(context: BuildContext, perfReport: PerfReport): void {\n const avg = stat('avg', perfReport.avgTime)\n const min = stat('min', perfReport.minTime)\n const max = stat('max', perfReport.maxTime)\n context.log('info', ` ${avg} ${min} ${max}`)\n}\n\nfunction printPerfStats(context: BuildContext, compareConfig: CompareConfig, report: CompareReport): void {\n context.log('info', '\\nPerformance stats:')\n context.log('info', ` ${compareConfig.bundleL.name}:`)\n printPerfReportLine(context, report.perfReportL)\n context.log('info', ` ${compareConfig.bundleR.name}:`)\n printPerfReportLine(context, report.perfReportR)\n context.log('info', '')\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { existsSync, statSync } from 'fs'\nimport { dirname, join as joinPath, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig, Plugin as VitePlugin } from 'vite'\nimport { nodeResolve } from '@rollup/plugin-node-resolve'\n\nimport type { ModelSpec } from '@sdeverywhere/build'\n\nimport { sdeNameForVensimVarName } from './var-names'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\n/**\n * This is a virtual module plugin used to inject model-specific configuration\n * values into the generated worker bundle.\n *\n * This follows the \"Virtual Modules Convention\" described here:\n * https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention\n *\n * TODO: This could be simplified by using `vite-plugin-virtual` but that\n * doesn't seem to be working correctly in an ESM setting\n */\nfunction injectModelSpec(prepDir: string, modelSpec: ModelSpec): VitePlugin {\n // Include the SDE variable ID with each spec\n const inputSpecs = modelSpec.inputs.map(i => {\n return {\n varId: sdeNameForVensimVarName(i.varName),\n ...i\n }\n })\n const outputSpecs = modelSpec.outputs.map(o => {\n return {\n varId: sdeNameForVensimVarName(o.varName),\n ...o\n }\n })\n\n function stagedFileSize(filename: string): number {\n const path = joinPath(prepDir, 'staged', 'model', filename)\n if (existsSync(path)) {\n return statSync(path).size\n } else {\n return 0\n }\n }\n\n // The size (in bytes) of the `wasm-model.js` file\n // TODO: Ideally we would measure the size of the raw WASM binary, but currently\n // we inline it as a base64 blob inside the JS file, so we take the size of the\n // whole JS file as the second best option\n const modelSizeInBytes = stagedFileSize('wasm-model.js')\n\n // The size (in bytes) of the `static-data.ts` file\n // TODO: Ideally we would measure the size of the minified JS file here, or\n // at least ignore things like whitespace\n const dataSizeInBytes = stagedFileSize('static-data.ts')\n\n const moduleSrc = `\nexport const startTime = ${modelSpec.startTime};\nexport const endTime = ${modelSpec.endTime};\nexport const inputSpecs = ${JSON.stringify(inputSpecs)};\nexport const outputSpecs = ${JSON.stringify(outputSpecs)};\nexport const modelSizeInBytes = ${modelSizeInBytes};\nexport const dataSizeInBytes = ${dataSizeInBytes};\n`\n\n const virtualModuleId = 'virtual:model-spec'\n const resolvedVirtualModuleId = '\\0' + virtualModuleId\n\n return {\n name: 'vite-plugin-virtual-custom',\n resolveId(id: string) {\n if (id === virtualModuleId) {\n return resolvedVirtualModuleId\n }\n },\n load(id: string) {\n if (id === resolvedVirtualModuleId) {\n return moduleSrc\n }\n }\n }\n}\n\nexport async function createViteConfigForBundle(prepDir: string, modelSpec: ModelSpec): Promise<InlineConfig> {\n // Use `template-bundle` as the root directory for the bundle project\n const root = resolvePath(__dirname, '..', 'template-bundle')\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n // Use the model worker from the staged directory\n // TODO: Make this configurable?\n const modelWorkerPath = joinPath(prepDir, 'staged', 'model', 'worker.js?raw')\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n // Configure path aliases\n resolve: {\n alias: [\n // Inject the configured model worker\n {\n find: '@_model_worker_',\n replacement: modelWorkerPath\n },\n\n // XXX: Prevent Vite from using the `browser` section of `threads/package.json`\n // since we want to force the use of the general module (under dist-esm) that chooses\n // the correct implementation (Web Worker vs worker_threads) at runtime. Currently\n // Vite's library mode is browser focused, so using a `customResolver` seems to be\n // the easiest way to prevent Vite from picking up the `browser` exports.\n {\n find: 'threads',\n replacement: 'threads',\n customResolver: async function (source, importer, options) {\n // Note that we need to use `resolveId.call` here in order to provide the\n // right `this` context, which provides Rollup plugin functionality\n const customResolver = nodeResolve({ browser: false })\n const resolved = await customResolver.resolveId.call(this, source, importer, options)\n // Force the use of the `dist-esm` variant of the threads.js package\n if (source === 'threads/worker') {\n return resolved.id.replace('worker.mjs', 'dist-esm/worker/index.js')\n } else {\n return resolved.id.replace('index.mjs', 'dist-esm/index.js')\n }\n }\n }\n ]\n },\n\n plugins: [\n // Use a virtual module plugin to inject the model spec values\n injectModelSpec(prepDir, modelSpec)\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-bundle.js'\n },\n\n rollupOptions: {\n // Don't transform Node imports used by threads.js\n external: ['events', 'os', 'path', 'url'],\n\n // XXX: Insert custom code at the top of the generated bundle that defines\n // the special `__non_webpack_require__` function that is used by threads.js\n // in its Node implementation. This import ensures that threads.js uses\n // the native `worker_threads` implementation when using the bundle in a\n // Node environment. When importing the bundle for use in the browser,\n // Vite will transform this import into an empty module (it does not seem\n // to be necessary to define a polyfill).\n output: {\n banner: `\nimport * as worker_threads from 'worker_threads'\nlet __non_webpack_require__ = () => {\n return worker_threads;\n};\n`\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\n/**\n * Helper function that converts a Vensim variable or subscript name\n * into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nfunction sdeNameForVensimName(name: string): string {\n return (\n '_' +\n name\n .trim()\n .replace(/\"/g, '_')\n .replace(/\\s+!$/g, '!')\n .replace(/\\s/g, '_')\n .replace(/,/g, '_')\n .replace(/-/g, '_')\n .replace(/\\./g, '_')\n .replace(/\\$/g, '_')\n .replace(/'/g, '_')\n .replace(/&/g, '_')\n .replace(/%/g, '_')\n .replace(/\\//g, '_')\n .replace(/\\|/g, '_')\n .toLowerCase()\n )\n}\n\n/**\n * Helper function that converts a Vensim variable name (possibly containing\n * subscripts) into a valid C identifier as used by SDE.\n * TODO: Import helper function from `compile` package instead\n */\nexport function sdeNameForVensimVarName(varName: string): string {\n const m = varName.match(/([^[]+)(?:\\[([^\\]]+)\\])?/)\n if (!m) {\n throw new Error(`Invalid Vensim name: ${varName}`)\n }\n let id = sdeNameForVensimName(m[1])\n if (m[2]) {\n const subscripts = m[2].split(',').map(x => sdeNameForVensimName(x))\n id += `[${subscripts.join('][')}]`\n }\n\n return id\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, join as joinPath, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { Alias, InlineConfig, PluginOption } from 'vite'\nimport replace from '@rollup/plugin-replace'\n\nimport type { SuiteSummary } from '@sdeverywhere/check-core'\n\nimport type { CheckPluginOptions } from './options'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForReport(\n options: CheckPluginOptions | undefined,\n projDir: string,\n prepDir: string,\n currentBundleName: string,\n currentBundlePath: string,\n testConfigPath: string,\n suiteSummary: SuiteSummary | undefined\n): InlineConfig {\n // Use `template-report` as the root directory for the report project\n const root = resolvePath(__dirname, '..', 'template-report')\n\n // Include `baselines/*.js` files under the configured project root directory. This\n // glob path apparently must be a relative path (relative to the `template-report/src`\n // directory where the glob is used).\n const templateSrcDir = resolvePath(root, 'src')\n const relProjDir = relative(templateSrcDir, projDir)\n // XXX: The glob pattern must use forward slashes only, so on Windows we need to\n // convert backslashes to slashes\n const relProjDirPath = relProjDir.replaceAll('\\\\', '/')\n // TODO: Use baselinesDir from options\n const baselinesPath = `${relProjDirPath}/baselines/*.js`\n\n // Calculate output directory relative to the template root\n let reportPath: string\n if (options?.reportPath) {\n reportPath = options.reportPath\n } else {\n reportPath = joinPath(prepDir, 'check-report')\n }\n const outDir = relative(root, reportPath)\n\n // Convert the suite summary to JSON, which is what the app currently expects\n const suiteSummaryJson = suiteSummary ? JSON.stringify(suiteSummary) : ''\n\n const alias = (find: string, replacement: string) => {\n return {\n find,\n replacement\n } as Alias\n }\n\n // XXX: This provides custom handling for Node built-ins such as 'events' that are\n // referenced by the check bundle (specifically in the Node implementation of\n // threads.js). These are not actually used in the browser, so we just need\n // to provide no-op polyfills for these.\n const noopPolyfillAlias = (find: string) => {\n return {\n find,\n replacement: '/polyfills/noop-polyfills.ts'\n } as Alias\n }\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Use `.` as the base directory (instead of the default `/`); this controls\n // how the path to the js/css files are generated in `index.html`\n base: '',\n\n // Use a custom cache directory under `prepDir`, as otherwise Vite will use\n // `packages/plugin-check/template-report/node_modules/.vite`, and we want to\n // avoid generating files in `template-report` (which should be read-only)\n cacheDir: joinPath(prepDir, '.vite-check-report'),\n\n // Load static files from `static` (instead of the default `public`)\n // publicDir: 'static',\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO\n // logLevel: 'silent',\n\n optimizeDeps: {\n // Prevent Vite from examining other html files when scanning entrypoints\n // for dependency optimization\n entries: ['index.html'],\n\n // XXX: When plugin-check is installed via pnpm, the Vite dev server seems\n // to have no trouble resolving other dependencies using the optimizeDeps\n // mechanism. However, this fails when the package is installed via yarn\n // or npm (probably due to the fact that the `template-report` directory\n // is located under the top-level `node_modules` directory); in the browser,\n // there will be \"import not found\" errors for the packages referenced below.\n // As a terrible workaround, explicitly include the direct dependencies so\n // that Vite optimizes them; this works for pnpm, yarn, and npm. We should\n // find a less fragile solution.\n include: [\n // from check-core\n 'assert-never',\n 'ajv',\n 'neverthrow',\n 'yaml',\n // from check-ui-shell\n 'fontfaceobserver',\n 'copy-text-to-clipboard',\n 'chart.js'\n ],\n\n exclude: [\n // XXX: The threads.js implementation references `tiny-worker` as an optional\n // dependency, but it doesn't get used at runtime, so we can just exclude it\n // so that Vite doesn't complain in dev mode\n 'tiny-worker',\n\n // XXX: Similarly, chart.js treats `moment` as an optional dependency, but we\n // don't use it at runtime; we need to exclude it here, otherwise Vite will\n // complain about missing dependencies in dev mode\n 'moment'\n ]\n },\n\n // Configure path aliases\n resolve: {\n alias: [\n // Use the configured \"baseline\" bundle if defined, otherwise use the \"empty\" bundle\n // (which will cause comparison tests to be skipped)\n alias('@_baseline_bundle_', options?.baseline ? options.baseline.path : '/src/empty-bundle.ts'),\n\n // Use the configured \"current\" bundle\n alias('@_current_bundle_', currentBundlePath),\n\n // Use the configured test config file\n alias('@_test_config_', testConfigPath),\n\n // Make the overlay use the `messages.html` file that is written to the prep directory\n alias('@_prep_', prepDir),\n\n // XXX: Include no-op polyfills for these modules that are used in the Node-specific\n // implementation of threads.js; this allows us to use one bundle that works in both\n // Node and browser environments\n noopPolyfillAlias('events'),\n noopPolyfillAlias('os'),\n noopPolyfillAlias('path'),\n noopPolyfillAlias('url')\n ]\n },\n\n // Inject special values into the generated JS\n define: {\n // Inject the summary JSON into the build\n __SUITE_SUMMARY_JSON__: JSON.stringify(suiteSummaryJson),\n\n // Inject the baseline branch name\n __BASELINE_NAME__: JSON.stringify(options?.baseline?.name || ''),\n\n // Inject the current branch name\n __CURRENT_NAME__: JSON.stringify(currentBundleName)\n },\n\n plugins: [\n // Inject special values into the generated JS\n // TODO: We currently have to use `@rollup/plugin-replace` instead of Vite's\n // built-in `define` feature because the latter does not seem to run before\n // the glob handler (which requires the glob to be injected as a literal)\n replace({\n preventAssignment: true,\n values: {\n // Inject the path for baseline bundles\n __BASELINE_BUNDLES_PATH__: JSON.stringify(baselinesPath)\n }\n }) as PluginOption\n ],\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n\n // Write js/css files to `public` (instead of the default `<outDir>/assets`)\n assetsDir: '',\n\n rollupOptions: {\n output: {\n // XXX: Prevent vite from creating a separate `vendor.js` file\n manualChunks: undefined\n },\n\n onwarn: (warning, warn) => {\n // XXX: Suppress \"Use of eval is strongly discouraged\" warnings that are\n // triggered by use of the following pattern in threads.js:\n // eval(\"require\")(\"worker_threads\")\n // It would be nice to avoid use of `eval` there, but it's not critical for\n // our use case so we will suppress the warnings for now\n if (warning.code !== 'EVAL') {\n warn(warning)\n }\n }\n }\n },\n\n server: {\n // Run the dev server at `localhost:8081` by default\n port: options?.serverPort || 8081,\n\n // Open the app in the browser by default\n open: '/index.html',\n\n // XXX: Add a small delay, otherwise on macOS we sometimes get multiple\n // change events when a file is saved just once. That is a relatively\n // harmless issue except that it causes redundant messages in the console\n // and can cause extra churn when refreshing the app.\n watch: {\n awaitWriteFinish: {\n stabilityThreshold: 100\n }\n }\n }\n }\n}\n","// Copyright (c) 2022 Climate Interactive / New Venture Fund\n\nimport { dirname, relative, resolve as resolvePath } from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { InlineConfig } from 'vite'\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = dirname(__filename)\n\nexport function createViteConfigForTests(projDir: string, prepDir: string, mode: 'build' | 'watch'): InlineConfig {\n // Use `template-tests` as the root directory for the tests project\n const root = resolvePath(__dirname, '..', 'template-tests')\n\n // Include `*.check.yaml` files under the configured project root directory. This\n // glob path apparently must be a relative path (relative to the `template-tests/src`\n // directory where the glob is used).\n const templateSrcDir = resolvePath(root, 'src')\n const relProjDir = relative(templateSrcDir, projDir)\n // XXX: The glob pattern must use forward slashes only, so on Windows we need to\n // convert backslashes to slashes\n const relProjDirPath = relProjDir.replaceAll('\\\\', '/')\n // TODO: Use yamlPath from options\n const yamlPath = `${relProjDirPath}/**/*.check.yaml`\n\n // // Read the `package.json` for the template project\n // const pkgPath = resolvePath(root, 'package.json')\n // const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n\n // Calculate output directory relative to the template root\n // TODO: For now we write it to `prepDir`; make this configurable?\n const outDir = relative(root, prepDir)\n\n return {\n // Don't use an external config file\n configFile: false,\n\n // Use the root directory configured above\n root,\n\n // Don't clear the screen in dev mode so that we can see builder output\n clearScreen: false,\n\n // TODO: Disable vite output by default?\n // logLevel: 'silent',\n\n // Inject special values into the generated JS\n define: {\n // Inject the glob pattern for matching check yaml files\n __YAML_PATH__: JSON.stringify(yamlPath)\n },\n\n build: {\n // Write output files to the configured directory (instead of the default `dist`);\n // note that this must be relative to the project `root`\n outDir,\n emptyOutDir: false,\n\n lib: {\n entry: './src/index.ts',\n formats: ['es'],\n fileName: () => 'check-tests.js'\n },\n\n // Enable watch mode if requested\n watch: mode === 'watch' && {},\n\n rollupOptions: {\n // Prevent dependencies from being included in packaged library\n // TODO: For now we include check-core in the packaged library so that its\n // dependencies are correctly resolved at runtime. Ideally this would only\n // include a couple functions that are used for defining tests, but Vite 2.x\n // does not implement tree shaking for ES libraries, which means the generated\n // library is much larger than it needs to be. Once we upgrade to Vite 3.x,\n // the generated library should be smaller; see related fix:\n // https://github.com/vitejs/vite/pull/8737\n // external: Object.keys(pkg.dependencies)\n }\n }\n }\n}\n"],"mappings":";AAEA,SAAS,WAAAA,UAAS,QAAQC,WAAU,YAAAC,iBAAgB;AACpD,SAAS,iBAAAC,sBAAqB;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MACL,OAAO;AAAA,MACP,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,YAAY;AAAA,MACZ,YAAY;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AASA,SAAS,qBAAqB,UAA0B;AACtD,QAAM,SAASC,SAAQC,eAAc,YAAY,GAAG,CAAC;AACrD,QAAM,UAAUC,UAAS,QAAQ,QAAQ;AACzC,SAAO,QAAQ,WAAW,MAAM,GAAG;AACrC;","names":["dirname","joinPath","relative","fileURLToPath","dirname","relative","joinPath","resolvePath","fileURLToPath","__filename","__dirname","dirname","relative","resolvePath","fileURLToPath","__filename","__dirname","joinPath","dirname","fileURLToPath","relative"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdeverywhere/plugin-check",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"files": [
|
|
5
|
+
"bin/**",
|
|
5
6
|
"dist/**",
|
|
6
7
|
"template-bundle/**",
|
|
7
8
|
"template-report/**",
|
|
@@ -18,19 +19,21 @@
|
|
|
18
19
|
"require": "./dist/index.cjs"
|
|
19
20
|
}
|
|
20
21
|
},
|
|
22
|
+
"bin": {
|
|
23
|
+
"sde-check": "bin/sde-check.js"
|
|
24
|
+
},
|
|
21
25
|
"dependencies": {
|
|
22
26
|
"@rollup/plugin-node-resolve": "^13.3.0",
|
|
23
|
-
"@rollup/plugin-replace": "^
|
|
24
|
-
"@sdeverywhere/build": "^0.1.1",
|
|
27
|
+
"@rollup/plugin-replace": "^4.0.0",
|
|
25
28
|
"@sdeverywhere/check-core": "^0.1.0",
|
|
26
|
-
"@sdeverywhere/check-ui-shell": "^0.
|
|
29
|
+
"@sdeverywhere/check-ui-shell": "^0.2.0",
|
|
27
30
|
"@sdeverywhere/runtime": "^0.1.0",
|
|
28
31
|
"@sdeverywhere/runtime-async": "^0.1.0",
|
|
29
32
|
"assert-never": "^1.2.1",
|
|
33
|
+
"chokidar": "^3.5.3",
|
|
30
34
|
"picocolors": "^1.0.0",
|
|
31
35
|
"rollup": "^2.76.0",
|
|
32
|
-
"vite": "^
|
|
33
|
-
"vite-plugin-glob": "^0.3.2"
|
|
36
|
+
"vite": "^3.1.3"
|
|
34
37
|
},
|
|
35
38
|
"dependenciesComments": {
|
|
36
39
|
"rollup": [
|
|
@@ -41,7 +44,11 @@
|
|
|
41
44
|
"it as a dependency here."
|
|
42
45
|
]
|
|
43
46
|
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@sdeverywhere/build": "^0.2.0"
|
|
49
|
+
},
|
|
44
50
|
"devDependencies": {
|
|
51
|
+
"@sdeverywhere/build": "*",
|
|
45
52
|
"@types/node": "^16.11.7"
|
|
46
53
|
},
|
|
47
54
|
"author": "Climate Interactive",
|
|
@@ -21,7 +21,7 @@ import type { Input } from './inputs'
|
|
|
21
21
|
import { getInputVars, setInputsForScenario } from './inputs'
|
|
22
22
|
import { getOutputVars } from './outputs'
|
|
23
23
|
|
|
24
|
-
import { startTime, endTime, inputSpecs, outputSpecs } from 'virtual:model-spec'
|
|
24
|
+
import { startTime, endTime, inputSpecs, outputSpecs, modelSizeInBytes, dataSizeInBytes } from 'virtual:model-spec'
|
|
25
25
|
|
|
26
26
|
import modelWorkerJs from '@_model_worker_/worker.js?raw'
|
|
27
27
|
|
|
@@ -31,14 +31,6 @@ import modelWorkerJs from '@_model_worker_/worker.js?raw'
|
|
|
31
31
|
// have different version numbers.
|
|
32
32
|
const VERSION = 1
|
|
33
33
|
|
|
34
|
-
// The size (in bytes) of the model file(s), injected at build time.
|
|
35
|
-
const __MODEL_SIZE_IN_BYTES__ = 1
|
|
36
|
-
const modelSizeInBytes = __MODEL_SIZE_IN_BYTES__
|
|
37
|
-
|
|
38
|
-
// The size (in bytes) of the data file(s), injected at build time.
|
|
39
|
-
const __DATA_SIZE_IN_BYTES__ = 1
|
|
40
|
-
const dataSizeInBytes = __DATA_SIZE_IN_BYTES__
|
|
41
|
-
|
|
42
34
|
export class BundleModel implements CheckBundleModel {
|
|
43
35
|
private readonly inputs: InputValue[]
|
|
44
36
|
private outputs: Outputs
|
|
@@ -13,6 +13,16 @@
|
|
|
13
13
|
rel="stylesheet"
|
|
14
14
|
/>
|
|
15
15
|
|
|
16
|
+
<style>
|
|
17
|
+
/*
|
|
18
|
+
* TODO: This avoids white flash when page reloads (due to the CSS bundled with
|
|
19
|
+
* check-ui-shell being loaded asynchronously); should fix this
|
|
20
|
+
*/
|
|
21
|
+
body {
|
|
22
|
+
background-color: #272727;
|
|
23
|
+
}
|
|
24
|
+
</style>
|
|
25
|
+
|
|
16
26
|
<script type="module" src="./src/index.ts"></script>
|
|
17
27
|
</head>
|
|
18
28
|
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// These values are injected by Vite at build time, so we need to
|
|
4
4
|
// declare types for them here
|
|
5
|
+
declare const __BASELINE_BUNDLES_PATH__: string
|
|
5
6
|
declare const __BASELINE_NAME__: string
|
|
6
7
|
declare const __CURRENT_NAME__: string
|
|
7
8
|
declare const __SUITE_SUMMARY_JSON__: string
|
|
@@ -14,17 +14,73 @@ import { createBundle as createBaselineBundle } from '@_baseline_bundle_'
|
|
|
14
14
|
import { createBundle as createCurrentBundle } from '@_current_bundle_'
|
|
15
15
|
import { getConfigOptions } from '@_test_config_'
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
17
|
+
function loadBundleName(key: string): string | undefined {
|
|
18
|
+
if (import.meta.hot) {
|
|
19
|
+
return localStorage.getItem(`sde-check-selected-bundle-${key}`)
|
|
20
|
+
} else {
|
|
21
|
+
return undefined
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function saveBundleName(key: string, value: string): void {
|
|
26
|
+
if (import.meta.hot) {
|
|
27
|
+
localStorage.setItem(`sde-check-selected-bundle-${key}`, value)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// For local development mode, load the list of available baseline bundles
|
|
32
|
+
type BundleModule = {
|
|
33
|
+
createBundle(): Bundle
|
|
25
34
|
}
|
|
35
|
+
type LoadBundle = () => Promise<Bundle>
|
|
36
|
+
const availableBundles: { [key: string]: LoadBundle } = {}
|
|
37
|
+
let bundleNames: string[]
|
|
38
|
+
let selectedBaselineBundleName: string
|
|
39
|
+
let selectedCurrentBundleName: string
|
|
40
|
+
const baselinesPath = __BASELINE_BUNDLES_PATH__
|
|
41
|
+
if (import.meta.hot && baselinesPath) {
|
|
42
|
+
// Restore the previously selected bundles (from before the page was reloaded)
|
|
43
|
+
selectedBaselineBundleName = loadBundleName('baseline')
|
|
44
|
+
selectedCurrentBundleName = loadBundleName('current')
|
|
45
|
+
|
|
46
|
+
// Get the available baseline bundles
|
|
47
|
+
const bundlesGlob = import.meta.glob(__BASELINE_BUNDLES_PATH__, {
|
|
48
|
+
eager: false
|
|
49
|
+
})
|
|
50
|
+
const baselineBundleNames: string[] = []
|
|
51
|
+
for (const bundleKey of Object.keys(bundlesGlob)) {
|
|
52
|
+
const loadBundle = bundlesGlob[bundleKey]
|
|
53
|
+
const bundlePathParts = bundleKey.split('/')
|
|
54
|
+
const bundleFileName = bundlePathParts[bundlePathParts.length - 1]
|
|
55
|
+
const bundleName = bundleFileName.replace('.js', '')
|
|
56
|
+
baselineBundleNames.push(bundleName)
|
|
57
|
+
availableBundles[bundleName] = async () => {
|
|
58
|
+
const module = (await loadBundle()) as BundleModule
|
|
59
|
+
return module.createBundle() as Bundle
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Alphabetize (reversed, so that newer dates are at the top of the list)
|
|
64
|
+
baselineBundleNames.sort((a, b) => {
|
|
65
|
+
return b.toLowerCase().localeCompare(a.toLowerCase())
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
// Always include the "current" bundle as the first option, followed by
|
|
69
|
+
// the alphabetized bundle names
|
|
70
|
+
bundleNames = ['current', ...baselineBundleNames]
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function initForProduction(): Promise<void> {
|
|
74
|
+
// For "production" builds, load the summary from a JSON file that
|
|
75
|
+
// was generated as part of the build process. This makes the
|
|
76
|
+
// report load almost immediately instead of running all the checks
|
|
77
|
+
// in the user's browser.
|
|
78
|
+
const suiteSummaryJson = __SUITE_SUMMARY_JSON__
|
|
79
|
+
let suiteSummary: SuiteSummary
|
|
80
|
+
if (suiteSummaryJson) {
|
|
81
|
+
suiteSummary = JSON.parse(suiteSummaryJson) as SuiteSummary
|
|
82
|
+
}
|
|
26
83
|
|
|
27
|
-
async function init() {
|
|
28
84
|
// Load the bundles used by the model check/compare configuration. We
|
|
29
85
|
// always initialize the "current" bundle.
|
|
30
86
|
const bundleR: Bundle = createCurrentBundle()
|
|
@@ -47,10 +103,85 @@ async function init() {
|
|
|
47
103
|
})
|
|
48
104
|
|
|
49
105
|
// Initialize the root Svelte component
|
|
50
|
-
initAppShell(checkOptions,
|
|
106
|
+
initAppShell(checkOptions, {
|
|
107
|
+
suiteSummary
|
|
108
|
+
})
|
|
109
|
+
}
|
|
51
110
|
|
|
52
|
-
|
|
53
|
-
|
|
111
|
+
async function initForLocal(): Promise<void> {
|
|
112
|
+
async function createBundle(requestedName: string | undefined): Promise<[Bundle, string]> {
|
|
113
|
+
if (requestedName === undefined) {
|
|
114
|
+
requestedName = 'current'
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// See if there is a bundle available for the requested name
|
|
118
|
+
let bundle: Bundle
|
|
119
|
+
let bundleName: string
|
|
120
|
+
if (requestedName in availableBundles) {
|
|
121
|
+
// Load the bundle for the requested name
|
|
122
|
+
const loadBundle = availableBundles[requestedName]
|
|
123
|
+
bundle = await loadBundle()
|
|
124
|
+
bundleName = requestedName
|
|
125
|
+
} else {
|
|
126
|
+
// Load the "current" bundle
|
|
127
|
+
bundle = createCurrentBundle()
|
|
128
|
+
bundleName = 'current'
|
|
129
|
+
}
|
|
130
|
+
return [bundle, bundleName]
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const [bundleL, nameL] = await createBundle(selectedBaselineBundleName)
|
|
134
|
+
const [bundleR, nameR] = await createBundle(selectedCurrentBundleName)
|
|
135
|
+
|
|
136
|
+
// Prepare the model check/compare configuration
|
|
137
|
+
const checkOptions = await getConfigOptions(bundleL, bundleR, {
|
|
138
|
+
nameL,
|
|
139
|
+
nameR
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
// Initialize the root Svelte component
|
|
143
|
+
initAppShell(checkOptions, {
|
|
144
|
+
bundleNames
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function initBundlesAndUI() {
|
|
149
|
+
// Prepare options differently if in local development mode
|
|
150
|
+
if (import.meta.hot) {
|
|
151
|
+
await initForLocal()
|
|
152
|
+
} else {
|
|
153
|
+
await initForProduction()
|
|
154
|
+
}
|
|
54
155
|
}
|
|
55
156
|
|
|
56
|
-
|
|
157
|
+
// Initialize the overlay element used to show builder messages/errors
|
|
158
|
+
initOverlay()
|
|
159
|
+
|
|
160
|
+
// Initialize the bundles and user interface
|
|
161
|
+
initBundlesAndUI()
|
|
162
|
+
|
|
163
|
+
if (import.meta.hot) {
|
|
164
|
+
// Reload everything when the user chooses a new baseline or current bundle
|
|
165
|
+
document.addEventListener('sde-check-bundle', e => {
|
|
166
|
+
// Change the selected bundle
|
|
167
|
+
const info = (e as CustomEvent).detail
|
|
168
|
+
if (info.kind === 'left') {
|
|
169
|
+
saveBundleName('baseline', info.name)
|
|
170
|
+
selectedBaselineBundleName = info.name
|
|
171
|
+
} else {
|
|
172
|
+
saveBundleName('current', info.name)
|
|
173
|
+
selectedCurrentBundleName = info.name
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Before switching bundles, clear out the app-shell-container element
|
|
177
|
+
const container = document.getElementById('app-shell-container')
|
|
178
|
+
while (container.firstChild) {
|
|
179
|
+
container.removeChild(container.firstChild)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// TODO: Release resources associated with active bundles
|
|
183
|
+
|
|
184
|
+
// Reinitialize using the chosen bundles
|
|
185
|
+
initBundlesAndUI()
|
|
186
|
+
})
|
|
187
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
|
-
"
|
|
3
|
+
// Use "esnext" for import.meta
|
|
4
|
+
"target": "esnext",
|
|
4
5
|
// Use "es2020" for dynamic import
|
|
5
6
|
"module": "es2020",
|
|
6
7
|
// Emit additional JS to ease support for importing CommonJS modules
|
|
@@ -14,7 +15,6 @@
|
|
|
14
15
|
"noImplicitAny": true,
|
|
15
16
|
"noUnusedLocals": true,
|
|
16
17
|
"noUnusedParameters": true,
|
|
17
|
-
// "types": ["vite/client", "vite-plugin-glob/client"],
|
|
18
18
|
"types": ["vite/client"],
|
|
19
19
|
"skipLibCheck": true,
|
|
20
20
|
// Use placeholders for path aliases that are configured in the Vite
|
|
@@ -4,11 +4,8 @@ import type { Bundle, CompareOptions, ConfigOptions, DatasetKey } from '@sdevery
|
|
|
4
4
|
|
|
5
5
|
import { DatasetManager, ScenarioManager } from '@sdeverywhere/check-core'
|
|
6
6
|
|
|
7
|
-
// Load the yaml test files
|
|
8
|
-
|
|
9
|
-
// does a better job of handling HMR when the yaml files are outside of
|
|
10
|
-
// the `template-report` app root directory.
|
|
11
|
-
const yamlGlob = import.meta.importGlob(__YAML_PATH__, {
|
|
7
|
+
// Load the yaml test files
|
|
8
|
+
const yamlGlob = import.meta.glob(__YAML_PATH__, {
|
|
12
9
|
eager: true,
|
|
13
10
|
as: 'raw'
|
|
14
11
|
})
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
|
-
"
|
|
3
|
+
// Use "esnext" for import.meta
|
|
4
|
+
"target": "esnext",
|
|
4
5
|
// Use "es2020" for dynamic import
|
|
5
6
|
"module": "es2020",
|
|
6
7
|
// Emit additional JS to ease support for importing CommonJS modules
|
|
@@ -14,6 +15,6 @@
|
|
|
14
15
|
"noImplicitAny": true,
|
|
15
16
|
"noUnusedLocals": true,
|
|
16
17
|
"noUnusedParameters": true,
|
|
17
|
-
"types": ["vite
|
|
18
|
+
"types": ["vite/client"]
|
|
18
19
|
}
|
|
19
20
|
}
|