@normed/bundle 4.1.0 → 4.2.1

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.
@@ -1,3 +1,28 @@
1
1
  import "@normed/json-types";
2
- import { APIOptions_Bundle } from "./types";
3
- export default function bundle(options?: APIOptions_Bundle): Promise<undefined>;
2
+ import { Entrypoint, APIOptions_Bundle } from "./types";
3
+ import { WrappedErrors } from "./errors";
4
+ import { BundlePlugins } from "./plugins";
5
+ export default function bundle(options?: APIOptions_Bundle, plugins?: BundlePlugins): Promise<WrappedErrors | {
6
+ completed: boolean;
7
+ errors: Error[];
8
+ warnings: Error[];
9
+ watchFiles: import("./File").FileInfo[];
10
+ watchDirs: {
11
+ path: string;
12
+ }[];
13
+ producedFiles: import("./File").FileInfo[];
14
+ entrypoints: Entrypoint[];
15
+ duration_ms: number;
16
+ children: ({
17
+ completed: boolean;
18
+ watchFiles: import("./File").FileInfo[];
19
+ watchDirs: {
20
+ path: string;
21
+ }[];
22
+ producedFiles: import("./File").FileInfo[];
23
+ } & import("./errors").ErrorLog & {
24
+ entrypoints: Entrypoint[];
25
+ builder: import("./types").Builder;
26
+ duration_ms: number;
27
+ })[];
28
+ }>;
@@ -1,4 +1,4 @@
1
1
  import "@normed/json-types";
2
2
  import { Entrypoint, BuildConfig } from "./types";
3
3
  import { NoMatchingBuilder } from "./errors";
4
- export default function getEntrypoints(buildConfig: BuildConfig, manuallySpecified?: string[]): Promise<(Entrypoint | NoMatchingBuilder)[]>;
4
+ export default function getEntrypoints(buildConfig: BuildConfig, manuallySpecified?: string[]): Promise<(NoMatchingBuilder | Entrypoint)[]>;
@@ -1,3 +1,24 @@
1
+ export interface MetaField {
2
+ meta?: JSONishObject | undefined;
3
+ }
4
+ export type WithMeta<V> = V & MetaField;
5
+ export interface ErrorLog {
6
+ errors?: Error[];
7
+ warnings?: Error[];
8
+ }
9
+ export declare function combineErrorLogs(...logs: ErrorLog[]): ErrorLog;
10
+ export declare class WrappedErrors extends AggregateError implements MetaField, ErrorLog {
11
+ meta?: JSONishObject | undefined;
12
+ warnings?: Error[];
13
+ constructor(errors: Error[] | ErrorLog, message: string, meta?: JSONishObject | undefined);
14
+ static fromErrorLog(errorLog: ErrorLog, message: string, meta?: JSONishObject): WrappedErrors;
15
+ static fromError(error: Error, message: string, meta?: JSONishObject): WrappedErrors;
16
+ static fromErrors(errors: Error[], message: string, meta?: JSONishObject): WrappedErrors;
17
+ static fromValue(value: unknown, message: string, meta?: JSONishObject): WrappedErrors;
18
+ static fromValues(values: unknown[], message: string, meta?: JSONishObject): WrappedErrors;
19
+ }
20
+ export declare function asError(value: unknown): Error;
21
+ export declare function asError(value: unknown, meta: JSONishObject): WithMeta<Error>;
1
22
  export declare class NoMatchingBuilder extends Error {
2
23
  readonly file: string;
3
24
  readonly ext: string;
package/bundles/index.js CHANGED
@@ -68594,6 +68594,34 @@ function groupBy(objs, extractSubgroupFuncs) {
68594
68594
  }
68595
68595
  return groups;
68596
68596
  }
