aboutsummaryrefslogtreecommitdiff
path: root/src/js/internal/shared.ts
blob: 0b20572ef2e0e95e3237103e5f872053d6fbfd6a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class NotImplementedError extends Error {
  code: string;
  constructor(feature: string, issue?: number) {
    super(
      feature +
        " is not yet implemented in Bun." +
        (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : ""),
    );
    this.name = "NotImplementedError";
    this.code = "ERR_NOT_IMPLEMENTED";

    // in the definition so that it isn't bundled unless used
    hideFromStack(NotImplementedError);
  }
}

function throwNotImplemented(feature: string, issue?: number): never {
  // in the definition so that it isn't bundled unless used
  hideFromStack(throwNotImplemented);

  throw new NotImplementedError(feature, issue);
}

function hideFromStack(...fns) {
  for (const fn of fns) {
    Object.defineProperty(fn, "name", {
      value: "::bunternal::",
    });
  }
}

/**
 * This utility ensures that old JS code that uses functions for classes still works.
 * Taken from https://github.com/microsoft/vscode/blob/main/src/vs/workbench/api/common/extHostTypes.ts
 */
function es5ClassCompat(target: Function): any {
  const interceptFunctions = {
    apply: function () {
      const args = arguments.length === 1 ? [] : arguments[1];
      return Reflect.construct(target, args, arguments[0].constructor);
    },
    call: function () {
      if (arguments.length === 0) {
        return Reflect.construct(target, []);
      } else {
        const [thisArg, ...restArgs] = arguments;
        return Reflect.construct(target, restArgs, thisArg.constructor);
      }
    },
  };
  return Object.assign(target, interceptFunctions);
}

export default {
  NotImplementedError,
  throwNotImplemented,
  hideFromStack,
  es5ClassCompat,
};