@tscircuit/cli 0.1.777 → 0.1.779

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/dist/main.js CHANGED
@@ -17,16 +17,6 @@ var __toESM2 = (mod, isNodeMode, target) => {
17
17
  return to;
18
18
  };
19
19
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
- var __export2 = (target, all) => {
21
- for (var name in all)
22
- __defProp2(target, name, {
23
- get: all[name],
24
- enumerable: true,
25
- configurable: true,
26
- set: (newValue) => all[name] = () => newValue
27
- });
28
- };
29
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
30
20
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
31
21
 
32
22
  // node_modules/commander/lib/error.js
@@ -2122,101 +2112,6 @@ var require_commander = __commonJS((exports2) => {
2122
2112
  exports2.InvalidOptionArgumentError = InvalidArgumentError;
2123
2113
  });
2124
2114
 
2125
- // node_modules/kleur/index.mjs
2126
- function run(arr, str) {
2127
- let i = 0, tmp, beg = "", end = "";
2128
- for (;i < arr.length; i++) {
2129
- tmp = arr[i];
2130
- beg += tmp.open;
2131
- end += tmp.close;
2132
- if (!!~str.indexOf(tmp.close)) {
2133
- str = str.replace(tmp.rgx, tmp.close + tmp.open);
2134
- }
2135
- }
2136
- return beg + str + end;
2137
- }
2138
- function chain(has, keys) {
2139
- let ctx = { has, keys };
2140
- ctx.reset = $.reset.bind(ctx);
2141
- ctx.bold = $.bold.bind(ctx);
2142
- ctx.dim = $.dim.bind(ctx);
2143
- ctx.italic = $.italic.bind(ctx);
2144
- ctx.underline = $.underline.bind(ctx);
2145
- ctx.inverse = $.inverse.bind(ctx);
2146
- ctx.hidden = $.hidden.bind(ctx);
2147
- ctx.strikethrough = $.strikethrough.bind(ctx);
2148
- ctx.black = $.black.bind(ctx);
2149
- ctx.red = $.red.bind(ctx);
2150
- ctx.green = $.green.bind(ctx);
2151
- ctx.yellow = $.yellow.bind(ctx);
2152
- ctx.blue = $.blue.bind(ctx);
2153
- ctx.magenta = $.magenta.bind(ctx);
2154
- ctx.cyan = $.cyan.bind(ctx);
2155
- ctx.white = $.white.bind(ctx);
2156
- ctx.gray = $.gray.bind(ctx);
2157
- ctx.grey = $.grey.bind(ctx);
2158
- ctx.bgBlack = $.bgBlack.bind(ctx);
2159
- ctx.bgRed = $.bgRed.bind(ctx);
2160
- ctx.bgGreen = $.bgGreen.bind(ctx);
2161
- ctx.bgYellow = $.bgYellow.bind(ctx);
2162
- ctx.bgBlue = $.bgBlue.bind(ctx);
2163
- ctx.bgMagenta = $.bgMagenta.bind(ctx);
2164
- ctx.bgCyan = $.bgCyan.bind(ctx);
2165
- ctx.bgWhite = $.bgWhite.bind(ctx);
2166
- return ctx;
2167
- }
2168
- function init(open, close) {
2169
- let blk = {
2170
- open: `\x1B[${open}m`,
2171
- close: `\x1B[${close}m`,
2172
- rgx: new RegExp(`\\x1b\\[${close}m`, "g")
2173
- };
2174
- return function(txt) {
2175
- if (this !== undefined && this.has !== undefined) {
2176
- !!~this.has.indexOf(open) || (this.has.push(open), this.keys.push(blk));
2177
- return txt === undefined ? this : $.enabled ? run(this.keys, txt + "") : txt + "";
2178
- }
2179
- return txt === undefined ? chain([open], [blk]) : $.enabled ? run([blk], txt + "") : txt + "";
2180
- };
2181
- }
2182
- var FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = true, $, kleur_default;
2183
- var init_kleur = __esm(() => {
2184
- if (typeof process !== "undefined") {
2185
- ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
2186
- isTTY = process.stdout && process.stdout.isTTY;
2187
- }
2188
- $ = {
2189
- enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY),
2190
- reset: init(0, 0),
2191
- bold: init(1, 22),
2192
- dim: init(2, 22),
2193
- italic: init(3, 23),
2194
- underline: init(4, 24),
2195
- inverse: init(7, 27),
2196
- hidden: init(8, 28),
2197
- strikethrough: init(9, 29),
2198
- black: init(30, 39),
2199
- red: init(31, 39),
2200
- green: init(32, 39),
2201
- yellow: init(33, 39),
2202
- blue: init(34, 39),
2203
- magenta: init(35, 39),
2204
- cyan: init(36, 39),
2205
- white: init(37, 39),
2206
- gray: init(90, 39),
2207
- grey: init(90, 39),
2208
- bgBlack: init(40, 49),
2209
- bgRed: init(41, 49),
2210
- bgGreen: init(42, 49),
2211
- bgYellow: init(43, 49),
2212
- bgBlue: init(44, 49),
2213
- bgMagenta: init(45, 49),
2214
- bgCyan: init(46, 49),
2215
- bgWhite: init(47, 49)
2216
- };
2217
- kleur_default = $;
2218
- });
2219
-
2220
2115
  // node_modules/ajv/dist/compile/codegen/code.js