68597
+ function keyBy(objs, extractKeyFuncs) {
68598
+ const result = /* @__PURE__ */ new Map();
68599
+ const knownKeys = [];
68600
+ for (const obj of objs) {
68601
+ const key = {};
68602
+ for (const [keyName, extractKeyFunc] of Object.entries(extractKeyFuncs)) {
68603
+ key[keyName] = extractKeyFunc(obj);
68604
+ }
68605
+ let knownKey = knownKeys.find(
68606
+ (knownKey2) => Object.keys(knownKey2).length === Object.keys(key).length && Object.keys(knownKey2).every(
68607
+ (k) => knownKey2[k] === key[k]
68608
+ )
68609
+ );
68610
+ if (!knownKey) {
68611
+ knownKey = key;
68612
+ knownKeys.push(key);
68613
+ result.set(knownKey, [obj]);
68614
+ } else {
68615
+ const group = result.get(knownKey);
68616
+ if (group) {
68617
+ group.push(obj);
68618
+ } else {
68619
+ throw new Error(`Keying failed in keyBy`);
68620
+ }
68621
+ }
68622
+ }
68623
+ return result;
68624
+ }
68597
68625
  function divide(list, divider) {
68598
68626
  const a = [];
68599
68627
  const b = [];
@@ -68890,6 +68918,68 @@ function mergeDeep(into, from) {
68890
68918
  }
68891
68919
 
68892
68920
  // pnp:/builds/normed/bundle/packages/bundle/src/errors.ts
68921
+ function combineErrorLogs(...logs) {
68922
+ const combined = {
68923
+ errors: [],
68924
+ warnings: []
68925
+ };
68926
+ for (const log of logs) {
68927
+ if (log.errors) {
68928
+ combined.errors.push(...log.errors);
68929
+ }
68930
+ if (log.warnings) {
68931
+ combined.warnings.push(...log.warnings);
68932
+ }
68933
+ }
68934
+ return combined;
68935
+ }
68936
+ var WrappedErrors = class _WrappedErrors extends AggregateError {
68937
+ constructor(errors, message, meta) {
68938
+ var __super = (...args) => {
68939
+ super(...args);
68940
+ this.meta = meta;
68941
+ return this;
68942
+ };
68943
+ if (Array.isArray(errors)) {
68944
+ __super(errors, message);
68945
+ } else {
68946
+ __super(errors.errors ?? [], message);
68947
+ this.warnings = errors.warnings ?? [];
68948
+ }
68949
+ this.name = "WrappedError";
68950
+ }
68951
+ warnings;
68952
+ static fromErrorLog(errorLog, message, meta) {
68953
+ return new _WrappedErrors(errorLog, message, meta);
68954
+ }
68955
+ static fromError(error, message, meta) {
68956
+ return new _WrappedErrors([error], message, meta);
68957
+ }
68958
+ static fromErrors(errors, message, meta) {
68959
+ return new _WrappedErrors(errors, message, meta);
68960
+ }
68961
+ static fromValue(value, message, meta) {
68962
+ const error = asError(value);
68963
+ return new _WrappedErrors([error], message, meta);
68964
+ }
68965
+ static fromValues(values, message, meta) {
68966
+ const errors = values.map(asError);
68967
+ return new _WrappedErrors(errors, message, meta);
68968
+ }
68969
+ };
68970
+ function asError(value, meta) {
68971
+ let error;
68972
+ if (!(value instanceof Error)) {
68973
+ error = new Error(String(value));
68974
+ } else {
68975
+ error = value;
68976
+ }
68977
+ if (meta) {
68978
+ let existingMeta = error.meta ?? {};
68979
+ error.meta = { ...existingMeta, ...meta };
68980
+ }
68981
+ return error;
68982
+ }
68893
68983
  var NoMatchingBuilder = class extends Error {
68894
68984
  file;
68895
68985
  ext;
@@ -68914,6 +69004,14 @@ var copyBuilder = {
68914
69004
  copy(infile.absolute, outfile.absolute);
68915
69005
  })
68916
69006
  );
69007
+ return {
69008
+ warnings: [],
69009
+ errors: [],
69010
+ watchFiles: entrypoints.map((e) => e.infile),
69011
+ watchDirs: [],
69012
+ producedFiles: entrypoints.map((e) => e.outfile),
69013
+ completed: true
69014
+ };
68917
69015
  }
68918
69016
  };
68919
69017
 
@@ -68996,14 +69094,20 @@ var plugin = {
68996
69094
  build2.onResolve(
68997
69095
  { filter: filter2 },
68998
69096
  async (args) => {
68999
- return {
69000
- sideEffects: false,
69001
- pluginData: Object.assign({}, args.pluginData, {
69002
- [name]: {
69003
- entrypoint: args.kind === "entry-point"
69004
- }
69005
- })
69006
- };
69097
+ const resolvedPath = import_path4.default.resolve(args.resolveDir, args.path);
69098
+ if (import_fs3.default.existsSync(resolvedPath)) {
69099
+ return {
69100
+ sideEffects: false,
69101
+ path: import_path4.default.resolve(args.resolveDir, args.path),
69102
+ pluginData: Object.assign({}, args.pluginData, {
69103
+ [name]: {
69104
+ entrypoint: args.kind === "entry-point"
69105
+ }
69106
+ })
69107
+ };
69108
+ } else {
69109
+ return {};
69110
+ }
69007
69111
  }
69008
69112
  );
69009
69113
  build2.onLoad(
@@ -69042,6 +69146,30 @@ var load_less_default = plugin;
69042
69146
  var import_pug = __toESM(require_lib14());
69043
69147
  var import_fs4 = __toESM(require("fs"));
69044
69148
  var import_path5 = __toESM(require("path"));
69149
+ function pugTransformer(test, onFound) {
69150
+ return {
69151
+ preCodeGen(ast) {
69152
+ const pending = [...ast?.nodes || []];
69153
+ const found = [];
69154
+ while (pending.length > 0) {
69155
+ const node = pending.shift();
69156
+ if (!node) continue;
69157
+ if (node.block?.nodes) {
69158
+ pending.push(...node.block.nodes);
69159
+ }
69160
+ if (!test(node)) continue;
69161
+ found.push(node);
69162
+ }
69163
+ if (found.length) {
69164
+ onFound(found);
69165
+ }
69166
+ return ast;
69167
+ }
69168
+ };
69169
+ }
69170
+ function isScriptNodeWithSrcAttr(node) {
69171
+ return node.name === "script" && node.attrs.some((attr) => attr.name === "src");
69172
+ }
69045
69173
  async function loadAsText2(_filepath) {
69046
69174
  return {
69047
69175
  loader: "text"
@@ -69066,19 +69194,29 @@ async function loadAsHtml(filepath, options) {
69066
69194
  const contents = import_pug.default.render(fileData, {
69067
69195
  name: "render",
69068
69196
  filename: filepath,
69069
- basedir: options.outbase
69197
+ basedir: options.outbase,
69198
+ plugins: [
69199
+ pugTransformer(isScriptNodeWithSrcAttr, (nodes) => {
69200
+ nodes;
69201
+ })
69202
+ ]
69070
69203
  });
69071
69204
  return {
69072
69205
  contents,
69073
69206
  loader: "js"
69074
69207
  };
69075
69208
  }
69076
- async function loadAsCopy(filepath, options) {
69209
+ async function loadAsEntrypoint(filepath, options) {
69077
69210
  const fileData = await import_fs4.default.promises.readFile(filepath, "utf8");
69078
69211
  const contents = import_pug.default.render(fileData, {
69079
69212
  filename: filepath,
69080
69213
  basedir: options.outbase,
69081
- name: "render"
69214
+ name: "render",
69215
+ plugins: [
69216
+ pugTransformer(isScriptNodeWithSrcAttr, (nodes) => {
69217
+ nodes;
69218
+ })
69219
+ ]
69082
69220
  });
69083
69221
  return {
69084
69222
  contents,
@@ -69130,7 +69268,7 @@ var plugin2 = {
69130
69268
  }) => {
69131
69269
  const isEntryPoint = pluginData?.[name2]?.entrypoint;
69132
69270
  if (isEntryPoint) {
69133
- return loadAsCopy(filepath, build2.initialOptions);
69271
+ return loadAsEntrypoint(filepath, build2.initialOptions);
69134
69272
  }
69135
69273
  const type = withArg?.["type"] ?? "js";
69136
69274
  switch (type) {
@@ -69448,6 +69586,18 @@ var esbuilder = {
69448
69586
  }
69449
69587
  await Promise.all(promises);
69450
69588
  }
69589
+ return {
69590
+ // TODO: rewrite to return warnings
69591
+ warnings: [],
69592
+ // TODO: rewrite to return errors
69593
+ errors: [],
69594
+ watchFiles: entrypoints.map((e) => e.infile),
69595
+ watchDirs: [],
69596
+ // TODO: these are not the correct files
69597
+ producedFiles: entrypoints.map((e) => e.outfile),
69598
+ // TODO: rewrite to only return true if all builds were successful
69599
+ completed: true
69600
+ };
69451
69601
  }
69452
69602
  };
69453
69603
  async function compileToTypeDeclarations(fileNames, options) {
@@ -70321,7 +70471,7 @@ async function getEntrypoints(buildConfig, manuallySpecified) {
70321
70471
  }
70322
70472
 
70323
70473
  // pnp:/builds/normed/bundle/packages/bundle/src/bundle.ts
70324
- async function bundle(options = {}) {
70474
+ async function getBuildConfig(options) {
70325
70475
  const buildConfig = {
70326
70476
  dir: {
70327
70477
  in: getInDir(options),
@@ -70435,125 +70585,116 @@ async function bundle(options = {}) {
70435
70585
  "Build Config - post reading package.json",
70436
70586
  JSON.stringify(buildConfig.baseConfig, null, 2)
70437
70587
  );
70438
- const [raw_entrypoints, missingBuilders] = divide(
70439
- await getEntrypoints(buildConfig, options.entrypoints),
70440
- (v) => {
70441
- return !(v instanceof NoMatchingBuilder);
70442
- }
70443
- );
70444
- const [allContextEntrypoints, entrypoints] = divide(
70445
- raw_entrypoints,
70446
- (e) => e.origin === "discovered" && e.infile.modifiers.includes("context")
70588
+ return buildConfig;
70589
+ }
70590
+ async function discoverEntrypoints(buildConfig, entrypoints, plugins = {}) {
70591
+ let initialEntrypoints = await getEntrypoints(buildConfig, entrypoints);
70592
+ initialEntrypoints = await plugins.initialEntrypoints?.(initialEntrypoints) ?? initialEntrypoints;
70593
+ const [missing, found] = divide(
70594
+ initialEntrypoints,
70595
+ (e) => e instanceof NoMatchingBuilder
70447
70596
  );
70448
- let skippedContextFile = false;
70449
- await Promise.all(
70450
- allContextEntrypoints.map(async (contextEntrypoint) => {
70451
- if (4 > 1) {
70452
- if (!skippedContextFile) {
70453
- log_default.warn(`Context files are not yet supported`);
70454
- skippedContextFile = true;
70455
- }
70456
- log_default.warn(` - skipping ${contextEntrypoint.infile.relative}`);
70457
- return;
70597
+ if (missing.length) {
70598
+ const missingBuilders = missing.filter((v, i, a) => a.indexOf(v) === i);
70599
+ return WrappedErrors.fromErrors(
70600
+ missing,
70601
+ "Missing builders for entrypoints",
70602
+ {
70603
+ missingBuilders: missingBuilders.map((b) => b.name),
70604
+ missingBuilders_count: missingBuilders.length
70458
70605
  }
70459
- skippedContextFile = false;
70460
- const matchingEntrypoints = entrypoints.filter(
70461
- (e) => e.infile.bare === contextEntrypoint.infile.bare
70462
- );
70463
- if (!matchingEntrypoints.length) {
70464
- log_default.warn(
70465
- `Context file ${contextEntrypoint.infile.bare} is not used by any entrypoint`
70466
- );
70467
- return;
70468
- }
70469
- log_default.verbose(
70470
- `Context file ${contextEntrypoint.infile.bare} is used by ${matchingEntrypoints.length} entrypoints`
70471
- );
70472
- async function compile(_v) {
70473
- throw new Error("Function not implemented.");
70474
- }
70475
- const compiled = await compile(contextEntrypoint);
70476
- const { context } = await compiled.run();
70477
- if (!context) {
70478
- log_default.warn(
70479
- `Context file ${contextEntrypoint.infile.bare} did not export a context function`
70480
- );
70481
- return;
70482
- }
70483
- const contextResult = await context();
70484
- if (!contextResult) {
70485
- log_default.warn(
70486
- `Context file ${contextEntrypoint.infile.bare} did not return a context object`
70487
- );
70488
- return;
70489
- }
70490
- const builderNames = matchingEntrypoints.map((e) => e.builder.name).filter((v, i, a) => a.indexOf(v) === i);
70491
- const builderNamesWithContexts = builderNames.filter(
70492
- (name3) => contextResult[name3]
70493
- );
70494
- if (!builderNamesWithContexts.length) {
70495
- log_default.warn(
70496
- `Context file ${contextEntrypoint.infile.bare} did not return any context for any of the builders: ${builderNames.join(", ")}`
70497
- );
70498
- return;
70499
- }
70500
- for (const builderName of builderNamesWithContexts) {
70501
- await Promise.all(
70502
- matchingEntrypoints.filter((e) => e.builder.name === builderName).map(async (entrypoint) => {
70503
- const func = contextResult[builderName];
70504
- if (!func) {
70505
- log_default.warn(
70506
- `Context file ${contextEntrypoint.infile.bare} did not return a context for builder ${builderName}`
70507
- );
70508
- return;
70509
- }
70510
- entrypoint.context = await func();
70511
- })
70512
- );
70513
- }
70514
- })
70606
+ );
70607
+ }
70608
+ return plugins.discoveredEntrypoints?.(found) ?? found;
70609
+ }
70610
+ async function bundle(options = {}, plugins = {}) {
70611
+ const start = Date.now();
70612
+ const buildConfig = await getBuildConfig(options);
70613
+ const entrypoints = await discoverEntrypoints(
70614
+ buildConfig,
70615
+ options.entrypoints,
70616
+ plugins
70515
70617
  );
70516
- log_default.warn(missingBuilders.map((missing) => missing.message).join("\n"));
70517
- log_default.info(entrypoints.length + " entrypoints");
70518
- const grouped = entrypoints.reduce((acc, entryPoint) => {
70519
- const index = buildConfig.builders.indexOf(entryPoint.builder);
70520
- if (!acc[index]) {
70521
- acc[index] = [];
70522
- }
70523
- acc[index]?.push(entryPoint);
70524
- return acc;
70525
- }, []);
70526
- for (const index in grouped) {
70527
- const group = grouped[index];
70528
- const builder = buildConfig.builders[index];
70529
- if (!builder) {
70530
- continue;
70531
- }
70532
- log_default.info(
70533
- builder.color(
70534
- `${builder.name}:
70535
- ${group?.map((i) => `${i.infile.relative} => ${i.outfile.relative}`).join("\n ")}`
70536
- )
70618
+ if (entrypoints instanceof WrappedErrors) {
70619
+ return WrappedErrors.fromError(
70620
+ entrypoints,
70621
+ "Failed to discover entrypoints"
70537
70622
  );
70538
70623
  }
70539
- const results = await Promise.all(
70540
- grouped.map(
70541
- (entrypoints2, index) => (async () => {
70542
- const start = Date.now();
70543
- await buildConfig.builders[index]?.build(entrypoints2);
70544
- const duration = Math.floor((Date.now() - start) / 10) / 100;
70545
- const builder = buildConfig.builders[index];
70546
- if (!builder) {
70547
- log_default.info(`Unknown builder: ${duration} seconds`);
70548
- } else {
70549
- log_default.info(builder.color(`${builder.name}: ${duration} seconds`));
70624
+ let grouped = keyBy(entrypoints, {
70625
+ builder: (entrypoint) => entrypoint.builder
70626
+ });
70627
+ grouped = await plugins.preBuild?.(grouped) ?? grouped;
70628
+ const results = await Promise.allSettled(
70629
+ Array.from(grouped.entries()).map(
70630
+ async ([
70631
+ { builder },
70632
+ entrypoints2
70633
+ ]) => {
70634
+ const start2 = Date.now();
70635
+ const annotations = {
70636
+ entrypoints: entrypoints2,
70637
+ builder,
70638
+ duration_ms: -1
70639
+ };
70640
+ let result;
70641
+ try {
70642
+ result = await builder.build(entrypoints2);
70643
+ } catch (e) {
70644
+ result = {
70645
+ warnings: [],
70646
+ errors: [WrappedErrors.fromValue(e, "Builder failed to build")],
70647
+ watchFiles: entrypoints2.map((e2) => e2.infile),
70648
+ watchDirs: [],
70649
+ producedFiles: [],
70650
+ completed: false
70651
+ };
70652
+ } finally {
70653
+ annotations.duration_ms = Date.now() - start2;
70550
70654
  }
70551
- })().catch((e) => e)
70655
+ result = await plugins.postBuild?.(result, annotations) ?? result;
70656
+ return {
70657
+ ...result,
70658
+ ...annotations
70659
+ };
70660
+ }
70552
70661
  )
70553
70662
  );
70554
- const errors = results.filter(Boolean).concat(missingBuilders);
70555
- if (errors.length) return Promise.reject(errors);
70556
- return;
70663
+ const [rejected, fulfilled] = divide(
70664
+ results,
70665
+ (r) => r.status === "rejected"
70666
+ );
70667
+ const [uncompleted, completed] = divide(fulfilled, (r) => r.value.completed);
70668
+ const errorLogs = combineErrorLogs(
70669
+ ...uncompleted.map((r) => r.value),
70670
+ ...completed.map((r) => r.value)
70671
+ );
70672
+ const errors = [
70673
+ rejected.length ? WrappedErrors.fromValues(
70674
+ rejected.map((r) => r.reason),
70675
+ "Some builders encountered errors when running",
70676
+ {
70677
+ rejected_count: rejected.length,
70678
+ entrypoints: entrypoints.map((e) => e.infile.relative),
70679
+ builders: Array.from(grouped.keys()).map(
70680
+ ({ builder }) => builder.name
70681
+ )
70682
+ }
70683
+ ) : void 0,
70684
+ ...errorLogs.errors ?? []
70685
+ ];
70686
+ const warnings = errorLogs.warnings ?? [];
70687
+ return {
70688
+ completed: rejected.length === 0 && uncompleted.length === 0,
70689
+ errors: errors.filter(isNot.undefined),
70690
+ warnings,
70691
+ watchFiles: fulfilled.flatMap((r) => r.value.watchFiles),
70692
+ watchDirs: fulfilled.flatMap((r) => r.value.watchDirs),
70693
+ producedFiles: fulfilled.flatMap((r) => r.value.producedFiles),
70694
+ entrypoints,
70695
+ duration_ms: Date.now() - start,
70696
+ children: fulfilled.map((r) => r.value)
70697
+ };
70557
70698
  }
70558
70699
 
70559
70700
  // pnp:/builds/normed/bundle/packages/bundle/src/index.ts