2221
2116
  var require_code = __commonJS((exports2) => {
2222
2117
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -16155,7 +16050,7 @@ var require_dist3 = __commonJS((exports2, module2) => {
16155
16050
  var __commonJS2 = (cb, mod) => function __require() {
16156
16051
  return mod || (0, cb[__getOwnPropNames22(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16157
16052
  };
16158
- var __export22 = (target, all) => {
16053
+ var __export2 = (target, all) => {
16159
16054
  for (var name in all)
16160
16055
  __defProp22(target, name, { get: all[name], enumerable: true });
16161
16056
  };
@@ -32811,7 +32706,7 @@ var crypto = new Crypto();
32811
32706
  }
32812
32707
  });
32813
32708
  var src_exports = {};
32814
- __export22(src_exports, {
32709
+ __export2(src_exports, {
32815
32710
  buildToFetchEvent: () => buildToFetchEvent,
32816
32711
  buildToHeaders: () => buildToHeaders,
32817
32712
  buildToNodeHandler: () => buildToNodeHandler,
@@ -32842,9 +32737,9 @@ var crypto = new Crypto();
32842
32737
  };
32843
32738
  }
32844
32739
  function buildToReadableStream(dependencies) {
32845
- const { ReadableStream: ReadableStream2, Uint8Array: Uint8Array2 } = dependencies;
32740
+ const { ReadableStream, Uint8Array: Uint8Array2 } = dependencies;
32846
32741
  return function toReadableStream(stream) {
32847
- return new ReadableStream2({
32742
+ return new ReadableStream({
32848
32743
  start(controller) {
32849
32744
  stream.on("data", (chunk) => {
32850
32745
  controller.enqueue(new Uint8Array2([...new Uint8Array2(chunk)]));
@@ -49392,7 +49287,7 @@ var require_load = __commonJS((exports2, module2) => {
49392
49287
  var __getProtoOf3 = Object.getPrototypeOf;
49393
49288
  var __hasOwnProp3 = Object.prototype.hasOwnProperty;
49394
49289
  var __name2 = (target, value) => __defProp3(target, "name", { value, configurable: true });
49395
- var __export3 = (target, all) => {
49290
+ var __export2 = (target, all) => {
49396
49291
  for (var name in all)
49397
49292
  __defProp3(target, name, { get: all[name], enumerable: true });
49398
49293
  };
@@ -49407,7 +49302,7 @@ var require_load = __commonJS((exports2, module2) => {
49407
49302
  var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps2(isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target, mod));
49408
49303
  var __toCommonJS2 = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod);
49409
49304
  var load_exports2 = {};
49410
- __export3(load_exports2, {
49305
+ __export2(load_exports2, {
49411
49306
  load: () => load2
49412
49307
  });
49413
49308
  module2.exports = __toCommonJS2(load_exports2);
@@ -49627,7 +49522,7 @@ var require_dist5 = __commonJS((exports2, module2) => {
49627
49522
  var __commonJS2 = (cb, mod) => function __require() {
49628
49523
  return mod || (0, cb[__getOwnPropNames3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
49629
49524
  };
49630
- var __export3 = (target, all) => {
49525
+ var __export2 = (target, all) => {
49631
49526
  for (var name in all)
49632
49527
  __defProp3(target, name, { get: all[name], enumerable: true });
49633
49528
  };
@@ -51933,7 +51828,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);
51933
51828
  }
51934
51829
  });
51935
51830
  var src_exports = {};
51936
- __export3(src_exports, {
51831
+ __export2(src_exports, {
51937
51832
  getMatchingFilePaths: () => getMatchingFilePaths,
51938
51833
  getVirtualFileSystemFromDirPath: () => getVirtualFileSystemFromDirPath,
51939
51834
  getVirtualFilesystemModuleFromDirPath: () => getVirtualFilesystemModuleFromDirPath,
@@ -52044,7 +51939,7 @@ var require_dist6 = __commonJS((exports2, module2) => {
52044
51939
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
52045
51940
  var __getOwnPropNames3 = Object.getOwnPropertyNames;
52046
51941
  var __hasOwnProp3 = Object.prototype.hasOwnProperty;
52047
- var __export3 = (target, all) => {
51942
+ var __export2 = (target, all) => {
52048
51943
  for (var name in all)
52049
51944
  __defProp3(target, name, { get: all[name], enumerable: true });
52050
51945
  };
@@ -52058,7 +51953,7 @@ var require_dist6 = __commonJS((exports2, module2) => {
52058
51953
  };
52059
51954
  var __toCommonJS2 = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod);
52060
51955
  var src_exports = {};
52061
- __export3(src_exports, {
51956
+ __export2(src_exports, {
52062
51957
  default: () => src_default,
52063
51958
  getRouteMatcher: () => getRouteMatcher,
52064
51959
  getRouteMatcherUgly: () => getRouteMatcherUgly
@@ -67244,7 +67139,7 @@ var require_dist7 = __commonJS((exports2, module2) => {
67244
67139
  }
67245
67140
  return target;
67246
67141
  };
67247
- var __export3 = (target, all) => {
67142
+ var __export2 = (target, all) => {
67248
67143
  for (var name in all)
67249
67144
  __defProp3(target, name, { get: all[name], enumerable: true });
67250
67145
  };
@@ -67279,7 +67174,7 @@ var require_dist7 = __commonJS((exports2, module2) => {
67279
67174
  });
67280
67175
  };
67281
67176
  var src_exports = {};
67282
- __export3(src_exports, {
67177
+ __export2(src_exports, {
67283
67178
  getCommandFromPath: () => getCommandFromPath,
67284
67179
  getCommandPathOnly: () => getCommandPathOnly,
67285
67180
  perfectCli: () => perfectCli
@@ -67564,36 +67459,6 @@ var require_dist7 = __commonJS((exports2, module2) => {
67564
67459
  });
67565
67460
  });
67566
67461
 
67567
- // lib/shared/importFromUserLand.ts
67568
- import { createRequire as createRequire2 } from "node:module";
67569
- import fs26 from "node:fs";
67570
- import path28 from "node:path";
67571
- async function importFromUserLand(moduleName) {
67572
- const userModulePath = path28.join(process.cwd(), "node_modules", moduleName);
67573
- if (fs26.existsSync(userModulePath)) {
67574
- const userRequire = createRequire2(path28.join(process.cwd(), "noop.js"));
67575
- try {
67576
- const resolvedUserPath = userRequire.resolve(moduleName);
67577
- return await import(resolvedUserPath);
67578
- } catch (error) {
67579
- if (error?.code !== "MODULE_NOT_FOUND") {
67580
- throw error;
67581
- }
67582
- }
67583
- }
67584
- const cliRequire = createRequire2(import.meta.url);
67585
- try {
67586
- const resolvedCliPath = cliRequire.resolve(moduleName);
67587
- return await import(resolvedCliPath);
67588
- } catch (error) {
67589
- if (error?.code !== "MODULE_NOT_FOUND") {
67590
- throw error;
67591
- }
67592
- }
67593
- return import(moduleName);
67594
- }
67595
- var init_importFromUserLand = () => {};
67596
-
67597
67462
  // node_modules/make-vfs/dist/index.js
67598
67463
  var require_dist8 = __commonJS((exports2, module2) => {
67599
67464
  var __create3 = Object.create;
@@ -67605,7 +67470,7 @@ var require_dist8 = __commonJS((exports2, module2) => {
67605
67470
  var __commonJS2 = (cb, mod) => function __require() {
67606
67471
  return mod || (0, cb[__getOwnPropNames3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
67607
67472
  };
67608
- var __export3 = (target, all) => {
67473
+ var __export2 = (target, all) => {
67609
67474
  for (var name in all)
67610
67475
  __defProp3(target, name, { get: all[name], enumerable: true });
67611
67476
  };
@@ -69911,7 +69776,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);
69911
69776
  }
69912
69777
  });
69913
69778
  var src_exports = {};
69914
- __export3(src_exports, {
69779
+ __export2(src_exports, {
69915
69780
  getMatchingFilePaths: () => getMatchingFilePaths2,
69916
69781
  getVirtualFileSystemFromDirPath: () => getVirtualFileSystemFromDirPath,
69917
69782
  getVirtualFilesystemModuleFromDirPath: () => getVirtualFilesystemModuleFromDirPath
@@ -70029,108 +69894,6 @@ export default {
70029
69894
  };
70030
69895
  });
70031
69896
 
70032
- // lib/utils/abbreviate-stringify-object.ts
70033
- var abbreviateStringifyObject = (obj) => {
70034
- if (obj === null || obj === undefined)
70035
- return obj;
70036
- if (typeof obj !== "object")
70037
- return obj;
70038
- return JSON.stringify(Object.fromEntries(Object.entries(obj).map(([k, v]) => {
70039
- return [
70040
- k,
70041
- typeof v === "string" ? v.slice(0, 100) : typeof v === "object" && v !== null ? abbreviateStringifyObject(v) : v
70042
- ];
70043
- })));
70044
- };
70045
-
70046
- // lib/shared/generate-circuit-json.tsx
70047
- import path30 from "node:path";
70048
- import fs28 from "node:fs";
70049
- import { pathToFileURL as pathToFileURL2 } from "node:url";
70050
- import Debug11 from "debug";
70051
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
70052
- async function generateCircuitJson({
70053
- filePath,
70054
- outputDir,
70055
- outputFileName,
70056
- saveToFile = false,
70057
- platformConfig
70058
- }) {
70059
- debug11(`Generating circuit JSON for ${filePath}`);
70060
- const React = await importFromUserLand("react");
70061
- globalThis.React = React;
70062
- const userLandTscircuit = await importFromUserLand("tscircuit");
70063
- const runner = new userLandTscircuit.RootCircuit({
70064
- platform: platformConfig
70065
- });
70066
- const absoluteFilePath = path30.isAbsolute(filePath) ? filePath : path30.resolve(process.cwd(), filePath);
70067
- const projectDir = path30.dirname(absoluteFilePath);
70068
- const resolvedOutputDir = outputDir ?? projectDir;
70069
- const relativeComponentPath = path30.relative(projectDir, absoluteFilePath);
70070
- const baseFileName = outputFileName || path30.basename(absoluteFilePath).replace(/\.[^.]+$/, "");
70071
- const outputPath = path30.join(resolvedOutputDir, `${baseFileName}.circuit.json`);
70072
- debug11(`Project directory: ${projectDir}`);
70073
- debug11(`Relative component path: ${relativeComponentPath}`);
70074
- debug11(`Output path: ${outputPath}`);
70075
- const fsMap = {
70076
- ...await import_make_vfs2.getVirtualFileSystemFromDirPath({
70077
- dirPath: projectDir,
70078
- fileMatchFn: (filePath2) => {
70079
- const normalizedFilePath = filePath2.replace(/\\/g, "/");
70080
- if (normalizedFilePath.endsWith(".kicad_mod")) {
70081
- return true;
70082
- }
70083
- if (normalizedFilePath.includes("node_modules/"))
70084
- return false;
70085
- if (normalizedFilePath.includes("dist/"))
70086
- return false;
70087
- if (normalizedFilePath.includes("build/"))
70088
- return false;
70089
- if (normalizedFilePath.match(/^\.[^/]/))
70090
- return false;
70091
- if (!ALLOWED_FILE_EXTENSIONS.includes(path30.extname(normalizedFilePath)))
70092
- return false;
70093
- return true;
70094
- },
70095
- contentFormat: "string"
70096
- })
70097
- };
70098
- debug11(`fsMap: ${abbreviateStringifyObject(fsMap)}`);
70099
- const MainComponent = await import(pathToFileURL2(absoluteFilePath).href);
70100
- const Component = MainComponent.default || (Object.keys(MainComponent).find((k) => k[0] === k[0].toUpperCase()) !== undefined ? MainComponent[Object.keys(MainComponent).find((k) => k[0] === k[0].toUpperCase())] : undefined);
70101
- if (!Component) {
70102
- throw new Error(`No component found in "${absoluteFilePath}". Make sure you export a component.`);
70103
- }
70104
- runner.add(/* @__PURE__ */ jsxDEV2(Component, {}, undefined, false, undefined, this));
70105
- await runner.renderUntilSettled();
70106
- const circuitJson = await runner.getCircuitJson();
70107
- if (saveToFile) {
70108
- debug11(`Saving circuit JSON to ${outputPath}`);
70109
- fs28.writeFileSync(outputPath, JSON.stringify(circuitJson, null, 2));
70110
- }
70111
- return {
70112
- circuitJson,
70113
- outputPath
70114
- };
70115
- }
70116
- var import_make_vfs2, debug11, ALLOWED_FILE_EXTENSIONS;
70117
- var init_generate_circuit_json = __esm(() => {
70118
- init_importFromUserLand();
70119
- import_make_vfs2 = __toESM2(require_dist8(), 1);
70120
- debug11 = Debug11("tsci:generate-circuit-json");
70121
- ALLOWED_FILE_EXTENSIONS = [
70122
- ".tsx",
70123
- ".ts",
70124
- ".jsx",
70125
- ".js",
70126
- ".json",
70127
- ".txt",
70128
- ".md",
70129
- ".obj",
70130
- ".kicad_mod"
70131
- ];
70132
- });
70133
-
70134
69897
  // node_modules/cli-spinners/spinners.json
70135
69898
  var require_spinners = __commonJS((exports2, module2) => {
70136
69899
  module2.exports = {
@@ -71778,179 +71541,6 @@ var require_emoji_regex = __commonJS((exports2, module2) => {
71778
71541
  };
71779
71542
  });
71780
71543
 
71781
- // lib/shared/circuit-json-diagnostics.ts
71782
- function analyzeCircuitJson(circuitJson) {
71783
- const errors = [];
71784
- const warnings = [];
71785
- for (const item of circuitJson) {
71786
- if (!item || typeof item !== "object")
71787
- continue;
71788
- const t3 = item.type;
71789
- if (typeof t3 === "string") {
71790
- if (t3.endsWith("_error"))
71791
- errors.push(item);
71792
- else if (t3.endsWith("_warning"))
71793
- warnings.push(item);
71794
- }
71795
- if ("error_type" in item)
71796
- errors.push(item);
71797
- if ("warning_type" in item)
71798
- warnings.push(item);
71799
- }
71800
- return { errors, warnings };
71801
- }
71802
-
71803
- // lib/shared/get-complete-platform-config.ts
71804
- import { getPlatformConfig } from "@tscircuit/eval/platform-config";
71805
- function getCompletePlatformConfig(userConfig) {
71806
- const basePlatformConfig = getPlatformConfig();
71807
- const defaultConfig = {
71808
- ...basePlatformConfig,
71809
- footprintFileParserMap: {
71810
- ...basePlatformConfig.footprintFileParserMap,
71811
- kicad_mod: {
71812
- loadFromUrl: async (url) => {
71813
- const fetchUrl = url.startsWith("/") ? `file://${url}` : url;
71814
- return basePlatformConfig.footprintFileParserMap.kicad_mod.loadFromUrl(fetchUrl);
71815
- }
71816
- }
71817
- }
71818
- };
71819
- if (!userConfig) {
71820
- return defaultConfig;
71821
- }
71822
- return {
71823
- ...defaultConfig,
71824
- ...userConfig,
71825
- footprintFileParserMap: {
71826
- ...defaultConfig.footprintFileParserMap,
71827
- ...userConfig.footprintFileParserMap
71828
- }
71829
- };
71830
- }
71831
- var init_get_complete_platform_config = () => {};
71832
-
71833
- // cli/build/build-file.ts
71834
- var exports_build_file = {};
71835
- __export2(exports_build_file, {
71836
- buildFile: () => buildFile
71837
- });
71838
- import path35 from "node:path";
71839
- import fs35 from "node:fs";
71840
- var buildFile = async (input, output, projectDir, options) => {
71841
- try {
71842
- console.log("Generating circuit JSON...");
71843
- const completePlatformConfig = getCompletePlatformConfig(options?.platformConfig);
71844
- const result = await generateCircuitJson({
71845
- filePath: input,
71846
- platformConfig: completePlatformConfig
71847
- });
71848
- fs35.mkdirSync(path35.dirname(output), { recursive: true });
71849
- fs35.writeFileSync(output, JSON.stringify(result.circuitJson, null, 2));
71850
- console.log(`Circuit JSON written to ${path35.relative(projectDir, output)}`);
71851
- const { errors, warnings } = analyzeCircuitJson(result.circuitJson);
71852
- if (!options?.ignoreWarnings) {
71853
- for (const warn of warnings) {
71854
- const msg = warn.message || JSON.stringify(warn);
71855
- console.log(kleur_default.yellow(msg));
71856
- }
71857
- }
71858
- if (!options?.ignoreErrors) {
71859
- for (const err of errors) {
71860
- const msg = err.message || JSON.stringify(err);
71861
- console.error(kleur_default.red(msg));
71862
- console.log(err.stack);
71863
- }
71864
- }
71865
- if (errors.length > 0 && !options?.ignoreErrors) {
71866
- console.error(kleur_default.red(`Build failed with ${errors.length} error(s). Use --ignore-errors to continue.`));
71867
- return { ok: false };
71868
- } else {
71869
- return {
71870
- ok: true,
71871
- circuitJson: result.circuitJson
71872
- };
71873
- }
71874
- } catch (err) {
71875
- console.error(err);
71876
- if (err instanceof Error) {
71877
- logTsxExtensionHint(err, input);
71878
- logTypeReexportHint(err, input);
71879
- }
71880
- return { ok: false };
71881
- }
71882
- }, logTsxExtensionHint = (error, entryFilePath) => {
71883
- const lowerPath = entryFilePath.toLowerCase();
71884
- const isTsEntry = lowerPath.endsWith(".ts") && !lowerPath.endsWith(".d.ts");
71885
- const isAggregateError = error instanceof AggregateError || String(error).includes("AggregateError");
71886
- if (!isTsEntry || !isAggregateError)
71887
- return;
71888
- const entryFileName = path35.basename(entryFilePath);
71889
- console.error([
71890
- "",
71891
- `It looks like "${entryFileName}" is a ".ts" file. tscircuit component files must use the ".tsx" extension.`,
71892
- "Try renaming the file to .tsx and re-running the build.",
71893
- ""
71894
- ].join(`
71895
- `));
71896
- }, TYPE_REEXPORT_ERROR_REGEX, logTypeReexportHint = (error, entryFilePath) => {
71897
- const match = String(error).match(TYPE_REEXPORT_ERROR_REGEX);
71898
- if (!match)
71899
- return;
71900
- const [, exportName, fromSpecifier] = match;
71901
- const entryFileName = path35.basename(entryFilePath);
71902
- console.error([
71903
- "",
71904
- `It looks like "${entryFileName}" re-exports the type-only symbol "${exportName}" from "${fromSpecifier}" without the "type" modifier.`,
71905
- "Type-only exports must be re-exported with `export type { ... }`.",
71906
- "Try rewriting the statement as:",
71907
- ` export type { ${exportName} } from "${fromSpecifier}"`,
71908
- ""
71909
- ].join(`
71910
- `));
71911
- };
71912
- var init_build_file = __esm(() => {
71913
- init_kleur();
71914
- init_generate_circuit_json();
71915
- init_get_complete_platform_config();
71916
- TYPE_REEXPORT_ERROR_REGEX = /SyntaxError: export '([^']+)' not found in '([^']+)'/;
71917
- });
71918
-
71919
- // lib/shared/register-static-asset-loaders.ts
71920
- var exports_register_static_asset_loaders = {};
71921
- __export2(exports_register_static_asset_loaders, {
71922
- registerStaticAssetLoaders: () => registerStaticAssetLoaders
71923
- });
71924
- var TEXT_STATIC_ASSET_EXTENSIONS, staticAssetFilter, registered = false, registerStaticAssetLoaders = () => {
71925
- if (registered)
71926
- return;
71927
- registered = true;
71928
- if (typeof Bun !== "undefined" && typeof Bun.plugin === "function") {
71929
- Bun.plugin({
71930
- name: "tsci-static-assets",
71931
- setup(build) {
71932
- build.onLoad({ filter: staticAssetFilter }, (args) => {
71933
- return {
71934
- contents: `export default ${JSON.stringify(args.path)};`,
71935
- loader: "js"
71936
- };
71937
- });
71938
- }
71939
- });
71940
- }
71941
- };
71942
- var init_register_static_asset_loaders = __esm(() => {
71943
- TEXT_STATIC_ASSET_EXTENSIONS = [
71944
- ".gltf",
71945
- ".step",
71946
- ".kicad_mod",
71947
- ".kicad_pcb",
71948
- ".kicad_pro",
71949
- ".kicad_sch"
71950
- ];
71951
- staticAssetFilter = new RegExp(`(${TEXT_STATIC_ASSET_EXTENSIONS.map((ext) => ext.replace(".", "\\.")).join("|")})$`, "i");
71952
- });
71953
-
71954
71544
  // node_modules/commander/esm.mjs
71955
71545
  var import__ = __toESM2(require_commander(), 1);
71956
71546
  var {
@@ -71976,8 +71566,106 @@ import fs2 from "node:fs";
71976
71566
  import path from "node:path";
71977
71567
 
71978
71568
  // lib/shared/get-package-manager.ts
71979
- init_kleur();
71980
71569
  import fs from "fs";
71570
+
71571
+ // node_modules/kleur/index.mjs
71572
+ var FORCE_COLOR;
71573
+ var NODE_DISABLE_COLORS;
71574
+ var NO_COLOR;
71575
+ var TERM;
71576
+ var isTTY = true;
71577
+ if (typeof process !== "undefined") {
71578
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
71579
+ isTTY = process.stdout && process.stdout.isTTY;
71580
+ }
71581
+ var $ = {
71582
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY),
71583
+ reset: init(0, 0),
71584
+ bold: init(1, 22),
71585
+ dim: init(2, 22),
71586
+ italic: init(3, 23),
71587
+ underline: init(4, 24),
71588
+ inverse: init(7, 27),
71589
+ hidden: init(8, 28),
71590
+ strikethrough: init(9, 29),
71591
+ black: init(30, 39),
71592
+ red: init(31, 39),
71593
+ green: init(32, 39),
71594
+ yellow: init(33, 39),
71595
+ blue: init(34, 39),
71596
+ magenta: init(35, 39),
71597
+ cyan: init(36, 39),
71598
+ white: init(37, 39),
71599
+ gray: init(90, 39),
71600
+ grey: init(90, 39),
71601
+ bgBlack: init(40, 49),
71602
+ bgRed: init(41, 49),
71603
+ bgGreen: init(42, 49),
71604
+ bgYellow: init(43, 49),
71605
+ bgBlue: init(44, 49),
71606
+ bgMagenta: init(45, 49),
71607
+ bgCyan: init(46, 49),
71608
+ bgWhite: init(47, 49)
71609
+ };
71610
+ function run(arr, str) {
71611
+ let i = 0, tmp, beg = "", end = "";
71612
+ for (;i < arr.length; i++) {
71613
+ tmp = arr[i];
71614
+ beg += tmp.open;
71615
+ end += tmp.close;
71616
+ if (!!~str.indexOf(tmp.close)) {
71617
+ str = str.replace(tmp.rgx, tmp.close + tmp.open);
71618
+ }
71619
+ }
71620
+ return beg + str + end;
71621
+ }
71622
+ function chain(has, keys) {
71623
+ let ctx = { has, keys };
71624
+ ctx.reset = $.reset.bind(ctx);
71625
+ ctx.bold = $.bold.bind(ctx);
71626
+ ctx.dim = $.dim.bind(ctx);
71627
+ ctx.italic = $.italic.bind(ctx);
71628
+ ctx.underline = $.underline.bind(ctx);
71629
+ ctx.inverse = $.inverse.bind(ctx);
71630
+ ctx.hidden = $.hidden.bind(ctx);
71631
+ ctx.strikethrough = $.strikethrough.bind(ctx);
71632
+ ctx.black = $.black.bind(ctx);
71633
+ ctx.red = $.red.bind(ctx);
71634
+ ctx.green = $.green.bind(ctx);
71635
+ ctx.yellow = $.yellow.bind(ctx);
71636
+ ctx.blue = $.blue.bind(ctx);
71637
+ ctx.magenta = $.magenta.bind(ctx);
71638
+ ctx.cyan = $.cyan.bind(ctx);
71639
+ ctx.white = $.white.bind(ctx);
71640
+ ctx.gray = $.gray.bind(ctx);
71641
+ ctx.grey = $.grey.bind(ctx);
71642
+ ctx.bgBlack = $.bgBlack.bind(ctx);
71643
+ ctx.bgRed = $.bgRed.bind(ctx);
71644
+ ctx.bgGreen = $.bgGreen.bind(ctx);
71645
+ ctx.bgYellow = $.bgYellow.bind(ctx);
71646
+ ctx.bgBlue = $.bgBlue.bind(ctx);
71647
+ ctx.bgMagenta = $.bgMagenta.bind(ctx);
71648
+ ctx.bgCyan = $.bgCyan.bind(ctx);
71649
+ ctx.bgWhite = $.bgWhite.bind(ctx);
71650
+ return ctx;
71651
+ }
71652
+ function init(open, close) {
71653
+ let blk = {
71654
+ open: `\x1B[${open}m`,
71655
+ close: `\x1B[${close}m`,
71656
+ rgx: new RegExp(`\\x1b\\[${close}m`, "g")
71657
+ };
71658
+ return function(txt) {
71659
+ if (this !== undefined && this.has !== undefined) {
71660
+ !!~this.has.indexOf(open) || (this.has.push(open), this.keys.push(blk));
71661
+ return txt === undefined ? this : $.enabled ? run(this.keys, txt + "") : txt + "";
71662
+ }
71663
+ return txt === undefined ? chain([open], [blk]) : $.enabled ? run([blk], txt + "") : txt + "";
71664
+ };
71665
+ }
71666
+ var kleur_default = $;
71667
+
71668
+ // lib/shared/get-package-manager.ts
71981
71669
  import { execSync } from "node:child_process";
71982
71670
  function detectPackageManager() {
71983
71671
  const userAgent = process.env.npm_config_user_agent || "";
@@ -74441,7 +74129,7 @@ var getGlobalDepsInstallCommand = (packageManager, deps) => {
74441
74129
  import { execSync as execSync2 } from "node:child_process";
74442
74130
  var import_semver2 = __toESM2(require_semver2(), 1);
74443
74131
  // package.json
74444
- var version = "0.1.776";
74132
+ var version = "0.1.778";
74445
74133
  var package_default = {
74446
74134
  name: "@tscircuit/cli",
74447
74135
  version,
@@ -74494,7 +74182,6 @@ var package_default = {
74494
74182
  "looks-same": "^9.0.1",
74495
74183
  "make-vfs": "^1.0.15",
74496
74184
  md5: "^2.3.0",
74497
- multithreading: "^0.3.45",
74498
74185
  "perfect-cli": "^1.0.21",
74499
74186
  playwright: "^1.57.0",
74500
74187
  poppygl: "^0.0.12",
@@ -74539,9 +74226,6 @@ var package_default = {
74539
74226
  type: "module"
74540
74227
  };
74541
74228
 
74542
- // lib/shared/check-for-cli-update.ts
74543
- init_kleur();
74544
-
74545
74229
  // lib/utils/prompts.ts
74546
74230
  var import_prompts = __toESM2(require_prompts3(), 1);
74547
74231
 
@@ -78040,7 +77724,6 @@ function watch(paths, options = {}) {
78040
77724
  }
78041
77725
 
78042
77726
  // lib/shared/push-snippet.ts
78043
- init_kleur();
78044
77727
  var import_semver3 = __toESM2(require_semver2(), 1);
78045
77728
  import * as fs13 from "node:fs";
78046
77729
  import * as path15 from "node:path";
@@ -78049,7 +77732,6 @@ import Debug from "debug";
78049
77732
  // lib/shared/get-entrypoint.ts
78050
77733
  import * as fs9 from "node:fs";
78051
77734
  import * as path11 from "node:path";
78052
- init_kleur();
78053
77735
  var ALLOWED_ENTRYPOINT_NAMES = Object.freeze([
78054
77736
  "index.tsx",
78055
77737
  "index.ts",
@@ -79077,7 +78759,6 @@ Publish completed with ${uploadResults.succeeded.length} files uploaded and ${up
79077
78759
  };
79078
78760
 
79079
78761
  // lib/shared/add-package.ts
79080
- init_kleur();
79081
78762
  import * as fs16 from "node:fs";
79082
78763
  import * as path18 from "node:path";
79083
78764
 
@@ -79110,7 +78791,6 @@ async function resolveTarballUrlFromRegistry(packageName) {
79110
78791
  // lib/shared/detect-and-setup-kicad-library.ts
79111
78792
  import * as fs14 from "node:fs";
79112
78793
  import * as path16 from "node:path";
79113
- init_kleur();
79114
78794
  var import_strip_json_comments = __toESM2(require_strip_json_comments(), 1);
79115
78795
  function extractPackageName(packageSpec) {
79116
78796
  if (packageSpec.startsWith("http")) {
@@ -79201,7 +78881,6 @@ async function setupTsConfig(projectDir) {
79201
78881
  }
79202
78882
 
79203
78883
  // lib/shared/handle-registry-auth-error.ts
79204
- init_kleur();
79205
78884
  import fs15 from "node:fs";
79206
78885
  import os2 from "node:os";
79207
78886
  import path17 from "node:path";
@@ -79315,7 +78994,6 @@ async function addPackage(packageSpec, projectDir = process.cwd()) {
79315
78994
  }
79316
78995
 
79317
78996
  // cli/dev/DevServer.ts
79318
- init_kleur();
79319
78997
  import Debug2 from "debug";
79320
78998
 
79321
78999
  // lib/dependency-analysis/getNodeModuleDependencies.ts
@@ -80126,9 +79804,6 @@ var resolveDevTarget = async (file) => {
80126
79804
  return { absolutePath: availableFiles[0], projectDir };
80127
79805
  };
80128
79806
 
80129
- // cli/dev/register.ts
80130
- init_kleur();
80131
-
80132
79807
  // lib/getVersion.ts
80133
79808
  var import_semver4 = __toESM2(require_semver2(), 1);
80134
79809
  var getVersion = () => {
@@ -80237,11 +79912,7 @@ function createDelay({ clearTimeout: defaultClear, setTimeout: defaultSet } = {}
80237
79912
  var delay2 = createDelay();
80238
79913
  var delay_default = delay2;
80239
79914
 
80240
- // cli/auth/login/register.ts
80241
- init_kleur();
80242
-
80243
79915
  // cli/auth/setup-npmrc/setup-npmrc.ts
80244
- init_kleur();
80245
79916
  import * as fs22 from "node:fs";
80246
79917
  import * as path24 from "node:path";
80247
79918
  import * as os3 from "node:os";
@@ -80419,11 +80090,9 @@ var registerConfigPrint = (program3) => {
80419
80090
  // cli/clone/register.ts
80420
80091
  import * as fs25 from "node:fs";
80421
80092
  import * as path27 from "node:path";
80422
- init_kleur();
80423
80093
 
80424
80094
  // cli/clone/clone-bug-report.ts
80425
80095
  var import_jszip = __toESM2(require_lib4(), 1);
80426
- init_kleur();
80427
80096
  var import_prompts7 = __toESM2(require_prompts3(), 1);
80428
80097
  import * as fs24 from "node:fs";
80429
80098
  import * as path26 from "node:path";
@@ -84810,7 +84479,37 @@ function createKicadLibraryConverterContext(params2) {
84810
84479
  import fs27 from "node:fs";
84811
84480
  import path29 from "node:path";
84812
84481
  import { pathToFileURL } from "node:url";
84813
- init_importFromUserLand();
84482
+
84483
+ // lib/shared/importFromUserLand.ts
84484
+ import { createRequire as createRequire2 } from "node:module";
84485
+ import fs26 from "node:fs";
84486
+ import path28 from "node:path";
84487
+ async function importFromUserLand(moduleName) {
84488
+ const userModulePath = path28.join(process.cwd(), "node_modules", moduleName);
84489
+ if (fs26.existsSync(userModulePath)) {
84490
+ const userRequire = createRequire2(path28.join(process.cwd(), "noop.js"));
84491
+ try {
84492
+ const resolvedUserPath = userRequire.resolve(moduleName);
84493
+ return await import(resolvedUserPath);
84494
+ } catch (error) {
84495
+ if (error?.code !== "MODULE_NOT_FOUND") {
84496
+ throw error;
84497
+ }
84498
+ }
84499
+ }
84500
+ const cliRequire = createRequire2(import.meta.url);
84501
+ try {
84502
+ const resolvedCliPath = cliRequire.resolve(moduleName);
84503
+ return await import(resolvedCliPath);
84504
+ } catch (error) {
84505
+ if (error?.code !== "MODULE_NOT_FOUND") {
84506
+ throw error;
84507
+ }
84508
+ }
84509
+ return import(moduleName);
84510
+ }
84511
+
84512
+ // lib/shared/convert-to-kicad-library.tsx
84814
84513
  import { jsxDEV } from "react/jsx-dev-runtime";
84815
84514
  async function convertToKicadLibrary({
84816
84515
  filePath,
@@ -84878,8 +84577,109 @@ async function convertToKicadLibrary({
84878
84577
  }
84879
84578
 
84880
84579
  // lib/shared/export-snippet.ts
84881
- init_generate_circuit_json();
84882
84580
  var import_jszip2 = __toESM2(require_lib4(), 1);
84581
+
84582
+ // lib/shared/generate-circuit-json.tsx
84583
+ var import_make_vfs2 = __toESM2(require_dist8(), 1);
84584
+ import path30 from "node:path";
84585
+ import fs28 from "node:fs";
84586
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
84587
+ import Debug11 from "debug";
84588
+
84589
+ // lib/utils/abbreviate-stringify-object.ts
84590
+ var abbreviateStringifyObject = (obj) => {
84591
+ if (obj === null || obj === undefined)
84592
+ return obj;
84593
+ if (typeof obj !== "object")
84594
+ return obj;
84595
+ return JSON.stringify(Object.fromEntries(Object.entries(obj).map(([k, v]) => {
84596
+ return [
84597
+ k,
84598
+ typeof v === "string" ? v.slice(0, 100) : typeof v === "object" && v !== null ? abbreviateStringifyObject(v) : v
84599
+ ];
84600
+ })));
84601
+ };
84602
+
84603
+ // lib/shared/generate-circuit-json.tsx
84604
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
84605
+ var debug11 = Debug11("tsci:generate-circuit-json");
84606
+ var ALLOWED_FILE_EXTENSIONS = [
84607
+ ".tsx",
84608
+ ".ts",
84609
+ ".jsx",
84610
+ ".js",
84611
+ ".json",
84612
+ ".txt",
84613
+ ".md",
84614
+ ".obj",
84615
+ ".kicad_mod"
84616
+ ];
84617
+ async function generateCircuitJson({
84618
+ filePath,
84619
+ outputDir,
84620
+ outputFileName,
84621
+ saveToFile = false,
84622
+ platformConfig
84623
+ }) {
84624
+ debug11(`Generating circuit JSON for ${filePath}`);
84625
+ const React = await importFromUserLand("react");
84626
+ globalThis.React = React;
84627
+ const userLandTscircuit = await importFromUserLand("tscircuit");
84628
+ const runner = new userLandTscircuit.RootCircuit({
84629
+ platform: platformConfig
84630
+ });
84631
+ const absoluteFilePath = path30.isAbsolute(filePath) ? filePath : path30.resolve(process.cwd(), filePath);
84632
+ const projectDir = path30.dirname(absoluteFilePath);
84633
+ const resolvedOutputDir = outputDir ?? projectDir;
84634
+ const relativeComponentPath = path30.relative(projectDir, absoluteFilePath);
84635
+ const baseFileName = outputFileName || path30.basename(absoluteFilePath).replace(/\.[^.]+$/, "");
84636
+ const outputPath = path30.join(resolvedOutputDir, `${baseFileName}.circuit.json`);
84637
+ debug11(`Project directory: ${projectDir}`);
84638
+ debug11(`Relative component path: ${relativeComponentPath}`);
84639
+ debug11(`Output path: ${outputPath}`);
84640
+ const fsMap = {
84641
+ ...await import_make_vfs2.getVirtualFileSystemFromDirPath({
84642
+ dirPath: projectDir,
84643
+ fileMatchFn: (filePath2) => {
84644
+ const normalizedFilePath = filePath2.replace(/\\/g, "/");
84645
+ if (normalizedFilePath.endsWith(".kicad_mod")) {
84646
+ return true;
84647
+ }
84648
+ if (normalizedFilePath.includes("node_modules/"))
84649
+ return false;
84650
+ if (normalizedFilePath.includes("dist/"))
84651
+ return false;
84652
+ if (normalizedFilePath.includes("build/"))
84653
+ return false;
84654
+ if (normalizedFilePath.match(/^\.[^/]/))
84655
+ return false;
84656
+ if (!ALLOWED_FILE_EXTENSIONS.includes(path30.extname(normalizedFilePath)))
84657
+ return false;
84658
+ return true;
84659
+ },
84660
+ contentFormat: "string"
84661
+ })
84662
+ };
84663
+ debug11(`fsMap: ${abbreviateStringifyObject(fsMap)}`);
84664
+ const MainComponent = await import(pathToFileURL2(absoluteFilePath).href);
84665
+ const Component = MainComponent.default || (Object.keys(MainComponent).find((k) => k[0] === k[0].toUpperCase()) !== undefined ? MainComponent[Object.keys(MainComponent).find((k) => k[0] === k[0].toUpperCase())] : undefined);
84666
+ if (!Component) {
84667
+ throw new Error(`No component found in "${absoluteFilePath}". Make sure you export a component.`);
84668
+ }
84669
+ runner.add(/* @__PURE__ */ jsxDEV2(Component, {}, undefined, false, undefined, this));
84670
+ await runner.renderUntilSettled();
84671
+ const circuitJson = await runner.getCircuitJson();
84672
+ if (saveToFile) {
84673
+ debug11(`Saving circuit JSON to ${outputPath}`);
84674
+ fs28.writeFileSync(outputPath, JSON.stringify(circuitJson, null, 2));
84675
+ }
84676
+ return {
84677
+ circuitJson,
84678
+ outputPath
84679
+ };
84680
+ }
84681
+
84682
+ // lib/shared/export-snippet.ts
84883
84683
  var writeFileAsync = promisify3(fs29.writeFile);
84884
84684
  var ALLOWED_EXPORT_FORMATS = [
84885
84685
  "json",
@@ -85018,9 +84818,6 @@ var exportSnippet = async ({
85018
84818
  onExit(0);
85019
84819
  };
85020
84820
 
85021
- // cli/export/register.ts
85022
- init_generate_circuit_json();
85023
-
85024
84821
  // lib/shared/get-spice-with-sim.ts
85025
84822
  import { circuitJsonToSpice } from "circuit-json-to-spice";
85026
84823
  var formatSimTime = (seconds) => {
@@ -85300,7 +85097,6 @@ var registerAuthSetToken = (program3) => {
85300
85097
  };
85301
85098
 
85302
85099
  // cli/auth/whoami/register.ts
85303
- init_kleur();
85304
85100
  var formatDate = (date) => {
85305
85101
  if (!date)
85306
85102
  return null;
@@ -85360,7 +85156,6 @@ var registerAdd = (program3) => {
85360
85156
  };
85361
85157
 
85362
85158
  // cli/upgrade/register.ts
85363
- init_kleur();
85364
85159
  function registerUpgradeCommand(program3) {
85365
85160
  program3.command("upgrade").description("Upgrade CLI to the latest version").action(async () => {
85366
85161
  const isUpdated = await updateTsciIfNewVersionIsAvailable();
@@ -85371,7 +85166,6 @@ function registerUpgradeCommand(program3) {
85371
85166
  }
85372
85167
 
85373
85168
  // cli/config/set/register.ts
85374
- init_kleur();
85375
85169
  var availableGlobalConfigKeys = [
85376
85170
  "alwaysCloneWithAuthorName"
85377
85171
  ];
@@ -86708,7 +86502,6 @@ Fuse.config = Config;
86708
86502
  }
86709
86503
 
86710
86504
  // cli/search/register.ts
86711
- init_kleur();
86712
86505
  var registerSearch = (program3) => {
86713
86506
  program3.command("search").description("Search for footprints, CAD models or packages in the tscircuit ecosystem").argument("<query>", "Search query (e.g. keyword, author, or package name)").option("--kicad", "Only search KiCad footprints").action(async (query, opts) => {
86714
86507
  const onlyKicad = opts.kicad;
@@ -86762,9 +86555,6 @@ var registerSearch = (program3) => {
86762
86555
  });
86763
86556
  };
86764
86557
 
86765
- // cli/import/register.ts
86766
- init_kleur();
86767
-
86768
86558
  // node_modules/easyeda/dist/browser/chunk-ZVLWDN7A.js
86769
86559
  var __create3 = Object.create;
86770
86560
  var __defProp3 = Object.defineProperty;
@@ -86780,7 +86570,7 @@ var __require2 = /* @__PURE__ */ ((x) => __require)(function(x) {
86780
86570
  var __commonJS2 = (cb, mod) => function __require2() {
86781
86571
  return mod || (0, cb[__getOwnPropNames3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
86782
86572
  };
86783
- var __export3 = (target, all) => {
86573
+ var __export2 = (target, all) => {
86784
86574
  for (var name in all)
86785
86575
  __defProp3(target, name, { get: all[name], enumerable: true });
86786
86576
  };
@@ -87574,7 +87364,7 @@ var require_svgson_umd = __commonJS2({
87574
87364
  }
87575
87365
  });
87576
87366
  var dist_exports = {};
87577
- __export3(dist_exports, {
87367
+ __export2(dist_exports, {
87578
87368
  all_layers: () => all_layers,
87579
87369
  any_circuit_element: () => any_circuit_element,
87580
87370
  any_soup_element: () => any_soup_element,
@@ -87752,7 +87542,7 @@ __export3(dist_exports, {
87752
87542
  wave_shape: () => wave_shape
87753
87543
  });
87754
87544
  var external_exports = {};
87755
- __export3(external_exports, {
87545
+ __export2(external_exports, {
87756
87546
  BRAND: () => BRAND,
87757
87547
  DIRTY: () => DIRTY,
87758
87548
  EMPTY_PATH: () => EMPTY_PATH,
@@ -121558,7 +121348,7 @@ var import_constants14 = __toESM3(require_constants6(), 1);
121558
121348
  var import_debug62 = __toESM3(require_browser(), 1);
121559
121349
  var import_debug72 = __toESM3(require_browser(), 1);
121560
121350
  var esm_exports2 = {};
121561
- __export3(esm_exports2, {
121351
+ __export2(esm_exports2, {
121562
121352
  DocumentPosition: () => DocumentPosition,
121563
121353
  append: () => append,
121564
121354
  appendChild: () => appendChild,
@@ -154773,12 +154563,12 @@ var import_jsx_runtime5 = __toESM3(require_jsx_runtime(), 1);
154773
154563
  var import_jsx_runtime6 = __toESM3(require_jsx_runtime(), 1);
154774
154564
  var import_react7 = __toESM3(require_react(), 1);
154775
154565
  var __defProp32 = Object.defineProperty;
154776
- var __export32 = (target, all) => {
154566
+ var __export3 = (target, all) => {
154777
154567
  for (var name in all)
154778
154568
  __defProp32(target, name, { get: all[name], enumerable: true });
154779
154569
  };
154780
154570
  var components_exports = {};
154781
- __export32(components_exports, {
154571
+ __export3(components_exports, {
154782
154572
  AnalogSimulation: () => AnalogSimulation,
154783
154573
  Battery: () => Battery,
154784
154574
  Board: () => Board,
@@ -172637,16 +172427,145 @@ var registerRemove = (program3) => {
172637
172427
  };
172638
172428
 
172639
172429
  // cli/build/register.ts
172640
- init_build_file();
172641
- import path47 from "node:path";
172642
- import fs47 from "node:fs";
172430
+ import path48 from "node:path";
172431
+ import fs48 from "node:fs";
172432
+
172433
+ // cli/build/build-file.ts
172434
+ import path35 from "node:path";
172435
+ import fs35 from "node:fs";
172436
+
172437
+ // lib/shared/circuit-json-diagnostics.ts
172438
+ function analyzeCircuitJson(circuitJson) {
172439
+ const errors = [];
172440
+ const warnings = [];
172441
+ for (const item of circuitJson) {
172442
+ if (!item || typeof item !== "object")
172443
+ continue;
172444
+ const t3 = item.type;
172445
+ if (typeof t3 === "string") {
172446
+ if (t3.endsWith("_error"))
172447
+ errors.push(item);
172448
+ else if (t3.endsWith("_warning"))
172449
+ warnings.push(item);
172450
+ }
172451
+ if ("error_type" in item)
172452
+ errors.push(item);
172453
+ if ("warning_type" in item)
172454
+ warnings.push(item);
172455
+ }
172456
+ return { errors, warnings };
172457
+ }
172458
+
172459
+ // lib/shared/get-complete-platform-config.ts
172460
+ import { getPlatformConfig } from "@tscircuit/eval/platform-config";
172461
+ function getCompletePlatformConfig(userConfig) {
172462
+ const basePlatformConfig = getPlatformConfig();
172463
+ const defaultConfig = {
172464
+ ...basePlatformConfig,
172465
+ footprintFileParserMap: {
172466
+ ...basePlatformConfig.footprintFileParserMap,
172467
+ kicad_mod: {
172468
+ loadFromUrl: async (url) => {
172469
+ const fetchUrl = url.startsWith("/") ? `file://${url}` : url;
172470
+ return basePlatformConfig.footprintFileParserMap.kicad_mod.loadFromUrl(fetchUrl);
172471
+ }
172472
+ }
172473
+ }
172474
+ };
172475
+ if (!userConfig) {
172476
+ return defaultConfig;
172477
+ }
172478
+ return {
172479
+ ...defaultConfig,
172480
+ ...userConfig,
172481
+ footprintFileParserMap: {
172482
+ ...defaultConfig.footprintFileParserMap,
172483
+ ...userConfig.footprintFileParserMap
172484
+ }
172485
+ };
172486
+ }
172487
+
172488
+ // cli/build/build-file.ts
172489
+ var buildFile = async (input, output, projectDir, options) => {
172490
+ try {
172491
+ console.log("Generating circuit JSON...");
172492
+ const completePlatformConfig = getCompletePlatformConfig(options?.platformConfig);
172493
+ const result = await generateCircuitJson({
172494
+ filePath: input,
172495
+ platformConfig: completePlatformConfig
172496
+ });
172497
+ fs35.mkdirSync(path35.dirname(output), { recursive: true });
172498
+ fs35.writeFileSync(output, JSON.stringify(result.circuitJson, null, 2));
172499
+ console.log(`Circuit JSON written to ${path35.relative(projectDir, output)}`);
172500
+ const { errors, warnings } = analyzeCircuitJson(result.circuitJson);
172501
+ if (!options?.ignoreWarnings) {
172502
+ for (const warn of warnings) {
172503
+ const msg = warn.message || JSON.stringify(warn);
172504
+ console.log(kleur_default.yellow(msg));
172505
+ }
172506
+ }
172507
+ if (!options?.ignoreErrors) {
172508
+ for (const err of errors) {
172509
+ const msg = err.message || JSON.stringify(err);
172510
+ console.error(kleur_default.red(msg));
172511
+ console.log(err.stack);
172512
+ }
172513
+ }
172514
+ if (errors.length > 0 && !options?.ignoreErrors) {
172515
+ console.error(kleur_default.red(`Build failed with ${errors.length} error(s). Use --ignore-errors to continue.`));
172516
+ return { ok: false };
172517
+ } else {
172518
+ return {
172519
+ ok: true,
172520
+ circuitJson: result.circuitJson
172521
+ };
172522
+ }
172523
+ } catch (err) {
172524
+ console.error(err);
172525
+ if (err instanceof Error) {
172526
+ logTsxExtensionHint(err, input);
172527
+ logTypeReexportHint(err, input);
172528
+ }
172529
+ return { ok: false };
172530
+ }
172531
+ };
172532
+ var logTsxExtensionHint = (error, entryFilePath) => {
172533
+ const lowerPath = entryFilePath.toLowerCase();
172534
+ const isTsEntry = lowerPath.endsWith(".ts") && !lowerPath.endsWith(".d.ts");
172535
+ const isAggregateError = error instanceof AggregateError || String(error).includes("AggregateError");
172536
+ if (!isTsEntry || !isAggregateError)
172537
+ return;
172538
+ const entryFileName = path35.basename(entryFilePath);
172539
+ console.error([
172540
+ "",
172541
+ `It looks like "${entryFileName}" is a ".ts" file. tscircuit component files must use the ".tsx" extension.`,
172542
+ "Try renaming the file to .tsx and re-running the build.",
172543
+ ""
172544
+ ].join(`
172545
+ `));
172546
+ };
172547
+ var TYPE_REEXPORT_ERROR_REGEX = /SyntaxError: export '([^']+)' not found in '([^']+)'/;
172548
+ var logTypeReexportHint = (error, entryFilePath) => {
172549
+ const match = String(error).match(TYPE_REEXPORT_ERROR_REGEX);
172550
+ if (!match)
172551
+ return;
172552
+ const [, exportName, fromSpecifier] = match;
172553
+ const entryFileName = path35.basename(entryFilePath);
172554
+ console.error([
172555
+ "",
172556
+ `It looks like "${entryFileName}" re-exports the type-only symbol "${exportName}" from "${fromSpecifier}" without the "type" modifier.`,
172557
+ "Type-only exports must be re-exported with `export type { ... }`.",
172558
+ "Try rewriting the statement as:",
172559
+ ` export type { ${exportName} } from "${fromSpecifier}"`,
172560
+ ""
172561
+ ].join(`
172562
+ `));
172563
+ };
172643
172564
 
172644
172565
  // cli/build/build-ci.ts
172645
- init_kleur();
172646
172566
  import { execSync as execSync3 } from "node:child_process";
172647
172567
 
172648
172568
  // lib/shared/install-project-dependencies.ts
172649
- init_kleur();
172650
172569
  import fs37 from "node:fs";
172651
172570
  import path37 from "node:path";
172652
172571
 
@@ -173231,7 +173150,6 @@ var generateKicadProject = async ({
173231
173150
  };
173232
173151
 
173233
173152
  // cli/build/build-kicad-pcm.ts
173234
- init_kleur();
173235
173153
  import path43 from "node:path";
173236
173154
  import fs43 from "node:fs";
173237
173155
 
@@ -173427,7 +173345,6 @@ async function buildKicadPcm({
173427
173345
  }
173428
173346
 
173429
173347
  // cli/build/transpile/index.ts
173430
- init_kleur();
173431
173348
  import path45 from "node:path";
173432
173349
  import fs45 from "node:fs";
173433
173350
  import { rollup } from "rollup";
@@ -173764,2655 +173681,176 @@ async function getLatestTscircuitCdnUrl() {
173764
173681
  return `https://cdn.jsdelivr.net/npm/tscircuit@${version2}/dist/browser.min.js`;
173765
173682
  }
173766
173683
 
173767
- // cli/build/register.ts
173768
- init_kleur();
173769
-
173770
- // node_modules/multithreading/src/node/polyfill.js
173771
- import { isMainThread, parentPort, Worker as NodeWorker } from "node:worker_threads";
173772
- globalThis.self = globalThis;
173773
- globalThis.ErrorEvent = class ErrorEvent2 extends Event {
173774
- constructor(type, init2) {
173775
- super(type, init2);
173776
- this.message = init2?.message || "";
173777
- this.filename = init2?.filename || "";
173778
- this.lineno = init2?.lineno || 0;
173779
- this.colno = init2?.colno || 0;
173780
- this.error = init2?.error || null;
173781
- }
173782
- };
173783
- if (isMainThread) {
173784
- globalThis.Worker = class Worker2 extends EventTarget {
173785
- constructor(scriptURL, options) {
173786
- super();
173787
- this.onmessage = null;
173788
- this.onerror = null;
173789
- const urlStr = scriptURL.toString();
173790
- const finalPath = urlStr.startsWith("file://") ? new URL(urlStr) : urlStr;
173791
- this._worker = new NodeWorker(finalPath, { ...options });
173792
- this._worker.on("message", (data) => {
173793
- const event = new MessageEvent("message", { data });
173794
- this.dispatchEvent(event);
173795
- if (this.onmessage)
173796
- this.onmessage(event);
173797
- });
173798
- this._worker.on("error", (error) => {
173799
- const event = new ErrorEvent("error", {
173800
- error,
173801
- message: error.message
173802
- });
173803
- this.dispatchEvent(event);
173804
- if (this.onerror)
173805
- this.onerror(event);
173806
- });
173807
- this._worker.on("exit", (code) => {
173808
- if (code !== 0) {
173809
- const err = new Error(`Worker stopped with exit code ${code}`);
173810
- const event = new ErrorEvent("error", {
173811
- error: err,
173812
- message: err.message
173813
- });
173814
- this.dispatchEvent(event);
173815
- if (this.onerror)
173816
- this.onerror(event);
173817
- }
173818
- });
173819
- }
173820
- postMessage(message, transfer) {
173821
- this._worker.postMessage(message, transfer);
173822
- }
173823
- terminate() {
173824
- this._worker.terminate();
173825
- }
173826
- };
173827
- }
173828
- if (!isMainThread && parentPort) {
173829
-
173830
- class WorkerGlobalScope extends EventTarget {
173831
- static [Symbol.hasInstance](instance) {
173832
- return instance === globalThis;
173833
- }
173834
- }
173835
- globalThis.WorkerGlobalScope = WorkerGlobalScope;
173836
- globalThis.postMessage = (message, transfer) => {
173837
- parentPort.postMessage(message, transfer);
173838
- };
173839
- let currentHandler = globalThis.onmessage;
173840
- parentPort.on("message", (data) => {
173841
- const event = new MessageEvent("message", { data });
173842
- if (typeof globalThis.onmessage === "function") {
173843
- globalThis.onmessage(event);
173844
- }
173845
- });
173846
- Object.defineProperty(globalThis, "onmessage", {
173847
- get: () => currentHandler,
173848
- set: (fn3) => {
173849
- currentHandler = fn3;
173850
- },
173851
- configurable: true,
173852
- enumerable: true
173853
- });
173854
- }
173855
-
173856
- // node_modules/multithreading/src/lib/shared.js
173857
- var toSerialized = Symbol("Thread.Serialize");
173858
- var toDeserialized = Symbol("Thread.Deserialize");
173859
-
173860
- class Serializable {
173861
- static [toDeserialized](obj) {
173862
- throw new Error(`[toDeserialized] not implemented for ${this.name}`);
173863
- }
173864
- }
173865
- var classRegistry = new Map;
173866
- var reverseClassRegistry = new Map;
173867
- function register2(typeId, cls) {
173868
- classRegistry.set(typeId, cls);
173869
- reverseClassRegistry.set(cls, typeId);
173870
- }
173871
- var TRANSFERABLE_CLASSES = [
173872
- MessagePort,
173873
- ReadableStream,
173874
- WritableStream,
173875
- TransformStream,
173876
- ArrayBuffer
173877
- ];
173878
- function serialize(arg) {
173879
- if (arg === null || arg === undefined) {
173880
- return { value: { t: 0, v: arg }, transfer: [] };
173881
- }
173882
- if (typeof arg === "object" && arg !== null && typeof arg[toSerialized] === "function") {
173883
- const { value, transfer: transfer2, typeId } = arg[toSerialized]();
173884
- const Ctor = arg.constructor;
173885
- return {
173886
- value: {
173887
- t: 1,
173888
- c: typeId ?? reverseClassRegistry.get(Ctor),
173889
- v: value
173890
- },
173891
- transfer: transfer2
173892
- };
173893
- }
173894
- const transfer = [];
173895
- if (arg instanceof SharedArrayBuffer) {} else if (ArrayBuffer.isView(arg)) {
173896
- if (!(arg.buffer instanceof SharedArrayBuffer)) {
173897
- transfer.push(arg.buffer);
173898
- }
173899
- } else if (TRANSFERABLE_CLASSES.some((t3) => arg instanceof t3)) {
173900
- transfer.push(arg);
173901
- }
173902
- return {
173903
- value: { t: 0, v: arg },
173904
- transfer
173905
- };
173906
- }
173907
- function deserialize(envelope) {
173908
- if (!envelope || typeof envelope !== "object")
173909
- return envelope;
173910
- if (envelope.t === 0) {
173911
- return envelope.v;
173684
+ // cli/build/worker-pool.ts
173685
+ import path47 from "node:path";
173686
+ import fs47 from "node:fs";
173687
+ import { Worker } from "node:worker_threads";
173688
+ var getWorkerEntrypointPath = () => {
173689
+ const tsPath = path47.join(import.meta.dir, "build-worker-entrypoint.ts");
173690
+ if (fs47.existsSync(tsPath)) {
173691
+ return tsPath;
173912
173692
  }
173913
- if (envelope.t === 1) {
173914
- const Cls = classRegistry.get(envelope.c);
173915
- if (Cls) {
173916
- return Cls[toDeserialized](envelope.v);
173917
- }
173918
- throw new Error(`Unknown TypeID ${envelope.c}. Did you forget to import the class?`);
173693
+ const jsBundledPath = path47.join(import.meta.dir, "build", "build-worker-entrypoint.js");
173694
+ if (fs47.existsSync(jsBundledPath)) {
173695
+ return jsBundledPath;
173919
173696
  }
173920
- return envelope;
173921
- }
173922
-
173923
- // node_modules/multithreading/src/lib/pool.js
173924
- var newWorker;
173925
- function workerOverride(fn3) {
173926
- newWorker = fn3;
173927
- }
173697
+ return path47.join(import.meta.dir, "build-worker-entrypoint.js");
173698
+ };
173928
173699
 
173929
173700
  class WorkerPool {
173930
- constructor(maxThreads) {
173931
- this.workers = [];
173932
- this.taskIdCounter = 0;
173933
- this.maxThreads = maxThreads || navigator.hardwareConcurrency || 4;
173934
- }
173935
- createWorker() {
173936
- const worker = newWorker();
173937
- worker._loadedFnIds = new Set;
173938
- worker._pending = new Map;
173939
- worker.onmessage = (e4) => {
173940
- const { taskId, type } = e4.data;
173941
- const p4 = worker._pending.get(taskId);
173942
- if (p4) {
173943
- if (type === "ERROR") {
173944
- const err = new Error(e4.data.error);
173945
- if (e4.data.stack)
173946
- err.stack = e4.data.stack;
173947
- p4.reject(err);
173948
- } else {
173949
- p4.resolve(deserialize(e4.data.result));
173950
- }
173951
- worker._pending.delete(taskId);
173952
- }
173953
- };
173954
- worker.onerror = (e4) => {
173955
- e4.preventDefault();
173956
- const err = new Error(`Worker Crashed: ${e4.message}`);
173957
- for (const p4 of worker._pending.values())
173958
- p4.reject(err);
173959
- worker._pending.clear();
173960
- this.removeWorker(worker);
173961
- };
173962
- this.workers.push(worker);
173963
- return worker;
173964
- }
173965
- removeWorker(worker) {
173966
- this.workers = this.workers.filter((w4) => w4 !== worker);
173967
- worker.terminate();
173968
- }
173969
- async executeTask(worker, task) {
173970
- const { fnId, code, args } = task;
173971
- const taskId = this.taskIdCounter++;
173972
- const { promise, resolve: resolve12, reject } = Promise.withResolvers();
173973
- worker._pending.set(taskId, { resolve: resolve12, reject });
173974
- const serializedArgs = args.map(serialize);
173975
- const values = serializedArgs.map((r4) => r4.value);
173976
- const transferList = [
173977
- ...new Set(serializedArgs.flatMap((r4) => r4.transfer))
173978
- ];
173979
- const hasCode = worker._loadedFnIds.has(fnId);
173980
- if (!hasCode) {
173981
- worker._loadedFnIds.add(fnId);
173982
- }
173983
- worker.postMessage({
173984
- type: "RUN",
173985
- taskId,
173986
- fnId,
173987
- code: hasCode ? undefined : code,
173988
- args: values
173989
- }, { transfer: transferList });
173990
- return await promise;
173991
- }
173992
- async submit(task) {
173993
- let bestCandidate;
173994
- let bestCandidateLoad = Infinity;
173995
- let bestCandidateScore = 4;
173996
- for (let i3 = 0;i3 < this.workers.length; i3++) {
173997
- const w4 = this.workers[i3];
173998
- const load3 = w4._pending.size;
173999
- const hasAffinity = w4._loadedFnIds.has(task.fnId);
174000
- if (load3 === 0 && hasAffinity) {
174001
- return await this.executeTask(w4, task);
174002
- }
174003
- let score = 4;
174004
- if (load3 === 0)
174005
- score = 1;
174006
- else if (hasAffinity)
174007
- score = 2;
174008
- else
174009
- score = 3;
174010
- if (score < bestCandidateScore || score === bestCandidateScore && load3 < bestCandidateLoad) {
174011
- bestCandidate = w4;
174012
- bestCandidateScore = score;
174013
- bestCandidateLoad = load3;
174014
- }
174015
- }
174016
- if (bestCandidateScore >= 2 && this.workers.length < this.maxThreads) {
174017
- return await this.executeTask(this.createWorker(), task);
174018
- }
174019
- if (bestCandidate) {
174020
- return await this.executeTask(bestCandidate, task);
174021
- }
174022
- return await this.executeTask(this.createWorker(), task);
174023
- }
174024
- terminate() {
174025
- for (const w4 of this.workers)
174026
- w4.terminate();
174027
- this.workers = [];
174028
- }
174029
- }
174030
-
174031
- // node_modules/multithreading/src/lib/caller_location.js
174032
- function getCallerLocation() {
174033
- const internalFiles = [
174034
- "caller_location.ts",
174035
- "caller_location.js",
174036
- "lib.ts",
174037
- "lib.js",
174038
- "internal",
174039
- "node_modules",
174040
- "native"
174041
- ];
174042
- const stack = new Error().stack;
174043
- const lines = stack.split(`
174044
- `);
174045
- let callerLine;
174046
- for (let i3 = 0;i3 < lines.length; i3++) {
174047
- const line2 = lines[i3];
174048
- if (line2.trim() === "Error")
174049
- continue;
174050
- const isInternal = internalFiles.some((file) => line2.includes(file));
174051
- if (!isInternal) {
174052
- callerLine = line2;
174053
- break;
174054
- }
174055
- }
174056
- if (!callerLine) {
174057
- throw new Error("Could not find caller line in stack trace");
174058
- }
174059
- const matchParen = callerLine.match(/\((.*)\)/);
174060
- let pathWithCoords = matchParen ? matchParen[1] : callerLine.replace(/^\s*at\s+/, "").trim();
174061
- pathWithCoords = pathWithCoords.replace(/^async\s+/, "");
174062
- const coordMatch = pathWithCoords.match(/:(\d+):(\d+)$/);
174063
- if (!coordMatch) {
174064
- throw new Error(`Could not parse coordinates from: ${callerLine}`);
174065
- }
174066
- const filePath = pathWithCoords.replace(/:\d+:\d+$/, "");
174067
- return {
174068
- filePath,
174069
- line: Number(coordMatch[1]) - 1,
174070
- column: Number(coordMatch[2]) - 1
174071
- };
174072
- }
174073
-
174074
- // node_modules/multithreading/src/lib/patch_import.js
174075
- function patchDynamicImports(code, callerLocation) {
174076
- let normalizedCaller = callerLocation;
174077
- if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(normalizedCaller)) {
174078
- normalizedCaller = normalizedCaller.replace(/\\/g, "/");
174079
- if (!normalizedCaller.startsWith("/")) {
174080
- normalizedCaller = "/" + normalizedCaller;
174081
- }
174082
- normalizedCaller = "file://" + normalizedCaller;
174083
- }
174084
- const importStartPattern = /\bimport\s*\(/g;
174085
- const replacements = [];
174086
- let match;
174087
- while ((match = importStartPattern.exec(code)) !== null) {
174088
- const importStartIndex = match.index;
174089
- const openParenIndex = importStartIndex + match[0].length - 1;
174090
- const argBounds = findArgumentBounds(code, openParenIndex + 1);
174091
- if (argBounds) {
174092
- const { start, end } = argBounds;
174093
- const originalArgument = code.slice(start, end);
174094
- const isStringLiteral2 = /^["'`]/.test(originalArgument);
174095
- let shouldApplyFallback = true;
174096
- if (isStringLiteral2) {
174097
- const content = originalArgument.slice(1, -1);
174098
- const isExplicitPath = /^\.{0,2}[/\\]|^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(content);
174099
- if (!isExplicitPath) {
174100
- shouldApplyFallback = false;
174101
- try {
174102
- const resolvedUrl = import.meta.resolve(content);
174103
- replacements.push({
174104
- start,
174105
- end,
174106
- text: JSON.stringify(resolvedUrl)
174107
- });
174108
- } catch (e4) {}
174109
- }
174110
- }
174111
- if (shouldApplyFallback) {
174112
- let base = `new URL(${JSON.stringify(normalizedCaller)}, import.meta.url).href`;
174113
- if (isStringLiteral2) {
174114
- const content = originalArgument.slice(1, -1);
174115
- if (content.startsWith("/") || content.startsWith("\\")) {
174116
- base = `(typeof location !== "undefined" ? location.origin : import.meta.url)`;
174117
- }
174118
- }
174119
- const newArgument = `new URL(${originalArgument}, ${base}).href`;
174120
- replacements.push({
174121
- start,
174122
- end,
174123
- text: newArgument
174124
- });
174125
- }
174126
- }
174127
- }
174128
- replacements.sort((a3, b3) => b3.start - a3.start);
174129
- let modifiedCode = code;
174130
- for (let i3 = 0;i3 < replacements.length; i3++) {
174131
- const rep = replacements[i3];
174132
- const before = modifiedCode.slice(0, rep.start);
174133
- const after = modifiedCode.slice(rep.end);
174134
- modifiedCode = before + rep.text + after;
174135
- }
174136
- return modifiedCode;
174137
- }
174138
- function findArgumentBounds(code, startIndex) {
174139
- let index = startIndex;
174140
- const len = code.length;
174141
- let inString = null;
174142
- let inComment = null;
174143
- let parenDepth = 0;
174144
- let argStart = -1;
174145
- let argEnd = -1;
174146
- for (;index < len; index++) {
174147
- const char = code[index];
174148
- const nextChar = code[index + 1];
174149
- if (inString) {
174150
- if (char === "\\" && index + 1 < len) {
174151
- index++;
174152
- argEnd = index + 1;
174153
- continue;
174154
- }
174155
- if (char === inString)
174156
- inString = null;
174157
- if (argStart === -1)
174158
- argStart = index;
174159
- argEnd = index + 1;
174160
- continue;
174161
- }
174162
- if (inComment) {
174163
- if (inComment === "//" && char === `
174164
- `)
174165
- inComment = null;
174166
- else if (inComment === "/*" && char === "*" && nextChar === "/") {
174167
- inComment = null;
174168
- index++;
174169
- }
174170
- continue;
174171
- }
174172
- if (char === '"' || char === "'" || char === "`") {
174173
- inString = char;
174174
- if (argStart === -1)
174175
- argStart = index;
174176
- argEnd = index + 1;
174177
- continue;
174178
- }
174179
- if (char === "/" && nextChar === "/") {
174180
- inComment = "//";
174181
- index++;
174182
- continue;
174183
- }
174184
- if (char === "/" && nextChar === "*") {
174185
- inComment = "/*";
174186
- index++;
174187
- continue;
174188
- }
174189
- if (char === "(") {
174190
- parenDepth++;
174191
- if (argStart === -1)
174192
- argStart = index;
174193
- argEnd = index + 1;
174194
- } else if (char === ")") {
174195
- if (parenDepth === 0) {
174196
- if (argStart === -1)
174197
- return null;
174198
- return { start: argStart, end: argEnd };
174199
- }
174200
- parenDepth--;
174201
- if (argStart === -1)
174202
- argStart = index;
174203
- argEnd = index + 1;
174204
- } else if (char === ",") {
174205
- if (parenDepth === 0) {
174206
- if (argStart === -1)
174207
- return null;
174208
- return { start: argStart, end: argEnd };
174209
- }
174210
- if (argStart === -1)
174211
- argStart = index;
174212
- argEnd = index + 1;
174213
- } else {
174214
- if (!/\s/.test(char)) {
174215
- if (argStart === -1)
174216
- argStart = index;
174217
- argEnd = index + 1;
174218
- }
174219
- }
174220
- }
174221
- return null;
174222
- }
174223
-
174224
- // node_modules/multithreading/src/lib/check_move_args.js
174225
- function checkMoveArgs(args) {
174226
- for (const arg of args) {
174227
- const isRawSAB = arg instanceof SharedArrayBuffer;
174228
- const isViewSAB = ArrayBuffer.isView(arg) && arg.buffer instanceof SharedArrayBuffer;
174229
- const isThreadSafe = arg instanceof Mutex || arg instanceof Condvar || arg instanceof RwLock || arg instanceof Sender || arg instanceof Receiver || arg instanceof Semaphore || arg instanceof Barrier;
174230
- const isLibrarySAB = !isThreadSafe && typeof arg[toSerialized] !== "undefined";
174231
- if (isRawSAB || isViewSAB || isLibrarySAB) {
174232
- console.warn("Warning: You are passing a SharedArrayBuffer to a worker without locking. Please wrap this data in a Mutex() or RwLock() to prevent race conditions.");
174233
- }
174234
- }
174235
- }
174236
-
174237
- // node_modules/multithreading/src/lib/sync/mutex.js
174238
- var __classPrivateFieldSet = function(receiver, state, value, kind, f2) {
174239
- if (kind === "m")
174240
- throw new TypeError("Private method is not writable");
174241
- if (kind === "a" && !f2)
174242
- throw new TypeError("Private accessor was defined without a setter");
174243
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174244
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
174245
- return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
174246
- };
174247
- var __classPrivateFieldGet = function(receiver, state, kind, f2) {
174248
- if (kind === "a" && !f2)
174249
- throw new TypeError("Private accessor was defined without a getter");
174250
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174251
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
174252
- return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
174253
- };
174254
- var _MutexGuard_data;
174255
- var _MutexGuard_mutex;
174256
- var _MutexGuard_released;
174257
- var _Mutex_instances;
174258
- var _a3;
174259
- var _Mutex_data;
174260
- var _Mutex_lockState;
174261
- var _Mutex_controller;
174262
- var _Mutex_tryLock;
174263
- var _Mutex_unlock;
174264
- var _Mutex_performBlockingLock;
174265
- var _Mutex_performAsyncLock;
174266
- var INTERNAL_MUTEX_CONTROLLER = Symbol("Thread.InternalMutexController");
174267
- var IDX_LOCK_STATE = 0;
174268
- var LOCKED = 1;
174269
- var UNLOCKED = 0;
174270
-
174271
- class MutexGuard {
174272
- constructor(data, mutex) {
174273
- _MutexGuard_data.set(this, undefined);
174274
- _MutexGuard_mutex.set(this, undefined);
174275
- _MutexGuard_released.set(this, false);
174276
- __classPrivateFieldSet(this, _MutexGuard_data, data, "f");
174277
- __classPrivateFieldSet(this, _MutexGuard_mutex, mutex, "f");
174278
- }
174279
- get [(_MutexGuard_data = new WeakMap, _MutexGuard_mutex = new WeakMap, _MutexGuard_released = new WeakMap, INTERNAL_MUTEX_CONTROLLER)]() {
174280
- return __classPrivateFieldGet(this, _MutexGuard_mutex, "f");
174281
- }
174282
- get value() {
174283
- if (__classPrivateFieldGet(this, _MutexGuard_released, "f"))
174284
- throw new Error("Cannot access released mutex data");
174285
- return __classPrivateFieldGet(this, _MutexGuard_data, "f");
174286
- }
174287
- [Symbol.dispose]() {
174288
- if (!__classPrivateFieldGet(this, _MutexGuard_released, "f")) {
174289
- __classPrivateFieldSet(this, _MutexGuard_released, true, "f");
174290
- __classPrivateFieldGet(this, _MutexGuard_mutex, "f").unlock();
174291
- }
174292
- }
174293
- dispose() {
174294
- this[Symbol.dispose]();
174295
- }
174296
- }
174297
-
174298
- class Mutex extends Serializable {
174299
- constructor(data, _lockBuffer) {
174300
- super();
174301
- _Mutex_instances.add(this);
174302
- _Mutex_data.set(this, undefined);
174303
- _Mutex_lockState.set(this, undefined);
174304
- _Mutex_controller.set(this, undefined);
174305
- __classPrivateFieldSet(this, _Mutex_data, data, "f");
174306
- __classPrivateFieldSet(this, _Mutex_lockState, _lockBuffer ? new Int32Array(_lockBuffer) : new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)), "f");
174307
- __classPrivateFieldSet(this, _Mutex_controller, {
174308
- unlock: () => __classPrivateFieldGet(this, _Mutex_instances, "m", _Mutex_unlock).call(this),
174309
- blockingLock: () => __classPrivateFieldGet(this, _Mutex_instances, "m", _Mutex_performBlockingLock).call(this),
174310
- lock: () => __classPrivateFieldGet(this, _Mutex_instances, "m", _Mutex_performAsyncLock).call(this)
174311
- }, "f");
174312
- }
174313
- blockingLock() {
174314
- __classPrivateFieldGet(this, _Mutex_instances, "m", _Mutex_performBlockingLock).call(this);
174315
- return new MutexGuard(__classPrivateFieldGet(this, _Mutex_data, "f"), __classPrivateFieldGet(this, _Mutex_controller, "f"));
174316
- }
174317
- async lock() {
174318
- await __classPrivateFieldGet(this, _Mutex_instances, "m", _Mutex_performAsyncLock).call(this);
174319
- return new MutexGuard(__classPrivateFieldGet(this, _Mutex_data, "f"), __classPrivateFieldGet(this, _Mutex_controller, "f"));
174320
- }
174321
- [(_Mutex_data = new WeakMap, _Mutex_lockState = new WeakMap, _Mutex_controller = new WeakMap, _Mutex_instances = new WeakSet, _Mutex_tryLock = function _Mutex_tryLock() {
174322
- return Atomics.compareExchange(__classPrivateFieldGet(this, _Mutex_lockState, "f"), IDX_LOCK_STATE, UNLOCKED, LOCKED) === UNLOCKED;
174323
- }, _Mutex_unlock = function _Mutex_unlock() {
174324
- if (Atomics.compareExchange(__classPrivateFieldGet(this, _Mutex_lockState, "f"), IDX_LOCK_STATE, LOCKED, UNLOCKED) !== LOCKED) {
174325
- throw new Error("Mutex was not locked or locked by another thread");
174326
- }
174327
- Atomics.notify(__classPrivateFieldGet(this, _Mutex_lockState, "f"), IDX_LOCK_STATE, 1);
174328
- }, _Mutex_performBlockingLock = function _Mutex_performBlockingLock() {
174329
- while (true) {
174330
- if (__classPrivateFieldGet(this, _Mutex_instances, "m", _Mutex_tryLock).call(this))
174331
- return;
174332
- Atomics.wait(__classPrivateFieldGet(this, _Mutex_lockState, "f"), IDX_LOCK_STATE, LOCKED);
174333
- }
174334
- }, _Mutex_performAsyncLock = async function _Mutex_performAsyncLock() {
174335
- while (true) {
174336
- if (__classPrivateFieldGet(this, _Mutex_instances, "m", _Mutex_tryLock).call(this))
174337
- return;
174338
- const result = Atomics.waitAsync(__classPrivateFieldGet(this, _Mutex_lockState, "f"), IDX_LOCK_STATE, LOCKED);
174339
- if (result.async) {
174340
- await result.value;
174341
- }
174342
- }
174343
- }, toSerialized)]() {
174344
- let serializedData;
174345
- let transfer = [];
174346
- if (__classPrivateFieldGet(this, _Mutex_data, "f") !== undefined) {
174347
- const result = serialize(__classPrivateFieldGet(this, _Mutex_data, "f"));
174348
- serializedData = result.value;
174349
- transfer = result.transfer;
174350
- }
174351
- return {
174352
- value: {
174353
- lockBuffer: __classPrivateFieldGet(this, _Mutex_lockState, "f").buffer,
174354
- data: serializedData
174355
- },
174356
- transfer
174357
- };
174358
- }
174359
- static [toDeserialized](obj) {
174360
- const data = obj.data !== undefined ? deserialize(obj.data) : undefined;
174361
- return new _a3(data, obj.lockBuffer);
174362
- }
174363
- }
174364
- _a3 = Mutex;
174365
- (() => {
174366
- register2(0, _a3);
174367
- })();
174368
-
174369
- // node_modules/multithreading/src/lib/sync/condvar.js
174370
- var __classPrivateFieldSet2 = function(receiver, state, value, kind, f2) {
174371
- if (kind === "m")
174372
- throw new TypeError("Private method is not writable");
174373
- if (kind === "a" && !f2)
174374
- throw new TypeError("Private accessor was defined without a setter");
174375
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174376
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
174377
- return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
174378
- };
174379
- var __classPrivateFieldGet2 = function(receiver, state, kind, f2) {
174380
- if (kind === "a" && !f2)
174381
- throw new TypeError("Private accessor was defined without a getter");
174382
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174383
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
174384
- return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
174385
- };
174386
- var _a4;
174387
- var _Condvar_atomic;
174388
- var IDX_NOTIFY_SEQ = 0;
174389
- var SEQ_INCREMENT = 1;
174390
- var NOTIFY_ONE = 1;
174391
- var NOTIFY_ALL = Infinity;
174392
-
174393
- class Condvar extends Serializable {
174394
- constructor(_buffer) {
174395
- super();
174396
- _Condvar_atomic.set(this, undefined);
174397
- __classPrivateFieldSet2(this, _Condvar_atomic, new Int32Array(_buffer ?? new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)), "f");
174398
- }
174399
- blockingWait(guard) {
174400
- const controller = guard[INTERNAL_MUTEX_CONTROLLER];
174401
- const seq = Atomics.load(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ);
174402
- controller.unlock();
174403
- Atomics.wait(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ, seq);
174404
- controller.blockingLock();
174405
- }
174406
- async wait(guard) {
174407
- const controller = guard[INTERNAL_MUTEX_CONTROLLER];
174408
- const seq = Atomics.load(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ);
174409
- controller.unlock();
174410
- const result = Atomics.waitAsync(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ, seq);
174411
- if (result.async) {
174412
- await result.value;
174413
- }
174414
- await controller.lock();
174415
- }
174416
- notifyOne() {
174417
- Atomics.add(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ, SEQ_INCREMENT);
174418
- Atomics.notify(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ, NOTIFY_ONE);
174419
- }
174420
- notifyAll() {
174421
- Atomics.add(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ, SEQ_INCREMENT);
174422
- Atomics.notify(__classPrivateFieldGet2(this, _Condvar_atomic, "f"), IDX_NOTIFY_SEQ, NOTIFY_ALL);
174423
- }
174424
- [(_Condvar_atomic = new WeakMap, toSerialized)]() {
174425
- return {
174426
- value: __classPrivateFieldGet2(this, _Condvar_atomic, "f").buffer,
174427
- transfer: []
174428
- };
174429
- }
174430
- static [toDeserialized](obj) {
174431
- return new _a4(obj);
174432
- }
174433
- }
174434
- _a4 = Condvar;
174435
- (() => {
174436
- register2(1, _a4);
174437
- })();
174438
- // node_modules/multithreading/src/lib/sync/rwlock.js
174439
- var __classPrivateFieldSet3 = function(receiver, state, value, kind, f2) {
174440
- if (kind === "m")
174441
- throw new TypeError("Private method is not writable");
174442
- if (kind === "a" && !f2)
174443
- throw new TypeError("Private accessor was defined without a setter");
174444
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174445
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
174446
- return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
174447
- };
174448
- var __classPrivateFieldGet3 = function(receiver, state, kind, f2) {
174449
- if (kind === "a" && !f2)
174450
- throw new TypeError("Private accessor was defined without a getter");
174451
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174452
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
174453
- return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
174454
- };
174455
- var _RwLockReadGuard_data;
174456
- var _RwLockReadGuard_controller;
174457
- var _RwLockReadGuard_released;
174458
- var _RwLockWriteGuard_data;
174459
- var _RwLockWriteGuard_controller;
174460
- var _RwLockWriteGuard_released;
174461
- var _RwLock_instances;
174462
- var _a5;
174463
- var _RwLock_data;
174464
- var _RwLock_lockState;
174465
- var _RwLock_readController;
174466
- var _RwLock_writeController;
174467
- var _RwLock_unlockRead;
174468
- var _RwLock_unlockWrite;
174469
- var INTERNAL_RWLOCK_CONTROLLER = Symbol("Thread.InternalRwLockController");
174470
- var IDX_LOCK_STATE2 = 0;
174471
- var UNLOCKED2 = 0;
174472
- var WRITE_LOCKED = -1;
174473
- var READ_ONE = 1;
174474
-
174475
- class RwLockReadGuard {
174476
- constructor(data, controller) {
174477
- _RwLockReadGuard_data.set(this, undefined);
174478
- _RwLockReadGuard_controller.set(this, undefined);
174479
- _RwLockReadGuard_released.set(this, false);
174480
- __classPrivateFieldSet3(this, _RwLockReadGuard_data, data, "f");
174481
- __classPrivateFieldSet3(this, _RwLockReadGuard_controller, controller, "f");
174482
- }
174483
- get [(_RwLockReadGuard_data = new WeakMap, _RwLockReadGuard_controller = new WeakMap, _RwLockReadGuard_released = new WeakMap, INTERNAL_RWLOCK_CONTROLLER)]() {
174484
- return __classPrivateFieldGet3(this, _RwLockReadGuard_controller, "f");
174485
- }
174486
- get value() {
174487
- if (__classPrivateFieldGet3(this, _RwLockReadGuard_released, "f"))
174488
- throw new Error("Cannot access released lock data");
174489
- return __classPrivateFieldGet3(this, _RwLockReadGuard_data, "f");
174490
- }
174491
- [Symbol.dispose]() {
174492
- if (!__classPrivateFieldGet3(this, _RwLockReadGuard_released, "f")) {
174493
- __classPrivateFieldSet3(this, _RwLockReadGuard_released, true, "f");
174494
- __classPrivateFieldGet3(this, _RwLockReadGuard_controller, "f").unlock();
174495
- }
174496
- }
174497
- dispose() {
174498
- this[Symbol.dispose]();
174499
- }
174500
- }
174501
-
174502
- class RwLockWriteGuard {
174503
- constructor(data, controller) {
174504
- _RwLockWriteGuard_data.set(this, undefined);
174505
- _RwLockWriteGuard_controller.set(this, undefined);
174506
- _RwLockWriteGuard_released.set(this, false);
174507
- __classPrivateFieldSet3(this, _RwLockWriteGuard_data, data, "f");
174508
- __classPrivateFieldSet3(this, _RwLockWriteGuard_controller, controller, "f");
174509
- }
174510
- get [(_RwLockWriteGuard_data = new WeakMap, _RwLockWriteGuard_controller = new WeakMap, _RwLockWriteGuard_released = new WeakMap, INTERNAL_RWLOCK_CONTROLLER)]() {
174511
- return __classPrivateFieldGet3(this, _RwLockWriteGuard_controller, "f");
174512
- }
174513
- get value() {
174514
- if (__classPrivateFieldGet3(this, _RwLockWriteGuard_released, "f"))
174515
- throw new Error("Cannot access released lock data");
174516
- return __classPrivateFieldGet3(this, _RwLockWriteGuard_data, "f");
174517
- }
174518
- [Symbol.dispose]() {
174519
- if (!__classPrivateFieldGet3(this, _RwLockWriteGuard_released, "f")) {
174520
- __classPrivateFieldSet3(this, _RwLockWriteGuard_released, true, "f");
174521
- __classPrivateFieldGet3(this, _RwLockWriteGuard_controller, "f").unlock();
174522
- }
174523
- }
174524
- dispose() {
174525
- this[Symbol.dispose]();
174526
- }
174527
- }
174528
-
174529
- class RwLock extends Serializable {
174530
- constructor(data, _stateBuffer) {
174531
- super();
174532
- _RwLock_instances.add(this);
174533
- _RwLock_data.set(this, undefined);
174534
- _RwLock_lockState.set(this, undefined);
174535
- _RwLock_readController.set(this, undefined);
174536
- _RwLock_writeController.set(this, undefined);
174537
- __classPrivateFieldSet3(this, _RwLock_data, data, "f");
174538
- __classPrivateFieldSet3(this, _RwLock_lockState, _stateBuffer ? new Int32Array(_stateBuffer) : new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)), "f");
174539
- __classPrivateFieldSet3(this, _RwLock_readController, { unlock: () => __classPrivateFieldGet3(this, _RwLock_instances, "m", _RwLock_unlockRead).call(this) }, "f");
174540
- __classPrivateFieldSet3(this, _RwLock_writeController, { unlock: () => __classPrivateFieldGet3(this, _RwLock_instances, "m", _RwLock_unlockWrite).call(this) }, "f");
174541
- }
174542
- blockingRead() {
174543
- while (true) {
174544
- const current2 = Atomics.load(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2);
174545
- if (current2 === WRITE_LOCKED) {
174546
- Atomics.wait(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, WRITE_LOCKED);
174547
- continue;
174548
- }
174549
- if (Atomics.compareExchange(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, current2, current2 + READ_ONE) === current2) {
174550
- return new RwLockReadGuard(__classPrivateFieldGet3(this, _RwLock_data, "f"), __classPrivateFieldGet3(this, _RwLock_readController, "f"));
174551
- }
174552
- }
174553
- }
174554
- async read() {
174555
- while (true) {
174556
- const current2 = Atomics.load(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2);
174557
- if (current2 === WRITE_LOCKED) {
174558
- const res2 = Atomics.waitAsync(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, WRITE_LOCKED);
174559
- if (res2.async) {
174560
- await res2.value;
174561
- }
174562
- continue;
174563
- }
174564
- if (Atomics.compareExchange(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, current2, current2 + READ_ONE) === current2) {
174565
- return new RwLockReadGuard(__classPrivateFieldGet3(this, _RwLock_data, "f"), __classPrivateFieldGet3(this, _RwLock_readController, "f"));
174566
- }
174567
- }
174568
- }
174569
- blockingWrite() {
174570
- while (true) {
174571
- const current2 = Atomics.load(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2);
174572
- if (current2 !== UNLOCKED2) {
174573
- Atomics.wait(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, current2);
174574
- continue;
174575
- }
174576
- if (Atomics.compareExchange(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, UNLOCKED2, WRITE_LOCKED) === UNLOCKED2) {
174577
- return new RwLockWriteGuard(__classPrivateFieldGet3(this, _RwLock_data, "f"), __classPrivateFieldGet3(this, _RwLock_writeController, "f"));
174578
- }
174579
- }
174580
- }
174581
- async write() {
174582
- while (true) {
174583
- const current2 = Atomics.load(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2);
174584
- if (current2 !== UNLOCKED2) {
174585
- const res2 = Atomics.waitAsync(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, current2);
174586
- if (res2.async) {
174587
- await res2.value;
174588
- }
174589
- continue;
174590
- }
174591
- if (Atomics.compareExchange(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, UNLOCKED2, WRITE_LOCKED) === UNLOCKED2) {
174592
- return new RwLockWriteGuard(__classPrivateFieldGet3(this, _RwLock_data, "f"), __classPrivateFieldGet3(this, _RwLock_writeController, "f"));
174593
- }
174594
- }
174595
- }
174596
- [(_RwLock_data = new WeakMap, _RwLock_lockState = new WeakMap, _RwLock_readController = new WeakMap, _RwLock_writeController = new WeakMap, _RwLock_instances = new WeakSet, _RwLock_unlockRead = function _RwLock_unlockRead() {
174597
- const prevState = Atomics.sub(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, READ_ONE);
174598
- if (prevState === READ_ONE) {
174599
- Atomics.notify(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, 1);
174600
- }
174601
- }, _RwLock_unlockWrite = function _RwLock_unlockWrite() {
174602
- if (Atomics.compareExchange(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, WRITE_LOCKED, UNLOCKED2) !== WRITE_LOCKED) {
174603
- throw new Error("RwLock was not write-locked or locked by another thread");
174604
- }
174605
- Atomics.notify(__classPrivateFieldGet3(this, _RwLock_lockState, "f"), IDX_LOCK_STATE2, Infinity);
174606
- }, toSerialized)]() {
174607
- let serializedData;
174608
- let transfer = [];
174609
- if (__classPrivateFieldGet3(this, _RwLock_data, "f") !== undefined) {
174610
- const result = serialize(__classPrivateFieldGet3(this, _RwLock_data, "f"));
174611
- serializedData = result.value;
174612
- transfer = result.transfer;
174613
- }
174614
- return {
174615
- value: {
174616
- stateBuffer: __classPrivateFieldGet3(this, _RwLock_lockState, "f").buffer,
174617
- data: serializedData
174618
- },
174619
- transfer
174620
- };
174621
- }
174622
- static [toDeserialized](obj) {
174623
- const data = obj.data !== undefined ? deserialize(obj.data) : undefined;
174624
- return new _a5(data, obj.stateBuffer);
174625
- }
174626
- }
174627
- _a5 = RwLock;
174628
- (() => {
174629
- register2(2, _a5);
174630
- })();
174631
- // node_modules/multithreading/src/lib/sync/semaphore.js
174632
- var __classPrivateFieldSet4 = function(receiver, state, value, kind, f2) {
174633
- if (kind === "m")
174634
- throw new TypeError("Private method is not writable");
174635
- if (kind === "a" && !f2)
174636
- throw new TypeError("Private accessor was defined without a setter");
174637
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174638
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
174639
- return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
174640
- };
174641
- var __classPrivateFieldGet4 = function(receiver, state, kind, f2) {
174642
- if (kind === "a" && !f2)
174643
- throw new TypeError("Private accessor was defined without a getter");
174644
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
174645
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
174646
- return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
174647
- };
174648
- var _SemaphoreGuard_amount;
174649
- var _SemaphoreGuard_controller;
174650
- var _SemaphoreGuard_released;
174651
- var _Semaphore_instances;
174652
- var _a6;
174653
- var _Semaphore_state;
174654
- var _Semaphore_controller;
174655
- var _Semaphore_release;
174656
- var INTERNAL_SEMAPHORE_CONTROLLER = Symbol("Thread.InternalSemaphoreController");
174657
- var IDX_PERMITS = 0;
174658
- var IDX_WAITERS = 1;
174659
- var META_SIZE = 2;
174660
-
174661
- class SemaphoreGuard {
174662
- constructor(amount, controller) {
174663
- _SemaphoreGuard_amount.set(this, undefined);
174664
- _SemaphoreGuard_controller.set(this, undefined);
174665
- _SemaphoreGuard_released.set(this, false);
174666
- __classPrivateFieldSet4(this, _SemaphoreGuard_amount, amount, "f");
174667
- __classPrivateFieldSet4(this, _SemaphoreGuard_controller, controller, "f");
174668
- }
174669
- get [(_SemaphoreGuard_amount = new WeakMap, _SemaphoreGuard_controller = new WeakMap, _SemaphoreGuard_released = new WeakMap, INTERNAL_SEMAPHORE_CONTROLLER)]() {
174670
- return __classPrivateFieldGet4(this, _SemaphoreGuard_controller, "f");
174671
- }
174672
- get amount() {
174673
- return __classPrivateFieldGet4(this, _SemaphoreGuard_amount, "f");
174674
- }
174675
- [Symbol.dispose]() {
174676
- if (!__classPrivateFieldGet4(this, _SemaphoreGuard_released, "f")) {
174677
- __classPrivateFieldSet4(this, _SemaphoreGuard_released, true, "f");
174678
- __classPrivateFieldGet4(this, _SemaphoreGuard_controller, "f").release(__classPrivateFieldGet4(this, _SemaphoreGuard_amount, "f"));
174679
- }
174680
- }
174681
- dispose() {
174682
- this[Symbol.dispose]();
174683
- }
174684
- }
174685
-
174686
- class Semaphore extends Serializable {
174687
- constructor(initialCount, _buffer) {
174688
- super();
174689
- _Semaphore_instances.add(this);
174690
- _Semaphore_state.set(this, undefined);
174691
- _Semaphore_controller.set(this, undefined);
174692
- if (_buffer) {
174693
- __classPrivateFieldSet4(this, _Semaphore_state, new Int32Array(_buffer), "f");
174694
- } else {
174695
- __classPrivateFieldSet4(this, _Semaphore_state, new Int32Array(new SharedArrayBuffer(META_SIZE * Int32Array.BYTES_PER_ELEMENT)), "f");
174696
- __classPrivateFieldGet4(this, _Semaphore_state, "f")[IDX_PERMITS] = initialCount;
174697
- __classPrivateFieldGet4(this, _Semaphore_state, "f")[IDX_WAITERS] = 0;
174698
- }
174699
- __classPrivateFieldSet4(this, _Semaphore_controller, {
174700
- release: (amount) => __classPrivateFieldGet4(this, _Semaphore_instances, "m", _Semaphore_release).call(this, amount)
174701
- }, "f");
174702
- }
174703
- get [(_Semaphore_state = new WeakMap, _Semaphore_controller = new WeakMap, _Semaphore_instances = new WeakSet, INTERNAL_SEMAPHORE_CONTROLLER)]() {
174704
- return __classPrivateFieldGet4(this, _Semaphore_controller, "f");
174705
- }
174706
- tryAcquire(amount = 1) {
174707
- const current2 = Atomics.load(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS);
174708
- if (current2 >= amount) {
174709
- const result = Atomics.compareExchange(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS, current2, current2 - amount);
174710
- if (result === current2) {
174711
- return new SemaphoreGuard(amount, __classPrivateFieldGet4(this, _Semaphore_controller, "f"));
174712
- }
174713
- }
174714
- return null;
174715
- }
174716
- blockingAcquire(amount = 1) {
174717
- while (true) {
174718
- const current2 = Atomics.load(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS);
174719
- if (current2 >= amount) {
174720
- const result = Atomics.compareExchange(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS, current2, current2 - amount);
174721
- if (result === current2) {
174722
- return new SemaphoreGuard(amount, __classPrivateFieldGet4(this, _Semaphore_controller, "f"));
174723
- }
174724
- } else {
174725
- Atomics.add(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_WAITERS, 1);
174726
- Atomics.wait(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS, current2);
174727
- Atomics.sub(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_WAITERS, 1);
174728
- }
174729
- }
174730
- }
174731
- async acquire(amount = 1) {
174732
- while (true) {
174733
- const current2 = Atomics.load(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS);
174734
- if (current2 >= amount) {
174735
- const result = Atomics.compareExchange(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS, current2, current2 - amount);
174736
- if (result === current2) {
174737
- return new SemaphoreGuard(amount, __classPrivateFieldGet4(this, _Semaphore_controller, "f"));
174738
- }
174739
- } else {
174740
- Atomics.add(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_WAITERS, 1);
174741
- const res2 = Atomics.waitAsync(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS, current2);
174742
- if (res2.async) {
174743
- await res2.value;
174744
- }
174745
- Atomics.sub(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_WAITERS, 1);
174746
- }
174747
- }
174748
- }
174749
- [(_Semaphore_release = function _Semaphore_release(amount) {
174750
- Atomics.add(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS, amount);
174751
- if (Atomics.load(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_WAITERS) > 0) {
174752
- Atomics.notify(__classPrivateFieldGet4(this, _Semaphore_state, "f"), IDX_PERMITS, amount);
174753
- }
174754
- }, toSerialized)]() {
174755
- return {
174756
- value: __classPrivateFieldGet4(this, _Semaphore_state, "f").buffer,
174757
- transfer: []
174758
- };
174759
- }
174760
- static [toDeserialized](buffer) {
174761
- return new _a6(0, buffer);
174762
- }
174763
- }
174764
- _a6 = Semaphore;
174765
- (() => {
174766
- register2(3, _a6);
174767
- })();
174768
- // node_modules/multithreading/src/lib/json_buffer.js
174769
- var _a7;
174770
- var CONSOLE_VIEW = Symbol("SharedJsonBuffer.consoleView");
174771
- var OFFSET_FREE_PTR = 0;
174772
- var OFFSET_ROOT = 8;
174773
- var HEADER_SIZE = 16;
174774
- var TYPE_NULL = 0;
174775
- var TYPE_TRUE = 1;
174776
- var TYPE_FALSE = 2;
174777
- var TYPE_NUMBER = 3;
174778
- var TYPE_STRING = 4;
174779
- var TYPE_OBJECT = 5;
174780
- var TYPE_ARRAY = 6;
174781
- var TYPE_MOVED = 4294967295;
174782
- function initConsoleHooks() {
174783
- if (typeof console === "undefined")
174784
- return;
174785
- const methods = [
174786
- "log",
174787
- "info",
174788
- "warn",
174789
- "error",
174790
- "dir",
174791
- "table",
174792
- "debug",
174793
- "trace"
174794
- ];
174795
- for (const method of methods) {
174796
- const original = console[method];
174797
- console[method] = function(...args) {
174798
- for (let i3 = 0;i3 < args.length; i3++) {
174799
- const arg = args[i3];
174800
- if (typeof arg === "object" && typeof arg[CONSOLE_VIEW] === "function") {
174801
- try {
174802
- args[i3] = arg[CONSOLE_VIEW]();
174803
- } catch (e4) {
174804
- args[i3] = arg;
174805
- }
174806
- }
174807
- }
174808
- return original.apply(this, args);
174809
- };
174810
- }
174811
- }
174812
-
174813
- class SharedJsonBufferImpl extends Serializable {
174814
- constructor(obj, optionsOrBuffer) {
174815
- super();
174816
- this.textDecoder = new TextDecoder;
174817
- this.textEncoder = new TextEncoder;
174818
- this.stringCache = new Map;
174819
- this.proxyCache = new Map;
174820
- this.propertyHints = new Map;
174821
- this.activeTargets = new Set;
174822
- this.tempRoots = [];
174823
- this.scratchPtr = 0;
174824
- this.scratchCap = 0;
174825
- this.scratchLen = 0;
174826
- this.scratchStart = 0;
174827
- this.objectHandler = {
174828
- get: (target, prop, receiver) => {
174829
- if (typeof prop === "symbol") {
174830
- if (prop === CONSOLE_VIEW) {
174831
- return () => this.toConsoleView(target.__ptr);
174832
- }
174833
- if (prop === toSerialized)
174834
- return () => this[toSerialized]();
174835
- if (prop === Symbol.iterator)
174836
- return;
174837
- return Reflect.get(target, prop, receiver);
174838
- }
174839
- if (prop === "__ptr")
174840
- return target.__ptr;
174841
- if (prop === "toJSON")
174842
- return () => this.toJSON(target.__ptr);
174843
- const ptr = target.__ptr;
174844
- if (ptr === 0)
174845
- return;
174846
- const curr = ptr;
174847
- const type = this.u32[curr >> 2];
174848
- if (type !== TYPE_MOVED) {
174849
- this.scratchLen = this.u32[curr + 8 >> 2];
174850
- this.scratchStart = curr + 12;
174851
- } else {
174852
- this.resolvePtr(ptr);
174853
- }
174854
- const count = this.scratchLen;
174855
- const start = this.scratchStart;
174856
- const hint = this.propertyHints.get(String(prop));
174857
- if (hint !== undefined && hint < count) {
174858
- const entryOffset = start + hint * 12;
174859
- const keyPtr = this.u32[entryOffset >> 2];
174860
- const keyStr = this.readString(keyPtr);
174861
- if (keyStr === prop)
174862
- return this.readSlot(entryOffset + 4);
174863
- }
174864
- for (let i3 = 0;i3 < count; i3++) {
174865
- const entryOffset = start + i3 * 12;
174866
- const keyPtr = this.u32[entryOffset >> 2];
174867
- const key = this.readString(keyPtr);
174868
- if (key === prop) {
174869
- this.propertyHints.set(String(prop), i3);
174870
- return this.readSlot(entryOffset + 4);
174871
- }
174872
- }
174873
- return;
174874
- },
174875
- has: (target, prop) => {
174876
- if (typeof prop === "symbol") {
174877
- if (prop === CONSOLE_VIEW || prop === toSerialized)
174878
- return true;
174879
- return Reflect.has(target, prop);
174880
- }
174881
- if (prop === "__ptr" || prop === "toJSON")
174882
- return true;
174883
- this.resolvePtr(target.__ptr);
174884
- if (target.__ptr === 0)
174885
- return false;
174886
- const propStr = String(prop);
174887
- const count = this.scratchLen;
174888
- const start = this.scratchStart;
174889
- const hint = this.propertyHints.get(propStr);
174890
- if (hint !== undefined && hint < count) {
174891
- const entryOffset = start + hint * 12;
174892
- const keyPtr = this.u32[entryOffset >> 2];
174893
- const keyStr = this.readString(keyPtr);
174894
- if (keyStr === propStr)
174895
- return true;
174896
- }
174897
- for (let i3 = 0;i3 < count; i3++) {
174898
- const entryOffset = start + i3 * 12;
174899
- const keyPtr = this.u32[entryOffset >> 2];
174900
- const key = this.readString(keyPtr);
174901
- if (key === propStr) {
174902
- this.propertyHints.set(propStr, i3);
174903
- return true;
174904
- }
174905
- }
174906
- return false;
174907
- },
174908
- set: (target, prop, value) => {
174909
- if (typeof prop === "symbol")
174910
- return false;
174911
- this.objectSet(target, String(prop), value);
174912
- return true;
174913
- },
174914
- defineProperty: (target, prop, descriptor) => {
174915
- if (typeof prop === "symbol")
174916
- return false;
174917
- if (descriptor.get || descriptor.set) {
174918
- throw new Error("SharedJsonBuffer cannot store accessors (get/set)");
174919
- }
174920
- if ("value" in descriptor) {
174921
- this.objectSet(target, String(prop), descriptor.value);
174922
- }
174923
- return true;
174924
- },
174925
- deleteProperty: (target, prop) => {
174926
- if (typeof prop === "symbol")
174927
- return false;
174928
- return this.objectDelete(target, String(prop));
174929
- },
174930
- ownKeys: (target) => {
174931
- this.resolvePtr(target.__ptr);
174932
- if (target.__ptr === 0)
174933
- return [];
174934
- const keys = [];
174935
- const start = this.scratchStart;
174936
- for (let i3 = 0;i3 < this.scratchLen; i3++) {
174937
- const keyPtr = this.u32[start + i3 * 12 >> 2];
174938
- const key = this.readString(keyPtr);
174939
- this.propertyHints.set(key, i3);
174940
- keys.push(key);
174941
- }
174942
- return keys;
174943
- },
174944
- getOwnPropertyDescriptor: (target, prop) => {
174945
- this.resolvePtr(target.__ptr);
174946
- if (target.__ptr === 0)
174947
- return;
174948
- const count = this.scratchLen;
174949
- const start = this.scratchStart;
174950
- const propStr = String(prop);
174951
- const hint = this.propertyHints.get(propStr);
174952
- if (hint !== undefined && hint < count) {
174953
- const entryOffset = start + hint * 12;
174954
- const keyPtr = this.u32[entryOffset >> 2];
174955
- const keyStr = this.readString(keyPtr);
174956
- if (keyStr === propStr) {
174957
- const val = this.readSlot(entryOffset + 4);
174958
- return {
174959
- enumerable: true,
174960
- configurable: true,
174961
- writable: true,
174962
- value: val
174963
- };
174964
- }
174965
- }
174966
- for (let i3 = 0;i3 < count; i3++) {
174967
- const entryOffset = start + i3 * 12;
174968
- const keyPtr = this.u32[entryOffset >> 2];
174969
- const key = this.readString(keyPtr);
174970
- if (key === propStr) {
174971
- this.propertyHints.set(propStr, i3);
174972
- const val = this.readSlot(entryOffset + 4);
174973
- return {
174974
- enumerable: true,
174975
- configurable: true,
174976
- writable: true,
174977
- value: val
174978
- };
174979
- }
174980
- }
174981
- return;
174982
- }
174983
- };
174984
- this.arrayHandler = {
174985
- get: (target, prop, receiver) => {
174986
- if (prop === CONSOLE_VIEW)
174987
- return () => this.toConsoleView(target.__ptr);
174988
- if (prop === toSerialized)
174989
- return () => this[toSerialized]();
174990
- if (prop === "__ptr")
174991
- return target.__ptr;
174992
- if (prop === "toJSON")
174993
- return () => this.toJSON(target.__ptr);
174994
- if (prop === Symbol.iterator) {
174995
- return () => new ArrayCursor(this, target.__ptr);
174996
- }
174997
- this.resolvePtr(target.__ptr);
174998
- if (target.__ptr === 0)
174999
- return;
175000
- if (prop === "length")
175001
- return this.scratchLen;
175002
- if (prop === "push") {
175003
- return (...args) => {
175004
- this.arraySpliceImpl(target, this.scratchLen, 0, args);
175005
- return this.scratchLen;
175006
- };
175007
- }
175008
- if (prop === "pop") {
175009
- return () => {
175010
- if (this.scratchLen === 0)
175011
- return;
175012
- return this.arraySpliceImpl(target, this.scratchLen - 1, 1)[0];
175013
- };
175014
- }
175015
- if (prop === "shift") {
175016
- return () => {
175017
- if (this.scratchLen === 0)
175018
- return;
175019
- return this.arraySpliceImpl(target, 0, 1)[0];
175020
- };
175021
- }
175022
- if (prop === "unshift") {
175023
- return (...args) => {
175024
- this.arraySpliceImpl(target, 0, 0, args);
175025
- return this.scratchLen;
175026
- };
175027
- }
175028
- if (prop === "splice") {
175029
- return (start, deleteCount, ...items) => {
175030
- const len = this.scratchLen;
175031
- const actualStart = start < 0 ? len + start : start;
175032
- const maxDel = len - (actualStart < 0 ? 0 : actualStart);
175033
- const actualDel = deleteCount === undefined ? maxDel : Math.min(Math.max(deleteCount, 0), maxDel);
175034
- return this.arraySpliceImpl(target, actualStart, actualDel, items);
175035
- };
175036
- }
175037
- if (prop === "flat") {
175038
- return (depth = 1) => {
175039
- const result = [];
175040
- const flatten = (ptr, currentDepth) => {
175041
- this.resolvePtr(ptr);
175042
- const len = this.scratchLen;
175043
- const start = this.scratchStart;
175044
- const captureStart = start;
175045
- for (let i3 = 0;i3 < len; i3++) {
175046
- const offset = captureStart + i3 * 8;
175047
- const type = this.u32[offset >> 2];
175048
- const payload = this.u32[offset + 4 >> 2];
175049
- if (type === TYPE_ARRAY && currentDepth > 0) {
175050
- flatten(payload, currentDepth - 1);
175051
- } else {
175052
- result.push(this.readSlot(offset));
175053
- }
175054
- }
175055
- };
175056
- flatten(target.__ptr, Math.floor(depth));
175057
- return result;
175058
- };
175059
- }
175060
- if (prop === "flatMap") {
175061
- return (callback, thisArg) => {
175062
- const len = this.scratchLen;
175063
- const start = this.scratchStart;
175064
- const result = [];
175065
- for (let i3 = 0;i3 < len; i3++) {
175066
- const val = this.readSlot(start + i3 * 8);
175067
- const mapped = callback.call(thisArg, val, i3, receiver);
175068
- if (Array.isArray(mapped)) {
175069
- result.push(...mapped);
175070
- } else {
175071
- result.push(mapped);
175072
- }
175073
- }
175074
- return result;
175075
- };
175076
- }
175077
- if (typeof prop === "string" && ["sort", "reverse", "fill", "copyWithin"].includes(prop)) {
175078
- return (...args) => {
175079
- const arr = this.toArrayShallow(target.__ptr);
175080
- arr[prop](...args);
175081
- arr.forEach((v4, i3) => this.arraySet(target, i3, v4));
175082
- return receiver;
175083
- };
175084
- }
175085
- if (typeof prop === "string" && prop in Array.prototype) {
175086
- const nativeMethod = Array.prototype[prop];
175087
- if (typeof nativeMethod === "function") {
175088
- return (...args) => {
175089
- const arr = this.toArrayShallow(target.__ptr);
175090
- return nativeMethod.apply(arr, args);
175091
- };
175092
- }
175093
- }
175094
- if (typeof prop === "string") {
175095
- const idx = Number(prop);
175096
- if (!isNaN(idx)) {
175097
- if (idx >= this.scratchLen)
175098
- return;
175099
- return this.readSlot(this.scratchStart + idx * 8);
175100
- }
175101
- }
175102
- return Reflect.get(target, prop, receiver);
175103
- },
175104
- set: (target, prop, value) => {
175105
- if (prop === "length") {
175106
- const newLen = Number(value);
175107
- if (!isNaN(newLen) && newLen >= 0) {
175108
- this.resolvePtr(target.__ptr);
175109
- const currentLen = this.scratchLen;
175110
- if (newLen < currentLen) {
175111
- this.arraySpliceImpl(target, newLen, currentLen - newLen);
175112
- } else if (newLen > currentLen) {
175113
- this.arrayEnsureCapacity(target, newLen);
175114
- this.u32[this.scratchPtr + 8 >> 2] = newLen;
175115
- }
175116
- return true;
175117
- }
175118
- return false;
175119
- }
175120
- const idx = Number(prop);
175121
- if (!isNaN(idx)) {
175122
- this.arraySet(target, idx, value);
175123
- return true;
175124
- }
175125
- return false;
175126
- },
175127
- ownKeys: (target) => {
175128
- this.resolvePtr(target.__ptr);
175129
- const keys = [];
175130
- for (let i3 = 0;i3 < this.scratchLen; i3++)
175131
- keys.push(String(i3));
175132
- keys.push("length");
175133
- return keys;
175134
- },
175135
- getOwnPropertyDescriptor: (target, prop) => {
175136
- if (prop === "length") {
175137
- this.resolvePtr(target.__ptr);
175138
- return {
175139
- value: this.scratchLen,
175140
- writable: true,
175141
- enumerable: false,
175142
- configurable: false
175143
- };
175144
- }
175145
- const idx = Number(prop);
175146
- if (!isNaN(idx)) {
175147
- this.resolvePtr(target.__ptr);
175148
- if (idx >= 0 && idx < this.scratchLen) {
175149
- const val = this.readSlot(this.scratchStart + idx * 8);
175150
- return {
175151
- value: val,
175152
- enumerable: true,
175153
- configurable: true,
175154
- writable: true
175155
- };
175156
- }
175157
- }
175158
- return;
175159
- }
175160
- };
175161
- if (optionsOrBuffer instanceof SharedArrayBuffer) {
175162
- this.buffer = optionsOrBuffer;
175163
- this.initViews();
175164
- if (Atomics.load(this.u32, OFFSET_FREE_PTR >> 2) === 0) {
175165
- this.initializeBuffer(obj);
175166
- }
175167
- } else {
175168
- const size2 = optionsOrBuffer?.size || 1024 * 64;
175169
- this.buffer = new SharedArrayBuffer(size2);
175170
- this.initViews();
175171
- this.initializeBuffer(obj);
175172
- }
175173
- return this.getRootProxy();
175174
- }
175175
- initViews() {
175176
- this.u32 = new Uint32Array(this.buffer);
175177
- this.f64 = new Float64Array(this.buffer);
175178
- this.u8 = new Uint8Array(this.buffer);
175179
- }
175180
- initializeBuffer(obj) {
175181
- Atomics.store(this.u32, OFFSET_FREE_PTR >> 2, HEADER_SIZE);
175182
- const isArr = Array.isArray(obj);
175183
- const initialKeys = isArr ? obj.length : obj ? Object.keys(obj).length : 0;
175184
- const rootPtr = isArr ? this.allocArray(initialKeys) : this.allocObject(initialKeys);
175185
- Atomics.store(this.u32, OFFSET_ROOT >> 2, rootPtr);
175186
- if (obj) {
175187
- const rootTarget = { __ptr: rootPtr };
175188
- this.tempRoots.push({
175189
- handle: rootTarget,
175190
- type: isArr ? TYPE_ARRAY : TYPE_OBJECT
175191
- });
175192
- try {
175193
- this.writeInitial(rootTarget, obj);
175194
- } finally {
175195
- this.tempRoots.pop();
175196
- Atomics.store(this.u32, OFFSET_ROOT >> 2, rootTarget.__ptr);
175197
- }
175198
- }
175199
- }
175200
- getRootProxy() {
175201
- const rootPtr = Atomics.load(this.u32, OFFSET_ROOT >> 2);
175202
- return this.getProxyForPtr(rootPtr);
175203
- }
175204
- alloc(byteSize, retry2 = true) {
175205
- const idx = OFFSET_FREE_PTR >> 2;
175206
- const currentPtr = Atomics.load(this.u32, idx);
175207
- const nextPtr = currentPtr + byteSize;
175208
- const alignedNext = nextPtr + 7 & ~7;
175209
- if (alignedNext > this.buffer.byteLength) {
175210
- if (retry2) {
175211
- this.collectGarbage();
175212
- this.propertyHints.clear();
175213
- return this.alloc(byteSize, false);
175214
- }
175215
- throw new Error(`SharedJsonBuffer OOM: Used ${alignedNext} of ${this.buffer.byteLength}`);
175216
- }
175217
- Atomics.store(this.u32, idx, alignedNext);
175218
- return currentPtr;
175219
- }
175220
- collectGarbage() {
175221
- const tempBuffer = new ArrayBuffer(this.buffer.byteLength);
175222
- const tempU32 = new Uint32Array(tempBuffer);
175223
- const tempF64 = new Float64Array(tempBuffer);
175224
- const tempU8 = new Uint8Array(tempBuffer);
175225
- let freePtr = HEADER_SIZE;
175226
- const visited = new Map;
175227
- const allocTemp = (size2) => {
175228
- const ptr = freePtr;
175229
- freePtr = freePtr + size2 + 7 & ~7;
175230
- if (freePtr > tempBuffer.byteLength) {
175231
- throw new Error("GC Fatal: Fragmentation too high");
175232
- }
175233
- return ptr;
175234
- };
175235
- const relocate = (oldPtr, type) => {
175236
- if (oldPtr === 0)
175237
- return 0;
175238
- if (type === TYPE_STRING) {
175239
- if (visited.has(oldPtr))
175240
- return visited.get(oldPtr);
175241
- const len = this.u32[oldPtr >> 2];
175242
- const newPtr2 = allocTemp(4 + len);
175243
- tempU32[newPtr2 >> 2] = len;
175244
- tempU8.set(this.u8.subarray(oldPtr + 4, oldPtr + 4 + len), newPtr2 + 4);
175245
- visited.set(oldPtr, newPtr2);
175246
- return newPtr2;
175247
- }
175248
- if (type === TYPE_NUMBER) {
175249
- if (visited.has(oldPtr))
175250
- return visited.get(oldPtr);
175251
- const newPtr2 = allocTemp(8);
175252
- tempF64[newPtr2 >> 3] = this.f64[oldPtr >> 3];
175253
- visited.set(oldPtr, newPtr2);
175254
- return newPtr2;
175255
- }
175256
- this.resolvePtr(oldPtr);
175257
- const actualOldPtr = this.scratchPtr;
175258
- if (visited.has(actualOldPtr))
175259
- return visited.get(actualOldPtr);
175260
- const actualType = this.u32[actualOldPtr >> 2];
175261
- let newPtr = 0;
175262
- if (actualType === TYPE_OBJECT) {
175263
- const count = this.u32[actualOldPtr + 8 >> 2];
175264
- const newCap = Math.max(4, count);
175265
- newPtr = allocTemp(12 + newCap * 12);
175266
- tempU32[newPtr >> 2] = TYPE_OBJECT;
175267
- tempU32[newPtr + 4 >> 2] = newCap;
175268
- tempU32[newPtr + 8 >> 2] = count;
175269
- const startOffset = actualOldPtr + 12;
175270
- const newStartOffset = newPtr + 12;
175271
- for (let i3 = 0;i3 < count; i3++) {
175272
- const entryOff = startOffset + i3 * 12;
175273
- const kPtr = this.u32[entryOff >> 2];
175274
- const vType = this.u32[entryOff + 4 >> 2];
175275
- const vPayload = this.u32[entryOff + 8 >> 2];
175276
- const newKeyPtr = relocate(kPtr, TYPE_STRING);
175277
- let newPayload = vPayload;
175278
- if (vType === TYPE_OBJECT || vType === TYPE_ARRAY || vType === TYPE_STRING || vType === TYPE_NUMBER) {
175279
- newPayload = relocate(vPayload, vType);
175280
- }
175281
- const destOff = newStartOffset + i3 * 12;
175282
- tempU32[destOff >> 2] = newKeyPtr;
175283
- tempU32[destOff + 4 >> 2] = vType;
175284
- tempU32[destOff + 8 >> 2] = newPayload;
175285
- }
175286
- } else if (actualType === TYPE_ARRAY) {
175287
- const len = this.u32[actualOldPtr + 8 >> 2];
175288
- const newCap = Math.max(4, len);
175289
- newPtr = allocTemp(12 + newCap * 8);
175290
- tempU32[newPtr >> 2] = TYPE_ARRAY;
175291
- tempU32[newPtr + 4 >> 2] = newCap;
175292
- tempU32[newPtr + 8 >> 2] = len;
175293
- const startOffset = actualOldPtr + 12;
175294
- const newStartOffset = newPtr + 12;
175295
- for (let i3 = 0;i3 < len; i3++) {
175296
- const entryOff = startOffset + i3 * 8;
175297
- const vType = this.u32[entryOff >> 2];
175298
- const vPayload = this.u32[entryOff + 4 >> 2];
175299
- let newPayload = vPayload;
175300
- if (vType === TYPE_OBJECT || vType === TYPE_ARRAY || vType === TYPE_STRING || vType === TYPE_NUMBER) {
175301
- newPayload = relocate(vPayload, vType);
175302
- }
175303
- const destOff = newStartOffset + i3 * 8;
175304
- tempU32[destOff >> 2] = vType;
175305
- tempU32[destOff + 4 >> 2] = newPayload;
175306
- }
175307
- }
175308
- visited.set(actualOldPtr, newPtr);
175309
- return newPtr;
175310
- };
175311
- const oldRoot = Atomics.load(this.u32, OFFSET_ROOT >> 2);
175312
- const newRoot = relocate(oldRoot, TYPE_OBJECT);
175313
- for (let i3 = 0;i3 < this.tempRoots.length; i3++) {
175314
- const root = this.tempRoots[i3];
175315
- relocate(root.handle.__ptr, root.type);
175316
- }
175317
- this.u8.set(new Uint8Array(tempBuffer).subarray(0, freePtr), 0);
175318
- Atomics.store(this.u32, OFFSET_FREE_PTR >> 2, freePtr);
175319
- Atomics.store(this.u32, OFFSET_ROOT >> 2, newRoot);
175320
- this.stringCache.clear();
175321
- this.proxyCache.clear();
175322
- this.propertyHints.clear();
175323
- const fixupPointer = (target) => {
175324
- this.resolvePtr(target.__ptr);
175325
- const oldP = this.scratchPtr;
175326
- if (visited.has(oldP)) {
175327
- target.__ptr = visited.get(oldP);
175328
- } else {
175329
- target.__ptr = 0;
175330
- }
175331
- };
175332
- for (const target of this.activeTargets) {
175333
- fixupPointer(target);
175334
- }
175335
- for (const root of this.tempRoots) {
175336
- fixupPointer(root.handle);
175337
- }
173701
+ workers = [];
173702
+ jobQueue = [];
173703
+ concurrency;
173704
+ onLog;
173705
+ workerEntrypointPath;
173706
+ initialized = false;
173707
+ constructor(options) {
173708
+ this.concurrency = options.concurrency;
173709
+ this.onLog = options.onLog;
173710
+ this.workerEntrypointPath = getWorkerEntrypointPath();
175338
173711
  }
175339
- resolvePtr(ptr) {
175340
- if (ptr === 0) {
175341
- this.scratchPtr = 0;
175342
- this.scratchLen = 0;
173712
+ async initWorkers() {
173713
+ if (this.initialized)
175343
173714
  return;
175344
- }
175345
- let curr = ptr;
175346
- let type = this.u32[curr >> 2];
175347
- while (type === TYPE_MOVED) {
175348
- curr = this.u32[curr + 4 >> 2];
175349
- type = this.u32[curr >> 2];
175350
- }
175351
- this.scratchPtr = curr;
175352
- this.scratchCap = this.u32[curr + 4 >> 2];
175353
- this.scratchLen = this.u32[curr + 8 >> 2];
175354
- this.scratchStart = curr + 12;
175355
- }
175356
- readString(ptr) {
175357
- if (this.stringCache.has(ptr)) {
175358
- return this.stringCache.get(ptr);
175359
- }
175360
- const len = this.u32[ptr >> 2];
175361
- const offset = ptr + 4;
175362
- if (len < 64) {
175363
- let res2 = "";
175364
- for (let i3 = 0;i3 < len; i3++) {
175365
- res2 += String.fromCharCode(this.u8[offset + i3]);
175366
- }
175367
- this.stringCache.set(ptr, res2);
175368
- return res2;
175369
- }
175370
- const str = this.textDecoder.decode(this.u8.subarray(offset, offset + len));
175371
- this.stringCache.set(ptr, str);
175372
- return str;
175373
- }
175374
- readSlot(offset) {
175375
- const type = this.u32[offset >> 2];
175376
- const payload = this.u32[offset + 4 >> 2];
175377
- if (type === TYPE_NUMBER) {
175378
- return this.f64[payload >> 3];
175379
- }
175380
- switch (type) {
175381
- case TYPE_STRING:
175382
- return this.readString(payload);
175383
- case TYPE_OBJECT:
175384
- case TYPE_ARRAY:
175385
- return this.getProxyForPtr(payload);
175386
- case TYPE_TRUE:
175387
- return true;
175388
- case TYPE_FALSE:
175389
- return false;
175390
- case TYPE_NULL:
175391
- return null;
175392
- default:
175393
- return;
175394
- }
175395
- }
175396
- writeValue(value) {
175397
- if (typeof value === "number") {
175398
- const ptr = this.alloc(8);
175399
- this.f64[ptr >> 3] = value;
175400
- return { type: TYPE_NUMBER, payload: ptr };
175401
- }
175402
- if (value === null || value === undefined) {
175403
- return { type: TYPE_NULL, payload: 0 };
175404
- }
175405
- if (value === true)
175406
- return { type: TYPE_TRUE, payload: 0 };
175407
- if (value === false)
175408
- return { type: TYPE_FALSE, payload: 0 };
175409
- if (typeof value === "string") {
175410
- const encoded = this.textEncoder.encode(value);
175411
- const len = encoded.byteLength;
175412
- const ptr = this.alloc(4 + len);
175413
- this.u32[ptr >> 2] = len;
175414
- this.u8.set(encoded, ptr + 4);
175415
- return { type: TYPE_STRING, payload: ptr };
175416
- }
175417
- if (Array.isArray(value)) {
175418
- const ptr = this.allocArray(value.length);
175419
- const target = { __ptr: ptr };
175420
- this.tempRoots.push({ handle: target, type: TYPE_ARRAY });
175421
- try {
175422
- value.forEach((v4, i3) => this.arraySet(target, i3, v4));
175423
- } finally {
175424
- this.tempRoots.pop();
175425
- }
175426
- return { type: TYPE_ARRAY, payload: target.__ptr };
175427
- }
175428
- if (typeof value === "object") {
175429
- const keys = Object.keys(value);
175430
- const ptr = this.allocObject(keys.length);
175431
- const target = { __ptr: ptr };
175432
- this.tempRoots.push({ handle: target, type: TYPE_OBJECT });
175433
- try {
175434
- Object.entries(value).forEach(([k4, v4]) => this.objectSet(target, k4, v4));
175435
- } finally {
175436
- this.tempRoots.pop();
175437
- }
175438
- return { type: TYPE_OBJECT, payload: target.__ptr };
175439
- }
175440
- throw new Error(`Unsupported type: ${typeof value}`);
175441
- }
175442
- allocObject(initialCap) {
175443
- const capacity2 = Math.max(4, initialCap);
175444
- const byteSize = 12 + capacity2 * 12;
175445
- const ptr = this.alloc(byteSize);
175446
- const idx = ptr >> 2;
175447
- this.u32[idx] = TYPE_OBJECT;
175448
- this.u32[idx + 1] = capacity2;
175449
- this.u32[idx + 2] = 0;
175450
- return ptr;
175451
- }
175452
- allocArray(initialCap) {
175453
- const capacity2 = Math.max(4, initialCap);
175454
- const byteSize = 12 + capacity2 * 8;
175455
- const ptr = this.alloc(byteSize);
175456
- const idx = ptr >> 2;
175457
- this.u32[idx] = TYPE_ARRAY;
175458
- this.u32[idx + 1] = capacity2;
175459
- this.u32[idx + 2] = 0;
175460
- return ptr;
175461
- }
175462
- writeInitial(target, data) {
175463
- if (Array.isArray(data)) {
175464
- data.forEach((v4, i3) => this.arraySet(target, i3, v4));
175465
- } else {
175466
- Object.entries(data).forEach(([k4, v4]) => this.objectSet(target, k4, v4));
175467
- }
175468
- }
175469
- getProxyForPtr(ptr) {
175470
- this.resolvePtr(ptr);
175471
- const resolvedPtr = this.scratchPtr;
175472
- if (this.proxyCache.has(resolvedPtr)) {
175473
- const ref = this.proxyCache.get(resolvedPtr);
175474
- const cached = ref?.deref();
175475
- if (cached)
175476
- return cached;
175477
- }
175478
- const type = this.u32[resolvedPtr >> 2];
175479
- const target = type === TYPE_ARRAY ? [] : {};
175480
- Object.defineProperty(target, "__ptr", {
175481
- value: resolvedPtr,
175482
- writable: true,
175483
- configurable: true,
175484
- enumerable: false
175485
- });
175486
- this.activeTargets.add(target);
175487
- const proxy = new Proxy(target, type === TYPE_ARRAY ? this.arrayHandler : this.objectHandler);
175488
- this.proxyCache.set(resolvedPtr, new WeakRef(proxy));
175489
- return proxy;
175490
- }
175491
- toConsoleView(ptr, depth = 0) {
175492
- this.resolvePtr(ptr);
175493
- const len = this.scratchLen;
175494
- const start = this.scratchStart;
175495
- const type = this.u32[this.scratchPtr >> 2];
175496
- const result = type === TYPE_ARRAY ? new Array(len) : {};
175497
- const EAGER_DEPTH = 5;
175498
- const EAGER_BREADTH = 100;
175499
- for (let i3 = 0;i3 < len; i3++) {
175500
- let key;
175501
- let offset;
175502
- if (type === TYPE_ARRAY) {
175503
- key = i3;
175504
- offset = start + i3 * 8;
175505
- } else {
175506
- const entryOffset = start + i3 * 12;
175507
- const keyPtr = this.u32[entryOffset >> 2];
175508
- key = this.readString(keyPtr);
175509
- offset = entryOffset + 4;
175510
- }
175511
- const itemType = this.u32[offset >> 2];
175512
- const itemPayload = this.u32[offset + 4 >> 2];
175513
- if (itemType === TYPE_OBJECT || itemType === TYPE_ARRAY) {
175514
- const isEager = depth < EAGER_DEPTH && i3 < EAGER_BREADTH;
175515
- if (isEager) {
175516
- result[key] = this.toConsoleView(itemPayload, depth + 1);
175517
- } else {
175518
- Object.defineProperty(result, key, {
175519
- enumerable: true,
175520
- configurable: true,
175521
- get: () => {
175522
- return this.toConsoleView(itemPayload, 0);
175523
- }
173715
+ for (let i3 = 0;i3 < this.concurrency; i3++) {
173716
+ const worker = new Worker(this.workerEntrypointPath);
173717
+ const threadWorker = {
173718
+ worker,
173719
+ busy: false,
173720
+ currentJob: null
173721
+ };
173722
+ this.setupWorkerMessageHandling(threadWorker);
173723
+ this.setupWorkerErrorHandling(threadWorker);
173724
+ this.workers.push(threadWorker);
173725
+ }
173726
+ this.initialized = true;
173727
+ }
173728
+ setupWorkerMessageHandling(threadWorker) {
173729
+ threadWorker.worker.on("message", (message) => {
173730
+ if (message.message_type === "worker_log") {
173731
+ const logMsg = message;
173732
+ if (this.onLog) {
173733
+ this.onLog(logMsg.log_lines);
173734
+ }
173735
+ } else if (message.message_type === "build_completed") {
173736
+ const completedMsg = message;
173737
+ const job = threadWorker.currentJob;
173738
+ if (job) {
173739
+ job.resolve({
173740
+ filePath: completedMsg.file_path,
173741
+ outputPath: completedMsg.output_path,
173742
+ ok: completedMsg.ok,
173743
+ errors: completedMsg.errors,
173744
+ warnings: completedMsg.warnings
175524
173745
  });
173746
+ threadWorker.currentJob = null;
173747
+ threadWorker.busy = false;
173748
+ this.processQueue();
175525
173749
  }
175526
- } else {
175527
- result[key] = this.readSlot(offset);
175528
- }
175529
- }
175530
- return result;
175531
- }
175532
- toJSON(ptr) {
175533
- this.resolvePtr(ptr);
175534
- const len = this.scratchLen;
175535
- const start = this.scratchStart;
175536
- const type = this.u32[this.scratchPtr >> 2];
175537
- if (type === TYPE_ARRAY) {
175538
- const arr = new Array(len);
175539
- for (let i3 = 0;i3 < len; i3++) {
175540
- const offset = start + i3 * 8;
175541
- const itemType = this.u32[offset >> 2];
175542
- const itemPayload = this.u32[offset + 4 >> 2];
175543
- if (itemType === TYPE_OBJECT || itemType === TYPE_ARRAY) {
175544
- arr[i3] = this.toJSON(itemPayload);
175545
- } else {
175546
- arr[i3] = this.readSlot(offset);
175547
- }
175548
- }
175549
- return arr;
175550
- } else {
175551
- const obj = {};
175552
- for (let i3 = 0;i3 < len; i3++) {
175553
- const entryOffset = start + i3 * 12;
175554
- const keyPtr = this.u32[entryOffset >> 2];
175555
- const key = this.readString(keyPtr);
175556
- const itemType = this.u32[entryOffset + 4 >> 2];
175557
- const itemPayload = this.u32[entryOffset + 8 >> 2];
175558
- if (itemType === TYPE_OBJECT || itemType === TYPE_ARRAY) {
175559
- obj[key] = this.toJSON(itemPayload);
175560
- } else {
175561
- obj[key] = this.readSlot(entryOffset + 4);
175562
- }
175563
- }
175564
- return obj;
175565
- }
175566
- }
175567
- objectDelete(target, key) {
175568
- this.resolvePtr(target.__ptr);
175569
- const ptr = this.scratchPtr;
175570
- const count = this.scratchLen;
175571
- const entriesStart = this.scratchStart;
175572
- let foundIdx = -1;
175573
- for (let i3 = 0;i3 < count; i3++) {
175574
- const entryOffset = entriesStart + i3 * 12;
175575
- const keyPtr = this.u32[entryOffset >> 2];
175576
- if (this.readString(keyPtr) === key) {
175577
- foundIdx = i3;
175578
- break;
175579
- }
175580
- }
175581
- if (foundIdx === -1)
175582
- return true;
175583
- const lastIdx = count - 1;
175584
- if (foundIdx !== lastIdx) {
175585
- const lastOffset = entriesStart + lastIdx * 12;
175586
- const foundOffset = entriesStart + foundIdx * 12;
175587
- this.u32[foundOffset >> 2] = this.u32[lastOffset >> 2];
175588
- this.u32[foundOffset + 4 >> 2] = this.u32[lastOffset + 4 >> 2];
175589
- this.u32[foundOffset + 8 >> 2] = this.u32[lastOffset + 8 >> 2];
175590
- }
175591
- this.u32[ptr + 8 >> 2] = count - 1;
175592
- return true;
175593
- }
175594
- objectSet(target, key, value) {
175595
- this.resolvePtr(target.__ptr);
175596
- const preScanLen = this.scratchLen;
175597
- const preScanStart = this.scratchStart;
175598
- for (let i3 = 0;i3 < preScanLen; i3++) {
175599
- const entryOffset = preScanStart + i3 * 12;
175600
- const keyPtr = this.u32[entryOffset >> 2];
175601
- if (this.readString(keyPtr) === key) {
175602
- this.u32[entryOffset + 4 >> 2] = TYPE_NULL;
175603
- this.u32[entryOffset + 8 >> 2] = 0;
175604
- break;
175605
- }
175606
- }
175607
- const valResult = this.writeValue(value);
175608
- const valHandle = { __ptr: valResult.payload };
175609
- const isValPtr = valResult.type >= TYPE_NUMBER;
175610
- if (isValPtr) {
175611
- this.tempRoots.push({ handle: valHandle, type: valResult.type });
175612
- }
175613
- try {
175614
- this.resolvePtr(target.__ptr);
175615
- let ptr = this.scratchPtr;
175616
- const entriesStart = this.scratchStart;
175617
- const count = this.scratchLen;
175618
- const cap2 = this.scratchCap;
175619
- for (let i3 = 0;i3 < count; i3++) {
175620
- const entryOffset = entriesStart + i3 * 12;
175621
- const keyPtr = this.u32[entryOffset >> 2];
175622
- if (this.readString(keyPtr) === key) {
175623
- this.u32[entryOffset + 4 >> 2] = valResult.type;
175624
- this.u32[entryOffset + 8 >> 2] = valHandle.__ptr;
175625
- return;
175626
- }
175627
- }
175628
- const keyResult = this.writeValue(key);
175629
- const keyHandle = { __ptr: keyResult.payload };
175630
- this.tempRoots.push({ handle: keyHandle, type: TYPE_STRING });
175631
- try {
175632
- this.resolvePtr(target.__ptr);
175633
- ptr = this.scratchPtr;
175634
- const currentCap = this.scratchCap;
175635
- const currentCount = this.scratchLen;
175636
- if (currentCount >= currentCap) {
175637
- const newCap = Math.max(currentCap * 2, 4);
175638
- const newByteSize = 12 + newCap * 12;
175639
- const newPtr = this.alloc(newByteSize);
175640
- this.resolvePtr(target.__ptr);
175641
- const oldDataStart = this.scratchStart;
175642
- const idx = newPtr >> 2;
175643
- this.u32[idx] = TYPE_OBJECT;
175644
- this.u32[idx + 1] = newCap;
175645
- this.u32[idx + 2] = currentCount + 1;
175646
- this.u8.set(this.u8.subarray(oldDataStart, oldDataStart + currentCount * 12), newPtr + 12);
175647
- const entryOffset = newPtr + 12 + currentCount * 12;
175648
- const eIdx = entryOffset >> 2;
175649
- this.u32[eIdx] = keyHandle.__ptr;
175650
- this.u32[eIdx + 1] = valResult.type;
175651
- this.u32[eIdx + 2] = valHandle.__ptr;
175652
- const pIdx = this.scratchPtr >> 2;
175653
- this.u32[pIdx] = TYPE_MOVED;
175654
- this.u32[pIdx + 1] = newPtr;
175655
- } else {
175656
- const entryOffset = this.scratchStart + currentCount * 12;
175657
- const eIdx = entryOffset >> 2;
175658
- this.u32[eIdx] = keyHandle.__ptr;
175659
- this.u32[eIdx + 1] = valResult.type;
175660
- this.u32[eIdx + 2] = valHandle.__ptr;
175661
- this.u32[ptr + 8 >> 2] = currentCount + 1;
175662
- }
175663
- } finally {
175664
- this.tempRoots.pop();
175665
173750
  }
175666
- } finally {
175667
- if (isValPtr)
175668
- this.tempRoots.pop();
175669
- }
175670
- }
175671
- arrayEnsureCapacity(target, minCap) {
175672
- this.resolvePtr(target.__ptr);
175673
- if (this.scratchCap >= minCap)
175674
- return;
175675
- const oldCap = this.scratchCap;
175676
- const oldLen = this.scratchLen;
175677
- const oldDataStart = this.scratchStart;
175678
- const newCap = Math.max(oldCap * 2, minCap);
175679
- const newByteSize = 12 + newCap * 8;
175680
- const newPtr = this.alloc(newByteSize);
175681
- this.resolvePtr(target.__ptr);
175682
- const idx = newPtr >> 2;
175683
- this.u32[idx] = TYPE_ARRAY;
175684
- this.u32[idx + 1] = newCap;
175685
- this.u32[idx + 2] = oldLen;
175686
- this.u8.set(this.u8.subarray(oldDataStart, oldDataStart + oldLen * 8), newPtr + 12);
175687
- const pIdx = this.scratchPtr >> 2;
175688
- this.u32[pIdx] = TYPE_MOVED;
175689
- this.u32[pIdx + 1] = newPtr;
175690
- this.resolvePtr(target.__ptr);
175691
- }
175692
- arraySpliceImpl(target, start, deleteCount, items = []) {
175693
- this.resolvePtr(target.__ptr);
175694
- const len = this.scratchLen;
175695
- const actualStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
175696
- const actualDeleteCount = Math.min(Math.max(deleteCount, 0), len - actualStart);
175697
- const deletedItems = [];
175698
- for (let i3 = 0;i3 < actualDeleteCount; i3++) {
175699
- const offset = this.scratchStart + (actualStart + i3) * 8;
175700
- deletedItems.push(this.readSlot(offset));
175701
- }
175702
- const insertCount = items.length;
175703
- const delta = insertCount - actualDeleteCount;
175704
- const newLen = len + delta;
175705
- this.arrayEnsureCapacity(target, newLen);
175706
- if (delta !== 0) {
175707
- const tailCount = len - (actualStart + actualDeleteCount);
175708
- const srcIdx = actualStart + actualDeleteCount;
175709
- const destIdx = actualStart + insertCount;
175710
- const srcOffset = this.scratchStart + srcIdx * 8;
175711
- const destOffset = this.scratchStart + destIdx * 8;
175712
- const byteLen = tailCount * 8;
175713
- this.u8.copyWithin(destOffset, srcOffset, srcOffset + byteLen);
175714
- }
175715
- for (let i3 = 0;i3 < insertCount; i3++) {
175716
- const val = items[i3];
175717
- const valResult = this.writeValue(val);
175718
- const valHandle = { __ptr: valResult.payload };
175719
- const isValPtr = valResult.type >= TYPE_NUMBER;
175720
- if (isValPtr) {
175721
- this.tempRoots.push({ handle: valHandle, type: valResult.type });
175722
- }
175723
- this.resolvePtr(target.__ptr);
175724
- const offset = this.scratchStart + (actualStart + i3) * 8;
175725
- const oIdx = offset >> 2;
175726
- this.u32[oIdx] = valResult.type;
175727
- this.u32[oIdx + 1] = valHandle.__ptr;
175728
- if (isValPtr)
175729
- this.tempRoots.pop();
175730
- }
175731
- this.u32[this.scratchPtr + 8 >> 2] = newLen;
175732
- this.scratchLen = newLen;
175733
- return deletedItems;
175734
- }
175735
- toArrayShallow(ptr) {
175736
- this.resolvePtr(ptr);
175737
- const len = this.scratchLen;
175738
- const start = this.scratchStart;
175739
- const result = new Array(len);
175740
- for (let i3 = 0;i3 < len; i3++) {
175741
- result[i3] = this.readSlot(start + i3 * 8);
175742
- }
175743
- return result;
173751
+ });
175744
173752
  }
175745
- arraySet(target, index, value) {
175746
- this.resolvePtr(target.__ptr);
175747
- if (index < this.scratchLen) {
175748
- const offset = this.scratchStart + index * 8;
175749
- this.u32[offset >> 2] = TYPE_NULL;
175750
- this.u32[offset + 4 >> 2] = 0;
175751
- }
175752
- const valResult = this.writeValue(value);
175753
- const valHandle = { __ptr: valResult.payload };
175754
- const isValPtr = valResult.type >= TYPE_NUMBER;
175755
- if (isValPtr) {
175756
- this.tempRoots.push({ handle: valHandle, type: valResult.type });
175757
- }
175758
- try {
175759
- this.resolvePtr(target.__ptr);
175760
- const ptr = this.scratchPtr;
175761
- const cap2 = this.scratchCap;
175762
- const len = this.scratchLen;
175763
- if (index >= cap2) {
175764
- const newCap = Math.max(cap2 * 2, index + 1);
175765
- const newByteSize = 12 + newCap * 8;
175766
- const newPtr = this.alloc(newByteSize);
175767
- this.resolvePtr(target.__ptr);
175768
- const oldDataStart = this.scratchStart;
175769
- const idx = newPtr >> 2;
175770
- this.u32[idx] = TYPE_ARRAY;
175771
- this.u32[idx + 1] = newCap;
175772
- const newLen = Math.max(len, index + 1);
175773
- this.u32[idx + 2] = newLen;
175774
- const oldByteLen = len * 8;
175775
- this.u8.set(this.u8.subarray(oldDataStart, oldDataStart + oldByteLen), newPtr + 12);
175776
- const pIdx = this.scratchPtr >> 2;
175777
- this.u32[pIdx] = TYPE_MOVED;
175778
- this.u32[pIdx + 1] = newPtr;
175779
- const offset2 = newPtr + 12 + index * 8;
175780
- const oIdx2 = offset2 >> 2;
175781
- this.u32[oIdx2] = valResult.type;
175782
- this.u32[oIdx2 + 1] = valHandle.__ptr;
175783
- return;
173753
+ setupWorkerErrorHandling(threadWorker) {
173754
+ threadWorker.worker.on("error", (error) => {
173755
+ if (threadWorker.currentJob) {
173756
+ threadWorker.currentJob.reject(error);
173757
+ threadWorker.currentJob = null;
173758
+ threadWorker.busy = false;
175784
173759
  }
175785
- const offset = ptr + 12 + index * 8;
175786
- const oIdx = offset >> 2;
175787
- this.u32[oIdx] = valResult.type;
175788
- this.u32[oIdx + 1] = valHandle.__ptr;
175789
- if (index >= len) {
175790
- this.u32[ptr + 8 >> 2] = index + 1;
175791
- }
175792
- } finally {
175793
- if (isValPtr)
175794
- this.tempRoots.pop();
175795
- }
175796
- }
175797
- [toSerialized]() {
175798
- return {
175799
- value: this.buffer,
175800
- transfer: [],
175801
- typeId: 7
175802
- };
175803
- }
175804
- static [toDeserialized](data) {
175805
- return new _a7(null, data);
175806
- }
175807
- }
175808
- _a7 = SharedJsonBufferImpl;
175809
- (() => {
175810
- initConsoleHooks();
175811
- register2(7, _a7);
175812
- })();
175813
-
175814
- class ArrayCursor {
175815
- constructor(buffer, ptr) {
175816
- this.buffer = buffer;
175817
- this.index = 0;
175818
- this.target = { __ptr: 0 };
175819
- buffer.resolvePtr(ptr);
175820
- this.len = buffer.scratchLen;
175821
- this.start = buffer.scratchStart;
175822
- const type = buffer.u32[buffer.scratchPtr >> 2];
175823
- if (type !== TYPE_ARRAY) {
175824
- throw new Error("Iterator must be used on an Array");
175825
- }
175826
- this.flyweightProxy = new Proxy(this.target, buffer.objectHandler);
175827
- this.result = { done: false, value: this.flyweightProxy };
175828
- }
175829
- [Symbol.iterator]() {
175830
- return this;
175831
- }
175832
- next() {
175833
- if (this.index >= this.len) {
175834
- this.result.done = true;
175835
- this.result.value = undefined;
175836
- return this.result;
175837
- }
175838
- const offset = this.start + this.index * 8;
175839
- const itemType = this.buffer.u32[offset >> 2];
175840
- const itemPayload = this.buffer.u32[offset + 4 >> 2];
175841
- this.index++;
175842
- if (itemType === TYPE_OBJECT || itemType === TYPE_ARRAY) {
175843
- this.target.__ptr = itemPayload;
175844
- return this.result;
175845
- }
175846
- this.result.value = this.buffer.readSlot(offset);
175847
- return this.result;
175848
- }
175849
- }
175850
-
175851
- // node_modules/multithreading/src/lib/sync/mpmc.js
175852
- var __addDisposableResource = function(env3, value, async) {
175853
- if (value !== null && value !== undefined) {
175854
- if (typeof value !== "object" && typeof value !== "function")
175855
- throw new TypeError("Object expected.");
175856
- var dispose, inner;
175857
- if (async) {
175858
- if (!Symbol.asyncDispose)
175859
- throw new TypeError("Symbol.asyncDispose is not defined.");
175860
- dispose = value[Symbol.asyncDispose];
175861
- }
175862
- if (dispose === undefined) {
175863
- if (!Symbol.dispose)
175864
- throw new TypeError("Symbol.dispose is not defined.");
175865
- dispose = value[Symbol.dispose];
175866
- if (async)
175867
- inner = dispose;
175868
- }
175869
- if (typeof dispose !== "function")
175870
- throw new TypeError("Object not disposable.");
175871
- if (inner)
175872
- dispose = function() {
175873
- try {
175874
- inner.call(this);
175875
- } catch (e4) {
175876
- return Promise.reject(e4);
175877
- }
175878
- };
175879
- env3.stack.push({ value, dispose, async });
175880
- } else if (async) {
175881
- env3.stack.push({ async: true });
175882
- }
175883
- return value;
175884
- };
175885
- var __disposeResources = function(SuppressedError2) {
175886
- return function(env3) {
175887
- function fail(e4) {
175888
- env3.error = env3.hasError ? new SuppressedError2(e4, env3.error, "An error was suppressed during disposal.") : e4;
175889
- env3.hasError = true;
175890
- }
175891
- var r4, s4 = 0;
175892
- function next() {
175893
- while (r4 = env3.stack.pop()) {
175894
- try {
175895
- if (!r4.async && s4 === 1)
175896
- return s4 = 0, env3.stack.push(r4), Promise.resolve().then(next);
175897
- if (r4.dispose) {
175898
- var result = r4.dispose.call(r4.value);
175899
- if (r4.async)
175900
- return s4 |= 2, Promise.resolve(result).then(next, function(e4) {
175901
- fail(e4);
175902
- return next();
175903
- });
175904
- } else
175905
- s4 |= 1;
175906
- } catch (e4) {
175907
- fail(e4);
175908
- }
175909
- }
175910
- if (s4 === 1)
175911
- return env3.hasError ? Promise.reject(env3.error) : Promise.resolve();
175912
- if (env3.hasError)
175913
- throw env3.error;
175914
- }
175915
- return next();
175916
- };
175917
- }(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
175918
- var e4 = new Error(message);
175919
- return e4.name = "SuppressedError", e4.error = error, e4.suppressed = suppressed, e4;
175920
- });
175921
- var _a8;
175922
- var _b2;
175923
- var _c2;
175924
- var IDX_HEAD = 0;
175925
- var IDX_TAIL = 1;
175926
- var IDX_CLOSED = 2;
175927
- var IDX_CAP = 3;
175928
- var IDX_TX_COUNT = 4;
175929
- var IDX_RX_COUNT = 5;
175930
- var CLOSED = 1;
175931
- var ERR_DISPOSED_SENDER = new Error("Sender is disposed");
175932
- var ERR_DISPOSED_RECEIVER = new Error("Receiver disposed");
175933
- var ERR_CLOSED = new Error("Channel closed");
175934
- var ERR_CLOSED_NO_RX = new Error("Channel closed (No Receivers)");
175935
- var ERR_SPURIOUS = new Error("Spurious wakeup or illegal null value");
175936
-
175937
- class ChannelInternals extends Serializable {
175938
- constructor(state, items, sendLock, recvLock, itemsAvailable, slotsAvailable) {
175939
- super();
175940
- this.state = state;
175941
- this.items = items;
175942
- this.sendLock = sendLock;
175943
- this.recvLock = recvLock;
175944
- this.itemsAvailable = itemsAvailable;
175945
- this.slotsAvailable = slotsAvailable;
175946
- }
175947
- write(value) {
175948
- const tail = this.state[IDX_TAIL];
175949
- this.items[tail] = value;
175950
- this.state[IDX_TAIL] = (tail + 1) % this.state[IDX_CAP];
175951
- }
175952
- read() {
175953
- const head = this.state[IDX_HEAD];
175954
- const val = this.items[head];
175955
- if (val === null)
175956
- return null;
175957
- this.items[head] = null;
175958
- this.state[IDX_HEAD] = (head + 1) % this.state[IDX_CAP];
175959
- return val;
175960
- }
175961
- isClosed() {
175962
- return Atomics.load(this.state, IDX_CLOSED) === CLOSED;
175963
- }
175964
- hasReceivers() {
175965
- return Atomics.load(this.state, IDX_RX_COUNT) > 0;
175966
- }
175967
- [toSerialized]() {
175968
- const itemsSer = serialize(this.items);
175969
- const sendLockSer = serialize(this.sendLock);
175970
- const recvLockSer = serialize(this.recvLock);
175971
- const itemsAvailSer = serialize(this.itemsAvailable);
175972
- const slotsAvailSer = serialize(this.slotsAvailable);
175973
- return {
175974
- value: {
175975
- state: this.state.buffer,
175976
- items: itemsSer.value,
175977
- sendLock: sendLockSer.value,
175978
- recvLock: recvLockSer.value,
175979
- itemsAvailable: itemsAvailSer.value,
175980
- slotsAvailable: slotsAvailSer.value
175981
- },
175982
- transfer: [
175983
- ...itemsSer.transfer,
175984
- ...sendLockSer.transfer,
175985
- ...recvLockSer.transfer,
175986
- ...itemsAvailSer.transfer,
175987
- ...slotsAvailSer.transfer
175988
- ]
175989
- };
175990
- }
175991
- static [toDeserialized](data) {
175992
- return new _a8(new Int32Array(data.state), deserialize(data.items), deserialize(data.sendLock), deserialize(data.recvLock), deserialize(data.itemsAvailable), deserialize(data.slotsAvailable));
175993
- }
175994
- }
175995
- _a8 = ChannelInternals;
175996
- (() => {
175997
- register2(4, _a8);
175998
- })();
175999
-
176000
- class ChannelHandle extends Serializable {
176001
- constructor(internals) {
176002
- super();
176003
- this.internals = internals;
176004
- this.disposed = false;
176005
- }
176006
- checkDisposed() {
176007
- return this.disposed ? { ok: false, error: this.disposeError } : null;
176008
- }
176009
- [toSerialized]() {
176010
- if (this.disposed)
176011
- throw new Error("Cannot move a disposed Handle");
176012
- this.disposed = true;
176013
- return serialize(this.internals);
176014
- }
176015
- }
176016
-
176017
- class Sender extends ChannelHandle {
176018
- get disposeError() {
176019
- return ERR_DISPOSED_SENDER;
176020
- }
176021
- clone() {
176022
- if (this.disposed)
176023
- throw new Error("Cannot clone disposed Sender");
176024
- Atomics.add(this.internals.state, IDX_TX_COUNT, 1);
176025
- return new _b2(this.internals);
176026
- }
176027
- async send(value) {
176028
- const disposedCheck = this.checkDisposed();
176029
- if (disposedCheck)
176030
- return disposedCheck;
176031
- if (!this.internals.hasReceivers()) {
176032
- return { ok: false, error: ERR_CLOSED_NO_RX };
176033
- }
176034
- const slotToken = await this.internals.slotsAvailable.acquire();
176035
- if (this.internals.isClosed()) {
176036
- slotToken[Symbol.dispose]();
176037
- return { ok: false, error: ERR_CLOSED };
176038
- }
176039
- try {
176040
- const env_1 = { stack: [], error: undefined, hasError: false };
176041
- try {
176042
- const _lockGuard = __addDisposableResource(env_1, await this.internals.sendLock.acquire(), false);
176043
- if (this.internals.isClosed()) {
176044
- slotToken[Symbol.dispose]();
176045
- return { ok: false, error: ERR_CLOSED };
176046
- }
176047
- this.internals.write(value);
176048
- } catch (e_1) {
176049
- env_1.error = e_1;
176050
- env_1.hasError = true;
176051
- } finally {
176052
- __disposeResources(env_1);
173760
+ if (this.onLog) {
173761
+ this.onLog([`Worker error: ${error.message}`]);
176053
173762
  }
176054
- } catch (err) {
176055
- slotToken[Symbol.dispose]();
176056
- throw err;
176057
- }
176058
- this.internals.itemsAvailable[INTERNAL_SEMAPHORE_CONTROLLER].release(1);
176059
- return { ok: true, value: undefined };
176060
- }
176061
- blockingSend(value) {
176062
- const disposedCheck = this.checkDisposed();
176063
- if (disposedCheck)
176064
- return disposedCheck;
176065
- if (!this.internals.hasReceivers()) {
176066
- return { ok: false, error: ERR_CLOSED_NO_RX };
176067
- }
176068
- const slotToken = this.internals.slotsAvailable.blockingAcquire();
176069
- if (this.internals.isClosed()) {
176070
- slotToken[Symbol.dispose]();
176071
- return { ok: false, error: ERR_CLOSED };
176072
- }
176073
- try {
176074
- const lockToken = this.internals.sendLock.blockingAcquire();
176075
- try {
176076
- if (this.internals.isClosed()) {
176077
- slotToken[Symbol.dispose]();
176078
- return { ok: false, error: ERR_CLOSED };
176079
- }
176080
- this.internals.write(value);
176081
- } finally {
176082
- lockToken[Symbol.dispose]();
173763
+ });
173764
+ threadWorker.worker.on("exit", (code) => {
173765
+ if (code !== 0 && threadWorker.currentJob) {
173766
+ threadWorker.currentJob.reject(new Error(`Worker exited with code ${code}`));
173767
+ threadWorker.currentJob = null;
173768
+ threadWorker.busy = false;
176083
173769
  }
176084
- this.internals.itemsAvailable[INTERNAL_SEMAPHORE_CONTROLLER].release(1);
176085
- return { ok: true, value: undefined };
176086
- } catch (err) {
176087
- slotToken[Symbol.dispose]();
176088
- throw err;
176089
- }
173770
+ });
176090
173771
  }
176091
- close() {
176092
- if (this.disposed || this.internals.isClosed())
173772
+ processQueue() {
173773
+ if (this.jobQueue.length === 0)
176093
173774
  return;
176094
- const { state, slotsAvailable, itemsAvailable, sendLock, recvLock } = this.internals;
176095
- const g12 = sendLock.blockingAcquire();
176096
- const g22 = recvLock.blockingAcquire();
176097
- try {
176098
- if (this.internals.isClosed())
176099
- return;
176100
- Atomics.store(state, IDX_CLOSED, CLOSED);
176101
- slotsAvailable[INTERNAL_SEMAPHORE_CONTROLLER].release(1073741823);
176102
- itemsAvailable[INTERNAL_SEMAPHORE_CONTROLLER].release(1073741823);
176103
- } finally {
176104
- g12[Symbol.dispose]();
176105
- g22[Symbol.dispose]();
176106
- }
176107
- }
176108
- [Symbol.dispose]() {
176109
- if (this.disposed)
173775
+ const availableWorker = this.workers.find((w4) => !w4.busy);
173776
+ if (!availableWorker)
176110
173777
  return;
176111
- const prevCount = Atomics.sub(this.internals.state, IDX_TX_COUNT, 1);
176112
- if (prevCount === 1)
176113
- this.close();
176114
- this.disposed = true;
176115
- }
176116
- static [toDeserialized](obj) {
176117
- return new _b2(deserialize(obj));
176118
- }
176119
- }
176120
- _b2 = Sender;
176121
- (() => {
176122
- register2(5, _b2);
176123
- })();
176124
-
176125
- class Receiver extends ChannelHandle {
176126
- get disposeError() {
176127
- return ERR_DISPOSED_RECEIVER;
176128
- }
176129
- clone() {
176130
- if (this.disposed)
176131
- throw new Error("Cannot clone disposed Receiver");
176132
- Atomics.add(this.internals.state, IDX_RX_COUNT, 1);
176133
- return new _c2(this.internals);
176134
- }
176135
- async recv() {
176136
- const disposedCheck = this.checkDisposed();
176137
- if (disposedCheck)
176138
- return disposedCheck;
176139
- const itemToken = await this.internals.itemsAvailable.acquire();
176140
- let val;
176141
- try {
176142
- const env_2 = { stack: [], error: undefined, hasError: false };
176143
- try {
176144
- const _lockGuard = __addDisposableResource(env_2, await this.internals.recvLock.acquire(), false);
176145
- val = this.internals.read();
176146
- } catch (e_2) {
176147
- env_2.error = e_2;
176148
- env_2.hasError = true;
176149
- } finally {
176150
- __disposeResources(env_2);
176151
- }
176152
- } catch (err) {
176153
- itemToken[Symbol.dispose]();
176154
- throw err;
176155
- }
176156
- if (val === null) {
176157
- itemToken[Symbol.dispose]();
176158
- return this.internals.isClosed() ? { ok: false, error: ERR_CLOSED } : { ok: false, error: ERR_SPURIOUS };
176159
- }
176160
- this.internals.slotsAvailable[INTERNAL_SEMAPHORE_CONTROLLER].release(1);
176161
- return { ok: true, value: val };
176162
- }
176163
- blockingRecv() {
176164
- const disposedCheck = this.checkDisposed();
176165
- if (disposedCheck)
176166
- return disposedCheck;
176167
- const itemToken = this.internals.itemsAvailable.blockingAcquire();
176168
- let val;
176169
- try {
176170
- const lockToken = this.internals.recvLock.blockingAcquire();
176171
- try {
176172
- val = this.internals.read();
176173
- } finally {
176174
- lockToken[Symbol.dispose]();
176175
- }
176176
- } catch (err) {
176177
- itemToken[Symbol.dispose]();
176178
- throw err;
176179
- }
176180
- if (val === null) {
176181
- itemToken[Symbol.dispose]();
176182
- return this.internals.isClosed() ? { ok: false, error: ERR_CLOSED } : { ok: false, error: ERR_SPURIOUS };
176183
- }
176184
- this.internals.slotsAvailable[INTERNAL_SEMAPHORE_CONTROLLER].release(1);
176185
- return { ok: true, value: val };
176186
- }
176187
- async* [Symbol.asyncIterator]() {
176188
- while (true) {
176189
- const result = await this.recv();
176190
- if (result.ok) {
176191
- yield result.value;
176192
- } else {
176193
- const msg = result.error.message;
176194
- if (msg === ERR_CLOSED.message || msg === ERR_DISPOSED_RECEIVER.message) {
176195
- return;
176196
- }
176197
- throw result.error;
176198
- }
176199
- }
176200
- }
176201
- close() {
176202
- const sender = new Sender(this.internals);
176203
- sender.close();
176204
- }
176205
- [Symbol.dispose]() {
176206
- if (this.disposed)
173778
+ const job = this.jobQueue.shift();
173779
+ if (!job)
176207
173780
  return;
176208
- this.disposed = true;
176209
- const prevCount = Atomics.sub(this.internals.state, IDX_RX_COUNT, 1);
176210
- if (prevCount === 1)
176211
- this.close();
176212
- }
176213
- static [toDeserialized](obj) {
176214
- return new _c2(deserialize(obj));
173781
+ availableWorker.busy = true;
173782
+ availableWorker.currentJob = job;
173783
+ const message = {
173784
+ message_type: "build_file",
173785
+ file_path: job.filePath,
173786
+ output_path: job.outputPath,
173787
+ project_dir: job.projectDir,
173788
+ options: job.options
173789
+ };
173790
+ availableWorker.worker.postMessage(message);
173791
+ }
173792
+ async queueJob(job) {
173793
+ await this.initWorkers();
173794
+ return new Promise((resolve12, reject) => {
173795
+ const queuedJob = {
173796
+ ...job,
173797
+ resolve: resolve12,
173798
+ reject
173799
+ };
173800
+ this.jobQueue.push(queuedJob);
173801
+ this.processQueue();
173802
+ });
176215
173803
  }
176216
- }
176217
- _c2 = Receiver;
176218
- (() => {
176219
- register2(6, _c2);
176220
- })();
176221
- // node_modules/multithreading/src/lib/sync/barrier.js
176222
- var __classPrivateFieldSet5 = function(receiver, state, value, kind, f2) {
176223
- if (kind === "m")
176224
- throw new TypeError("Private method is not writable");
176225
- if (kind === "a" && !f2)
176226
- throw new TypeError("Private accessor was defined without a setter");
176227
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
176228
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
176229
- return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
176230
- };
176231
- var __classPrivateFieldGet5 = function(receiver, state, kind, f2) {
176232
- if (kind === "a" && !f2)
176233
- throw new TypeError("Private accessor was defined without a getter");
176234
- if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver))
176235
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
176236
- return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
176237
- };
176238
- var _Barrier_instances;
176239
- var _a9;
176240
- var _Barrier_state;
176241
- var _Barrier_lock;
176242
- var _Barrier_unlock;
176243
- var _Barrier_lockAsync;
176244
- var IDX_LOCK = 0;
176245
- var IDX_CAP2 = 1;
176246
- var IDX_COUNT = 2;
176247
- var IDX_GEN = 3;
176248
- var META_SIZE2 = 4;
176249
- var LOCK_UNLOCKED = 0;
176250
- var LOCK_LOCKED = 1;
176251
-
176252
- class Barrier extends Serializable {
176253
- constructor(n3, _buffer) {
176254
- super();
176255
- _Barrier_instances.add(this);
176256
- _Barrier_state.set(this, undefined);
176257
- if (_buffer) {
176258
- __classPrivateFieldSet5(this, _Barrier_state, new Int32Array(_buffer), "f");
176259
- } else {
176260
- if (n3 === undefined) {
176261
- throw new Error("Barrier capacity must be provided");
176262
- }
176263
- __classPrivateFieldSet5(this, _Barrier_state, new Int32Array(new SharedArrayBuffer(META_SIZE2 * Int32Array.BYTES_PER_ELEMENT)), "f");
176264
- __classPrivateFieldGet5(this, _Barrier_state, "f")[IDX_LOCK] = LOCK_UNLOCKED;
176265
- __classPrivateFieldGet5(this, _Barrier_state, "f")[IDX_CAP2] = n3;
176266
- __classPrivateFieldGet5(this, _Barrier_state, "f")[IDX_COUNT] = n3;
176267
- __classPrivateFieldGet5(this, _Barrier_state, "f")[IDX_GEN] = 0;
176268
- }
176269
- }
176270
- blockingWait() {
176271
- __classPrivateFieldGet5(this, _Barrier_instances, "m", _Barrier_lock).call(this);
176272
- const localGen = Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN);
176273
- const count = Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_COUNT) - 1;
176274
- if (count === 0) {
176275
- Atomics.store(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_COUNT, Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_CAP2));
176276
- Atomics.add(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN, 1);
176277
- __classPrivateFieldGet5(this, _Barrier_instances, "m", _Barrier_unlock).call(this);
176278
- Atomics.notify(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN, Infinity);
176279
- return { isLeader: true };
176280
- } else {
176281
- Atomics.store(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_COUNT, count);
176282
- __classPrivateFieldGet5(this, _Barrier_instances, "m", _Barrier_unlock).call(this);
176283
- while (Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN) === localGen) {
176284
- Atomics.wait(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN, localGen);
176285
- }
176286
- return { isLeader: false };
176287
- }
176288
- }
176289
- async wait() {
176290
- await __classPrivateFieldGet5(this, _Barrier_instances, "m", _Barrier_lockAsync).call(this);
176291
- const localGen = Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN);
176292
- const count = Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_COUNT) - 1;
176293
- if (count === 0) {
176294
- Atomics.store(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_COUNT, Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_CAP2));
176295
- Atomics.add(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN, 1);
176296
- __classPrivateFieldGet5(this, _Barrier_instances, "m", _Barrier_unlock).call(this);
176297
- Atomics.notify(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN, Infinity);
176298
- return { isLeader: true };
176299
- } else {
176300
- Atomics.store(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_COUNT, count);
176301
- __classPrivateFieldGet5(this, _Barrier_instances, "m", _Barrier_unlock).call(this);
176302
- while (Atomics.load(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN) === localGen) {
176303
- const res2 = Atomics.waitAsync(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_GEN, localGen);
176304
- if (res2.async) {
176305
- await res2.value;
173804
+ async runUntilComplete() {
173805
+ return new Promise((resolve12) => {
173806
+ const checkComplete = () => {
173807
+ const allIdle = this.workers.every((w4) => !w4.busy);
173808
+ const queueEmpty = this.jobQueue.length === 0;
173809
+ if (allIdle && queueEmpty) {
173810
+ resolve12();
173811
+ } else {
173812
+ setTimeout(checkComplete, 50);
176306
173813
  }
176307
- }
176308
- return { isLeader: false };
176309
- }
176310
- }
176311
- [(_Barrier_state = new WeakMap, _Barrier_instances = new WeakSet, _Barrier_lock = function _Barrier_lock() {
176312
- while (Atomics.compareExchange(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_LOCK, LOCK_UNLOCKED, LOCK_LOCKED) !== LOCK_UNLOCKED) {
176313
- Atomics.wait(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_LOCK, LOCK_LOCKED);
176314
- }
176315
- }, _Barrier_unlock = function _Barrier_unlock() {
176316
- if (Atomics.compareExchange(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_LOCK, LOCK_LOCKED, LOCK_UNLOCKED) !== LOCK_LOCKED) {
176317
- throw new Error("Barrier lock state corrupted");
176318
- }
176319
- Atomics.notify(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_LOCK, 1);
176320
- }, _Barrier_lockAsync = async function _Barrier_lockAsync() {
176321
- while (Atomics.compareExchange(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_LOCK, LOCK_UNLOCKED, LOCK_LOCKED) !== LOCK_UNLOCKED) {
176322
- const res2 = Atomics.waitAsync(__classPrivateFieldGet5(this, _Barrier_state, "f"), IDX_LOCK, LOCK_LOCKED);
176323
- if (res2.async) {
176324
- await res2.value;
176325
- }
176326
- }
176327
- }, toSerialized)]() {
176328
- return {
176329
- value: __classPrivateFieldGet5(this, _Barrier_state, "f").buffer,
176330
- transfer: []
176331
- };
173814
+ };
173815
+ checkComplete();
173816
+ });
176332
173817
  }
176333
- static [toDeserialized](buffer) {
176334
- return new _a9(undefined, buffer);
173818
+ async terminate() {
173819
+ const terminatePromises = this.workers.map((w4) => w4.worker.terminate());
173820
+ await Promise.all(terminatePromises);
173821
+ this.workers = [];
173822
+ this.initialized = false;
176335
173823
  }
176336
173824
  }
176337
- _a9 = Barrier;
176338
- (() => {
176339
- register2(8, _a9);
176340
- })();
176341
- // node_modules/multithreading/src/lib/lib.js
176342
- var globalPool = null;
176343
- var globalConfig = { maxWorkers: navigator.hardwareConcurrency || 4 };
176344
- var globalFunctionRegistry = new WeakMap;
176345
- function getPool() {
176346
- if (!globalPool) {
176347
- globalPool = new WorkerPool(globalConfig.maxWorkers);
176348
- }
176349
- return globalPool;
176350
- }
176351
- var moveTag = Symbol("Thread.move");
176352
- function move(...args) {
176353
- checkMoveArgs(args);
176354
- return Object.defineProperty(args, moveTag, {
176355
- enumerable: false,
176356
- configurable: false,
176357
- writable: false,
176358
- value: true
173825
+ async function buildFilesWithWorkerPool(options) {
173826
+ const pool = new WorkerPool({
173827
+ concurrency: options.concurrency,
173828
+ onLog: options.onLog
176359
173829
  });
176360
- }
176361
- function spawn(arg1, arg2) {
176362
- const pool = getPool();
176363
- const { resolve: resolve12, reject, promise } = Promise.withResolvers();
176364
- let args = [];
176365
- let fn3;
176366
- if (arg1 && Object.prototype.hasOwnProperty.call(arg1, moveTag)) {
176367
- args = arg1;
176368
- fn3 = arg2;
176369
- } else {
176370
- fn3 = arg1;
176371
- }
176372
- let meta = globalFunctionRegistry.get(fn3);
176373
- if (!meta) {
176374
- const id = Math.random().toString(36).slice(2);
176375
- const callerLocation = getCallerLocation();
176376
- try {
176377
- const code = patchDynamicImports("export default " + fn3.toString(), callerLocation.filePath);
176378
- meta = { id, code };
176379
- globalFunctionRegistry.set(fn3, meta);
176380
- } catch (err) {
176381
- console.error(err);
176382
- return {
176383
- join: () => Promise.resolve({
176384
- ok: false,
176385
- error: err instanceof Error ? err : new Error("Failed to compile function")
176386
- }),
176387
- abort: () => {}
176388
- };
176389
- }
173830
+ const results = [];
173831
+ const promises = [];
173832
+ for (const file of options.files) {
173833
+ const promise = pool.queueJob({
173834
+ filePath: file.filePath,
173835
+ outputPath: file.outputPath,
173836
+ projectDir: options.projectDir,
173837
+ options: options.buildOptions
173838
+ }).then((result) => {
173839
+ results.push(result);
173840
+ if (options.onJobComplete) {
173841
+ options.onJobComplete(result);
173842
+ }
173843
+ return result;
173844
+ });
173845
+ promises.push(promise);
176390
173846
  }
176391
- (async () => {
176392
- try {
176393
- const task = {
176394
- fnId: meta.id,
176395
- code: meta.code,
176396
- args
176397
- };
176398
- const val = await pool.submit(task);
176399
- resolve12({ ok: true, value: val });
176400
- } catch (err) {
176401
- resolve12({ ok: false, error: err });
176402
- }
176403
- })();
176404
- return {
176405
- join: () => promise,
176406
- abort: () => reject(new Error("Task aborted"))
176407
- };
173847
+ await Promise.all(promises);
173848
+ await pool.terminate();
173849
+ return results;
176408
173850
  }
176409
- var isWorker = typeof globalThis.WorkerGlobalScope !== "undefined" && self instanceof globalThis.WorkerGlobalScope;
176410
-
176411
- // node_modules/multithreading/src/node/lib.js
176412
- workerOverride(() => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }));
176413
173851
 
176414
173852
  // cli/build/register.ts
176415
- var normalizeRelativePath = (projectDir, targetPath) => path47.relative(projectDir, targetPath).split(path47.sep).join("/");
173853
+ var normalizeRelativePath = (projectDir, targetPath) => path48.relative(projectDir, targetPath).split(path48.sep).join("/");
176416
173854
  var registerBuild = (program3) => {
176417
173855
  program3.command("build").description("Run tscircuit eval and output circuit json").argument("[file]", "Path to the entry file").option("--ci", "Run install and optional prebuild/build commands (or default CI build)").option("--ignore-errors", "Do not exit with code 1 on errors").option("--ignore-warnings", "Do not log warnings").option("--disable-pcb", "Disable PCB outputs").option("--disable-parts-engine", "Disable the parts engine").option("--site", "Generate a static site in the dist directory").option("--transpile", "Transpile the entry file to JavaScript").option("--preview-images", "Generate preview images in the dist directory").option("--all-images", "Generate preview images for every successful build output").option("--kicad", "Generate KiCad project directories for each successful build output").option("--preview-gltf", "Generate a GLTF file from the preview entrypoint").option("--kicad-pcm", "Generate KiCad PCM (Plugin and Content Manager) assets in dist/pcm").option("--use-cdn-javascript", "Use CDN-hosted JavaScript instead of bundled standalone file for --site").option("--concurrency <number>", "Number of files to build in parallel (default: 1)", "1").action(async (file, options) => {
176418
173856
  try {
@@ -176445,8 +173883,8 @@ var registerBuild = (program3) => {
176445
173883
  }
176446
173884
  return config;
176447
173885
  })();
176448
- const distDir = path47.join(projectDir, "dist");
176449
- fs47.mkdirSync(distDir, { recursive: true });
173886
+ const distDir = path48.join(projectDir, "dist");
173887
+ fs48.mkdirSync(distDir, { recursive: true });
176450
173888
  const concurrencyValue = Math.max(1, Number.parseInt(resolvedOptions?.concurrency || "1", 10));
176451
173889
  if (concurrencyValue > 1) {
176452
173890
  console.log(`Building ${circuitFiles.length} file(s) with concurrency ${concurrencyValue}...`);
@@ -176464,7 +173902,7 @@ var registerBuild = (program3) => {
176464
173902
  platformConfig: platformConfig2
176465
173903
  };
176466
173904
  const processBuildResult = async (filePath, outputPath, buildOutcome) => {
176467
- const relative10 = path47.relative(projectDir, filePath);
173905
+ const relative10 = path48.relative(projectDir, filePath);
176468
173906
  const outputDirName = relative10.replace(/(\.board|\.circuit)?\.tsx$/, "");
176469
173907
  builtFiles.push({
176470
173908
  sourcePath: filePath,
@@ -176474,97 +173912,80 @@ var registerBuild = (program3) => {
176474
173912
  if (!buildOutcome.ok) {
176475
173913
  hasErrors = true;
176476
173914
  } else if (resolvedOptions?.site) {
176477
- const normalizedSourcePath = relative10.split(path47.sep).join("/");
176478
- const relativeOutputPath = path47.join(outputDirName, "circuit.json");
176479
- const normalizedOutputPath = relativeOutputPath.split(path47.sep).join("/");
173915
+ const normalizedSourcePath = relative10.split(path48.sep).join("/");
173916
+ const relativeOutputPath = path48.join(outputDirName, "circuit.json");
173917
+ const normalizedOutputPath = relativeOutputPath.split(path48.sep).join("/");
176480
173918
  staticFileReferences.push({
176481
173919
  filePath: normalizedSourcePath,
176482
173920
  fileStaticAssetUrl: `./${normalizedOutputPath}`
176483
173921
  });
176484
173922
  }
176485
- if (buildOutcome.ok && shouldGenerateKicad && buildOutcome.circuitJson) {
176486
- const projectOutputDir = path47.join(distDir, outputDirName, "kicad");
176487
- const projectName = path47.basename(outputDirName);
176488
- const project = await generateKicadProject({
176489
- circuitJson: buildOutcome.circuitJson,
176490
- outputDir: projectOutputDir,
176491
- projectName,
176492
- writeFiles: Boolean(resolvedOptions?.kicad)
176493
- });
176494
- kicadProjects.push({
176495
- ...project,
176496
- sourcePath: filePath
176497
- });
173923
+ if (buildOutcome.ok && shouldGenerateKicad) {
173924
+ let circuitJson = buildOutcome.circuitJson;
173925
+ if (!circuitJson && fs48.existsSync(outputPath)) {
173926
+ circuitJson = JSON.parse(fs48.readFileSync(outputPath, "utf-8"));
173927
+ }
173928
+ if (circuitJson) {
173929
+ const projectOutputDir = path48.join(distDir, outputDirName, "kicad");
173930
+ const projectName = path48.basename(outputDirName);
173931
+ const project = await generateKicadProject({
173932
+ circuitJson,
173933
+ outputDir: projectOutputDir,
173934
+ projectName,
173935
+ writeFiles: Boolean(resolvedOptions?.kicad)
173936
+ });
173937
+ kicadProjects.push({
173938
+ ...project,
173939
+ sourcePath: filePath
173940
+ });
173941
+ }
176498
173942
  }
176499
173943
  };
176500
173944
  const buildSequentially = async () => {
176501
173945
  for (const filePath of circuitFiles) {
176502
- const relative10 = path47.relative(projectDir, filePath);
173946
+ const relative10 = path48.relative(projectDir, filePath);
176503
173947
  console.log(`Building ${relative10}...`);
176504
173948
  const outputDirName = relative10.replace(/(\.board|\.circuit)?\.tsx$/, "");
176505
- const outputPath = path47.join(distDir, outputDirName, "circuit.json");
173949
+ const outputPath = path48.join(distDir, outputDirName, "circuit.json");
176506
173950
  const buildOutcome = await buildFile(filePath, outputPath, projectDir, buildOptions);
176507
173951
  await processBuildResult(filePath, outputPath, buildOutcome);
176508
173952
  }
176509
173953
  };
176510
- const buildWithMultithreading = async () => {
176511
- const buildTasks = circuitFiles.map((filePath) => {
176512
- const relative10 = path47.relative(projectDir, filePath);
173954
+ const buildWithWorkers = async () => {
173955
+ const filesToBuild = circuitFiles.map((filePath) => {
173956
+ const relative10 = path48.relative(projectDir, filePath);
176513
173957
  const outputDirName = relative10.replace(/(\.board|\.circuit)?\.tsx$/, "");
176514
- const outputPath = path47.join(distDir, outputDirName, "circuit.json");
176515
- return {
176516
- filePath,
176517
- outputPath,
176518
- projectDir,
176519
- options: buildOptions
176520
- };
173958
+ const outputPath = path48.join(distDir, outputDirName, "circuit.json");
173959
+ return { filePath, outputPath };
176521
173960
  });
176522
- const handles = buildTasks.map((task) => spawn(move(task), async (i3) => {
176523
- const { registerStaticAssetLoaders: registerStaticAssetLoaders2 } = await Promise.resolve().then(() => (init_register_static_asset_loaders(), exports_register_static_asset_loaders));
176524
- registerStaticAssetLoaders2();
176525
- const { buildFile: b3 } = await Promise.resolve().then(() => (init_build_file(), exports_build_file));
176526
- const r4 = await b3(i3.filePath, i3.outputPath, i3.projectDir, i3.options);
176527
- return {
176528
- filePath: i3.filePath,
176529
- outputPath: i3.outputPath,
176530
- ok: r4.ok,
176531
- circuitJson: r4.circuitJson,
176532
- logs: [],
176533
- errors: []
176534
- };
176535
- }));
176536
- const results = await Promise.all(handles.map((h3) => h3.join()));
176537
- for (let i3 = 0;i3 < results.length; i3++) {
176538
- const result = results[i3];
176539
- const task = buildTasks[i3];
176540
- const relative10 = path47.relative(projectDir, task.filePath);
176541
- if (!result.ok) {
176542
- console.error(kleur_default.red(`Failed to build ${relative10}: ${result.error}`));
176543
- await processBuildResult(task.filePath, task.outputPath, {
176544
- ok: false
176545
- });
176546
- continue;
176547
- }
176548
- const buildResult = result.value;
176549
- console.log(`[${relative10}]`);
176550
- if (buildResult.logs.length > 0) {
176551
- for (const log of buildResult.logs) {
176552
- console.log(` ${log}`);
173961
+ await buildFilesWithWorkerPool({
173962
+ files: filesToBuild,
173963
+ projectDir,
173964
+ concurrency: concurrencyValue,
173965
+ buildOptions,
173966
+ onLog: (lines) => {
173967
+ for (const line2 of lines) {
173968
+ console.log(line2);
176553
173969
  }
176554
- }
176555
- if (buildResult.errors.length > 0) {
176556
- for (const err of buildResult.errors) {
176557
- console.error(kleur_default.red(` ${err}`));
173970
+ },
173971
+ onJobComplete: async (result) => {
173972
+ const relative10 = path48.relative(projectDir, result.filePath);
173973
+ if (result.ok) {
173974
+ console.log(kleur_default.green(`✓ ${relative10}`));
173975
+ } else {
173976
+ console.log(kleur_default.red(`✗ ${relative10}`));
173977
+ for (const error of result.errors) {
173978
+ console.error(kleur_default.red(` ${error}`));
173979
+ }
176558
173980
  }
173981
+ await processBuildResult(result.filePath, result.outputPath, {
173982
+ ok: result.ok
173983
+ });
176559
173984
  }
176560
- await processBuildResult(task.filePath, task.outputPath, {
176561
- ok: buildResult.ok,
176562
- circuitJson: buildResult.circuitJson
176563
- });
176564
- }
173985
+ });
176565
173986
  };
176566
173987
  if (concurrencyValue > 1) {
176567
- await buildWithMultithreading();
173988
+ await buildWithWorkers();
176568
173989
  } else {
176569
173990
  await buildSequentially();
176570
173991
  }
@@ -176618,14 +174039,14 @@ var registerBuild = (program3) => {
176618
174039
  if (resolvedOptions?.useCdnJavascript) {
176619
174040
  standaloneScriptSrc = await getLatestTscircuitCdnUrl();
176620
174041
  } else {
176621
- fs47.writeFileSync(path47.join(distDir, "standalone.min.js"), standalone_min_default);
174042
+ fs48.writeFileSync(path48.join(distDir, "standalone.min.js"), standalone_min_default);
176622
174043
  }
176623
174044
  const indexHtml = getStaticIndexHtmlFile({
176624
174045
  files: staticFileReferences,
176625
174046
  standaloneScriptSrc,
176626
174047
  defaultMainComponentPath: siteDefaultComponentPath ? normalizeRelativePath(projectDir, siteDefaultComponentPath) : undefined
176627
174048
  });
176628
- fs47.writeFileSync(path47.join(distDir, "index.html"), indexHtml);
174049
+ fs48.writeFileSync(path48.join(distDir, "index.html"), indexHtml);
176629
174050
  }
176630
174051
  if (resolvedOptions?.kicadFootprintLibrary) {
176631
174052
  console.log("Generating KiCad footprint library...");
@@ -176644,15 +174065,15 @@ var registerBuild = (program3) => {
176644
174065
  process.exit(1);
176645
174066
  }
176646
174067
  } else {
176647
- const libraryName = path47.basename(projectDir);
176648
- const kicadLibOutputDir = path47.join(distDir, "kicad-library");
174068
+ const libraryName = path48.basename(projectDir);
174069
+ const kicadLibOutputDir = path48.join(distDir, "kicad-library");
176649
174070
  try {
176650
174071
  await convertToKicadLibrary({
176651
174072
  filePath: entryFile,
176652
174073
  libraryName,
176653
174074
  outputDir: kicadLibOutputDir
176654
174075
  });
176655
- console.log(` KiCad library generated at ${kleur_default.dim(path47.relative(process.cwd(), kicadLibOutputDir))}`);
174076
+ console.log(` KiCad library generated at ${kleur_default.dim(path48.relative(process.cwd(), kicadLibOutputDir))}`);
176656
174077
  } catch (err) {
176657
174078
  console.error(`Error generating KiCad library: ${err instanceof Error ? err.message : err}`);
176658
174079
  if (!resolvedOptions?.ignoreErrors) {
@@ -176710,7 +174131,7 @@ var registerBuild = (program3) => {
176710
174131
  if (enabledOpts.length > 0) {
176711
174132
  console.log(` Options ${kleur_default.cyan(enabledOpts.join(", "))}`);
176712
174133
  }
176713
- console.log(` Output ${kleur_default.dim(path47.relative(process.cwd(), distDir) || "dist")}`);
174134
+ console.log(` Output ${kleur_default.dim(path48.relative(process.cwd(), distDir) || "dist")}`);
176714
174135
  console.log(hasErrors ? kleur_default.yellow(`
176715
174136
  ⚠ Build completed with errors`) : kleur_default.green(`
176716
174137
  ✓ Done`));
@@ -176724,11 +174145,8 @@ var registerBuild = (program3) => {
176724
174145
  };
176725
174146
 
176726
174147
  // lib/shared/snapshot-project.ts
176727
- init_kleur();
176728
- init_generate_circuit_json();
176729
- init_get_complete_platform_config();
176730
- import fs49 from "node:fs";
176731
- import path48 from "node:path";
174148
+ import fs50 from "node:fs";
174149
+ import path49 from "node:path";
176732
174150
  import looksSame2 from "looks-same";
176733
174151
  import {
176734
174152
  convertCircuitJsonToPcbSvg as convertCircuitJsonToPcbSvg3,
@@ -176739,7 +174157,7 @@ import { renderGLTFToPNGBufferFromGLBBuffer as renderGLTFToPNGBufferFromGLBBuffe
176739
174157
 
176740
174158
  // lib/shared/compare-images.ts
176741
174159
  import looksSame from "looks-same";
176742
- import fs48 from "node:fs/promises";
174160
+ import fs49 from "node:fs/promises";
176743
174161
  var compareAndCreateDiff = async (buffer1, buffer2, diffPath) => {
176744
174162
  const { equal: equal2 } = await looksSame(buffer1, buffer2, {
176745
174163
  strict: false,
@@ -176755,7 +174173,7 @@ var compareAndCreateDiff = async (buffer1, buffer2, diffPath) => {
176755
174173
  tolerance: 2
176756
174174
  });
176757
174175
  } else {
176758
- await fs48.writeFile(diffPath, buffer2);
174176
+ await fs49.writeFile(diffPath, buffer2);
176759
174177
  }
176760
174178
  }
176761
174179
  return { equal: equal2 };
@@ -176780,7 +174198,7 @@ var snapshotProject = async ({
176780
174198
  ...DEFAULT_IGNORED_PATTERNS,
176781
174199
  ...ignored.map(normalizeIgnorePattern)
176782
174200
  ];
176783
- const resolvedPaths = filePaths.map((f2) => path48.resolve(projectDir, f2));
174201
+ const resolvedPaths = filePaths.map((f2) => path49.resolve(projectDir, f2));
176784
174202
  const boardFiles = findBoardFiles({
176785
174203
  projectDir,
176786
174204
  ignore,
@@ -176794,7 +174212,7 @@ var snapshotProject = async ({
176794
174212
  const mismatches = [];
176795
174213
  let didUpdate = false;
176796
174214
  for (const file of boardFiles) {
176797
- const relativeFilePath = path48.relative(projectDir, file);
174215
+ const relativeFilePath = path49.relative(projectDir, file);
176798
174216
  let circuitJson;
176799
174217
  let pcbSvg;
176800
174218
  let schSvg;
@@ -176849,17 +174267,17 @@ var snapshotProject = async ({
176849
174267
  } catch (error) {
176850
174268
  const errorMessage = error instanceof Error ? error.message : String(error);
176851
174269
  if (errorMessage.includes("No pcb_board found in circuit JSON")) {
176852
- const fileDir = path48.dirname(file);
176853
- const relativeDir = path48.relative(projectDir, fileDir);
176854
- const snapDir2 = snapshotsDirName ? path48.join(projectDir, snapshotsDirName, relativeDir) : path48.join(fileDir, "__snapshots__");
176855
- const base2 = path48.basename(file).replace(/\.tsx$/, "");
176856
- const snap3dPath = path48.join(snapDir2, `${base2}-3d.snap.png`);
176857
- const existing3dSnapshot = fs49.existsSync(snap3dPath);
174270
+ const fileDir = path49.dirname(file);
174271
+ const relativeDir = path49.relative(projectDir, fileDir);
174272
+ const snapDir2 = snapshotsDirName ? path49.join(projectDir, snapshotsDirName, relativeDir) : path49.join(fileDir, "__snapshots__");
174273
+ const base2 = path49.basename(file).replace(/\.tsx$/, "");
174274
+ const snap3dPath = path49.join(snapDir2, `${base2}-3d.snap.png`);
174275
+ const existing3dSnapshot = fs50.existsSync(snap3dPath);
176858
174276
  if (existing3dSnapshot) {
176859
174277
  onError(kleur_default.red(`
176860
174278
  ❌ Failed to generate 3D snapshot for ${relativeFilePath}:
176861
174279
  `) + kleur_default.red(` No pcb_board found in circuit JSON
176862
- `) + kleur_default.red(` Existing snapshot: ${path48.relative(projectDir, snap3dPath)}
174280
+ `) + kleur_default.red(` Existing snapshot: ${path49.relative(projectDir, snap3dPath)}
176863
174281
  `));
176864
174282
  return onExit2(1);
176865
174283
  } else {
@@ -176875,9 +174293,9 @@ var snapshotProject = async ({
176875
174293
  }
176876
174294
  }
176877
174295
  }
176878
- const snapDir = snapshotsDirName ? path48.join(projectDir, snapshotsDirName, path48.relative(projectDir, path48.dirname(file))) : path48.join(path48.dirname(file), "__snapshots__");
176879
- fs49.mkdirSync(snapDir, { recursive: true });
176880
- const base = path48.basename(file).replace(/\.tsx$/, "");
174296
+ const snapDir = snapshotsDirName ? path49.join(projectDir, snapshotsDirName, path49.relative(projectDir, path49.dirname(file))) : path49.join(path49.dirname(file), "__snapshots__");
174297
+ fs50.mkdirSync(snapDir, { recursive: true });
174298
+ const base = path49.basename(file).replace(/\.tsx$/, "");
176881
174299
  const snapshots = [];
176882
174300
  if (pcbOnly || !schematicOnly) {
176883
174301
  snapshots.push({ type: "pcb", content: pcbSvg, isBinary: false });
@@ -176895,31 +174313,31 @@ var snapshotProject = async ({
176895
174313
  for (const snapshot of snapshots) {
176896
174314
  const { type } = snapshot;
176897
174315
  const is3d = type === "3d";
176898
- const snapPath = path48.join(snapDir, `${base}-${type}.snap.${is3d ? "png" : "svg"}`);
176899
- const existing = fs49.existsSync(snapPath);
174316
+ const snapPath = path49.join(snapDir, `${base}-${type}.snap.${is3d ? "png" : "svg"}`);
174317
+ const existing = fs50.existsSync(snapPath);
176900
174318
  const newContentBuffer = snapshot.isBinary ? snapshot.content : Buffer.from(snapshot.content, "utf8");
176901
174319
  const newContentForFile = snapshot.content;
176902
174320
  if (!existing) {
176903
- fs49.writeFileSync(snapPath, newContentForFile);
176904
- console.log("✅", kleur_default.gray(path48.relative(projectDir, snapPath)));
174321
+ fs50.writeFileSync(snapPath, newContentForFile);
174322
+ console.log("✅", kleur_default.gray(path49.relative(projectDir, snapPath)));
176905
174323
  didUpdate = true;
176906
174324
  continue;
176907
174325
  }
176908
- const oldContentBuffer = fs49.readFileSync(snapPath);
174326
+ const oldContentBuffer = fs50.readFileSync(snapPath);
176909
174327
  const diffPath = snapPath.replace(is3d ? ".snap.png" : ".snap.svg", is3d ? ".diff.png" : ".diff.svg");
176910
174328
  const { equal: equal2 } = await compareAndCreateDiff(oldContentBuffer, newContentBuffer, diffPath);
176911
174329
  if (update) {
176912
174330
  if (!forceUpdate && equal2) {
176913
- console.log("✅", kleur_default.gray(path48.relative(projectDir, snapPath)));
174331
+ console.log("✅", kleur_default.gray(path49.relative(projectDir, snapPath)));
176914
174332
  } else {
176915
- fs49.writeFileSync(snapPath, newContentForFile);
176916
- console.log("✅", kleur_default.gray(path48.relative(projectDir, snapPath)));
174333
+ fs50.writeFileSync(snapPath, newContentForFile);
174334
+ console.log("✅", kleur_default.gray(path49.relative(projectDir, snapPath)));
176917
174335
  didUpdate = true;
176918
174336
  }
176919
174337
  } else if (!equal2) {
176920
174338
  mismatches.push(`${snapPath} (diff: ${diffPath})`);
176921
174339
  } else {
176922
- console.log("✅", kleur_default.gray(path48.relative(projectDir, snapPath)));
174340
+ console.log("✅", kleur_default.gray(path49.relative(projectDir, snapPath)));
176923
174341
  }
176924
174342
  }
176925
174343
  }
@@ -176958,22 +174376,22 @@ var registerSnapshot = (program3) => {
176958
174376
  };
176959
174377
 
176960
174378
  // lib/shared/setup-github-actions.ts
176961
- import fs50 from "node:fs";
176962
- import path49 from "node:path";
174379
+ import fs51 from "node:fs";
174380
+ import path50 from "node:path";
176963
174381
  var setupGithubActions = (projectDir = process.cwd()) => {
176964
174382
  const findGitRoot = (startDir) => {
176965
- let dir = path49.resolve(startDir);
176966
- while (dir !== path49.parse(dir).root) {
176967
- if (fs50.existsSync(path49.join(dir, ".git"))) {
174383
+ let dir = path50.resolve(startDir);
174384
+ while (dir !== path50.parse(dir).root) {
174385
+ if (fs51.existsSync(path50.join(dir, ".git"))) {
176968
174386
  return dir;
176969
174387
  }
176970
- dir = path49.dirname(dir);
174388
+ dir = path50.dirname(dir);
176971
174389
  }
176972
174390
  return null;
176973
174391
  };
176974
174392
  const gitRoot = findGitRoot(projectDir) ?? projectDir;
176975
- const workflowsDir = path49.join(gitRoot, ".github", "workflows");
176976
- fs50.mkdirSync(workflowsDir, { recursive: true });
174393
+ const workflowsDir = path50.join(gitRoot, ".github", "workflows");
174394
+ fs51.mkdirSync(workflowsDir, { recursive: true });
176977
174395
  const buildWorkflow = `name: tscircuit Build
176978
174396
 
176979
174397
  on:
@@ -177012,8 +174430,8 @@ jobs:
177012
174430
  - run: bun install
177013
174431
  - run: bunx tsci snapshot
177014
174432
  `;
177015
- writeFileIfNotExists(path49.join(workflowsDir, "tscircuit-build.yml"), buildWorkflow);
177016
- writeFileIfNotExists(path49.join(workflowsDir, "tscircuit-snapshot.yml"), snapshotWorkflow);
174433
+ writeFileIfNotExists(path50.join(workflowsDir, "tscircuit-build.yml"), buildWorkflow);
174434
+ writeFileIfNotExists(path50.join(workflowsDir, "tscircuit-snapshot.yml"), snapshotWorkflow);
177017
174435
  };
177018
174436
 
177019
174437
  // cli/setup/register.ts
@@ -177039,7 +174457,6 @@ var registerSetup = (program3) => {
177039
174457
  };
177040
174458
 
177041
174459
  // cli/auth/setup-npmrc/register.ts
177042
- init_kleur();
177043
174460
  function registerAuthSetupNpmrc(program3) {
177044
174461
  program3.commands.find((c3) => c3.name() === "auth").command("setup-npmrc").description("Configure your global .npmrc file with authentication for tscircuit private packages").action(async () => {
177045
174462
  const sessionToken = getSessionToken();
@@ -177052,9 +174469,8 @@ function registerAuthSetupNpmrc(program3) {
177052
174469
  }
177053
174470
 
177054
174471
  // cli/convert/register.ts
177055
- init_kleur();
177056
- import fs51 from "node:fs/promises";
177057
- import path50 from "node:path";
174472
+ import fs52 from "node:fs/promises";
174473
+ import path51 from "node:path";
177058
174474
  import { parseKicadModToCircuitJson } from "kicad-component-converter";
177059
174475
 
177060
174476
  // node_modules/@tscircuit/mm/dist/index.js
@@ -177175,15 +174591,15 @@ var convertCircuitJsonToTscircuit = (circuitJson, opts) => {
177175
174591
  var registerConvert = (program3) => {
177176
174592
  program3.command("convert").description("Convert a .kicad_mod footprint to a tscircuit component").argument("<file>", "Path to the .kicad_mod file").option("-o, --output <path>", "Output TSX file path").option("-n, --name <component>", "Component name for export").action(async (file, options) => {
177177
174593
  try {
177178
- const inputPath = path50.resolve(file);
177179
- const modContent = await fs51.readFile(inputPath, "utf-8");
174594
+ const inputPath = path51.resolve(file);
174595
+ const modContent = await fs52.readFile(inputPath, "utf-8");
177180
174596
  const circuitJson = await parseKicadModToCircuitJson(modContent);
177181
- const componentName = options.name ?? path50.basename(inputPath, ".kicad_mod");
174597
+ const componentName = options.name ?? path51.basename(inputPath, ".kicad_mod");
177182
174598
  const tsx = convertCircuitJsonToTscircuit(circuitJson, {
177183
174599
  componentName
177184
174600
  });
177185
- const outputPath = options.output ? path50.resolve(options.output) : path50.join(path50.dirname(inputPath), `${componentName}.tsx`);
177186
- await fs51.writeFile(outputPath, tsx);
174601
+ const outputPath = options.output ? path51.resolve(options.output) : path51.join(path51.dirname(inputPath), `${componentName}.tsx`);
174602
+ await fs52.writeFile(outputPath, tsx);
177187
174603
  console.log(kleur_default.green(`Converted ${outputPath}`));
177188
174604
  } catch (error) {
177189
174605
  console.error(kleur_default.red("Failed to convert footprint:"), error instanceof Error ? error.message : error);
@@ -177192,9 +174608,6 @@ var registerConvert = (program3) => {
177192
174608
  });
177193
174609
  };
177194
174610
 
177195
- // cli/simulate/register.ts
177196
- init_generate_circuit_json();
177197
-
177198
174611
  // lib/shared/result-to-table.ts
177199
174612
  var formatNumber = (n3) => {
177200
174613
  return n3.toExponential(6);
@@ -177302,7 +174715,7 @@ var registerInstall = (program3) => {
177302
174715
  };
177303
174716
 
177304
174717
  // cli/transpile/register.ts
177305
- import path51 from "node:path";
174718
+ import path52 from "node:path";
177306
174719
  var registerTranspile = (program3) => {
177307
174720
  program3.command("transpile").description("Transpile TypeScript/TSX to JavaScript (ESM, CommonJS, and type declarations)").argument("[file]", "Path to the entry file").action(async (file) => {
177308
174721
  try {
@@ -177310,7 +174723,7 @@ var registerTranspile = (program3) => {
177310
174723
  fileOrDir: file,
177311
174724
  includeBoardFiles: false
177312
174725
  });
177313
- const distDir = path51.join(projectDir, "dist");
174726
+ const distDir = path52.join(projectDir, "dist");
177314
174727
  validateMainInDist(projectDir, distDir);
177315
174728
  console.log("Transpiling entry file...");
177316
174729
  const entryFile = mainEntrypoint || circuitFiles[0];
@@ -177337,8 +174750,37 @@ var registerTranspile = (program3) => {
177337
174750
  });
177338
174751
  };
177339
174752
 
174753
+ // lib/shared/register-static-asset-loaders.ts
174754
+ var TEXT_STATIC_ASSET_EXTENSIONS = [
174755
+ ".gltf",
174756
+ ".step",
174757
+ ".kicad_mod",
174758
+ ".kicad_pcb",
174759
+ ".kicad_pro",
174760
+ ".kicad_sch"
174761
+ ];
174762
+ var staticAssetFilter = new RegExp(`(${TEXT_STATIC_ASSET_EXTENSIONS.map((ext) => ext.replace(".", "\\.")).join("|")})$`, "i");
174763
+ var registered = false;
174764
+ var registerStaticAssetLoaders = () => {
174765
+ if (registered)
174766
+ return;
174767
+ registered = true;
174768
+ if (typeof Bun !== "undefined" && typeof Bun.plugin === "function") {
174769
+ Bun.plugin({
174770
+ name: "tsci-static-assets",
174771
+ setup(build) {
174772
+ build.onLoad({ filter: staticAssetFilter }, (args) => {
174773
+ return {
174774
+ contents: `export default ${JSON.stringify(args.path)};`,
174775
+ loader: "js"
174776
+ };
174777
+ });
174778
+ }
174779
+ });
174780
+ }
174781
+ };
174782
+
177340
174783
  // cli/main.ts
177341
- init_register_static_asset_loaders();
177342
174784
  var program2 = new Command;
177343
174785
  program2.name("tsci").description("CLI for developing tscircuit packages");
177344
174786
  registerStaticAssetLoaders();