summaryrefslogtreecommitdiff
path: root/cli/tsc
diff options
context:
space:
mode:
authorBartek IwaƄczuk <biwanczuk@gmail.com>2020-07-23 15:29:36 +0200
committerGitHub <noreply@github.com>2020-07-23 15:29:36 +0200
commitb449964d1a8d87d53350c0f9adcf1227e6fd3eef (patch)
treec192a67245e0b3bec7af13680f7c0bd2a134db00 /cli/tsc
parente18e46a3b3f734d1c848b80a16d11810597b49f4 (diff)
refactor: remove more compiler runtime code (#6841)
Diffstat (limited to 'cli/tsc')
-rw-r--r--cli/tsc/01_build.js26
-rw-r--r--cli/tsc/01_colors.js89
-rw-r--r--cli/tsc/01_event.js1044
-rw-r--r--cli/tsc/01_internals.js23
-rw-r--r--cli/tsc/01_version.js26
-rw-r--r--cli/tsc/01_web_util.js202
-rw-r--r--cli/tsc/02_console.js1183
-rw-r--r--cli/tsc/06_util.js101
-rw-r--r--cli/tsc/08_text_encoding.js638
-rw-r--r--cli/tsc/11_timers.js11
-rw-r--r--cli/tsc/11_workers.js231
-rw-r--r--cli/tsc/40_diagnostics.js27
-rw-r--r--cli/tsc/40_error_stack.js84
-rw-r--r--cli/tsc/40_performance.js321
-rw-r--r--cli/tsc/90_deno_ns.js13
-rw-r--r--cli/tsc/99_main.js217
-rw-r--r--cli/tsc/99_main_compiler.js117
17 files changed, 116 insertions, 4237 deletions
diff --git a/cli/tsc/01_build.js b/cli/tsc/01_build.js
deleted file mode 100644
index 7c1dc817e..000000000
--- a/cli/tsc/01_build.js
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- const build = {
- target: "unknown",
- arch: "unknown",
- os: "unknown",
- vendor: "unknown",
- env: undefined,
- };
-
- function setBuildInfo(target) {
- const [arch, vendor, os, env] = target.split("-", 4);
- build.target = target;
- build.arch = arch;
- build.vendor = vendor;
- build.os = os;
- build.env = env;
- Object.freeze(build);
- }
-
- window.__bootstrap.build = {
- build,
- setBuildInfo,
- };
-})(this);
diff --git a/cli/tsc/01_colors.js b/cli/tsc/01_colors.js
deleted file mode 100644
index 2dc559186..000000000
--- a/cli/tsc/01_colors.js
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- function code(open, close) {
- return {
- open: `\x1b[${open}m`,
- close: `\x1b[${close}m`,
- regexp: new RegExp(`\\x1b\\[${close}m`, "g"),
- };
- }
-
- function run(str, code) {
- return !globalThis || !globalThis.Deno || globalThis.Deno.noColor
- ? str
- : `${code.open}${str.replace(code.regexp, code.open)}${code.close}`;
- }
-
- function bold(str) {
- return run(str, code(1, 22));
- }
-
- function italic(str) {
- return run(str, code(3, 23));
- }
-
- function yellow(str) {
- return run(str, code(33, 39));
- }
-
- function cyan(str) {
- return run(str, code(36, 39));
- }
-
- function red(str) {
- return run(str, code(31, 39));
- }
-
- function green(str) {
- return run(str, code(32, 39));
- }
-
- function bgRed(str) {
- return run(str, code(41, 49));
- }
-
- function white(str) {
- return run(str, code(37, 39));
- }
-
- function gray(str) {
- return run(str, code(90, 39));
- }
-
- function magenta(str) {
- return run(str, code(35, 39));
- }
-
- function dim(str) {
- return run(str, code(2, 22));
- }
-
- // https://github.com/chalk/ansi-regex/blob/2b56fb0c7a07108e5b54241e8faec160d393aedb/index.js
- const ANSI_PATTERN = new RegExp(
- [
- "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
- "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
- ].join("|"),
- "g",
- );
-
- function stripColor(string) {
- return string.replace(ANSI_PATTERN, "");
- }
-
- window.__bootstrap.colors = {
- bold,
- italic,
- yellow,
- cyan,
- red,
- green,
- bgRed,
- white,
- gray,
- magenta,
- dim,
- stripColor,
- };
-})(this);
diff --git a/cli/tsc/01_event.js b/cli/tsc/01_event.js
deleted file mode 100644
index 35967e0a1..000000000
--- a/cli/tsc/01_event.js
+++ /dev/null
@@ -1,1044 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-// This module follows most of the WHATWG Living Standard for the DOM logic.
-// Many parts of the DOM are not implemented in Deno, but the logic for those
-// parts still exists. This means you will observe a lot of strange structures
-// and impossible logic branches based on what Deno currently supports.
-
-((window) => {
- const eventData = new WeakMap();
-
- function requiredArguments(
- name,
- length,
- required,
- ) {
- if (length < required) {
- const errMsg = `${name} requires at least ${required} argument${
- required === 1 ? "" : "s"
- }, but only ${length} present`;
- throw new TypeError(errMsg);
- }
- }
-
- // accessors for non runtime visible data
-
- function getDispatched(event) {
- return Boolean(eventData.get(event)?.dispatched);
- }
-
- function getPath(event) {
- return eventData.get(event)?.path ?? [];
- }
-
- function getStopImmediatePropagation(event) {
- return Boolean(eventData.get(event)?.stopImmediatePropagation);
- }
-
- function setCurrentTarget(
- event,
- value,
- ) {
- event.currentTarget = value;
- }
-
- function setDispatched(event, value) {
- const data = eventData.get(event);
- if (data) {
- data.dispatched = value;
- }
- }
-
- function setEventPhase(event, value) {
- event.eventPhase = value;
- }
-
- function setInPassiveListener(event, value) {
- const data = eventData.get(event);
- if (data) {
- data.inPassiveListener = value;
- }
- }
-
- function setPath(event, value) {
- const data = eventData.get(event);
- if (data) {
- data.path = value;
- }
- }
-
- function setRelatedTarget(
- event,
- value,
- ) {
- if ("relatedTarget" in event) {
- event.relatedTarget = value;
- }
- }
-
- function setTarget(event, value) {
- event.target = value;
- }
-
- function setStopImmediatePropagation(
- event,
- value,
- ) {
- const data = eventData.get(event);
- if (data) {
- data.stopImmediatePropagation = value;
- }
- }
-
- // Type guards that widen the event type
-
- function hasRelatedTarget(
- event,
- ) {
- return "relatedTarget" in event;
- }
-
- function isTrusted() {
- return eventData.get(this).isTrusted;
- }
-
- class Event {
- #canceledFlag = false;
- #stopPropagationFlag = false;
- #attributes = {};
-
- constructor(type, eventInitDict = {}) {
- requiredArguments("Event", arguments.length, 1);
- type = String(type);
- this.#attributes = {
- type,
- bubbles: eventInitDict.bubbles ?? false,
- cancelable: eventInitDict.cancelable ?? false,
- composed: eventInitDict.composed ?? false,
- currentTarget: null,
- eventPhase: Event.NONE,
- target: null,
- timeStamp: Date.now(),
- };
- eventData.set(this, {
- dispatched: false,
- inPassiveListener: false,
- isTrusted: false,
- path: [],
- stopImmediatePropagation: false,
- });
- Reflect.defineProperty(this, "isTrusted", {
- enumerable: true,
- get: isTrusted,
- });
- }
-
- get bubbles() {
- return this.#attributes.bubbles;
- }
-
- get cancelBubble() {
- return this.#stopPropagationFlag;
- }
-
- set cancelBubble(value) {
- this.#stopPropagationFlag = value;
- }
-
- get cancelable() {
- return this.#attributes.cancelable;
- }
-
- get composed() {
- return this.#attributes.composed;
- }
-
- get currentTarget() {
- return this.#attributes.currentTarget;
- }
-
- set currentTarget(value) {
- this.#attributes = {
- type: this.type,
- bubbles: this.bubbles,
- cancelable: this.cancelable,
- composed: this.composed,
- currentTarget: value,
- eventPhase: this.eventPhase,
- target: this.target,
- timeStamp: this.timeStamp,
- };
- }
-
- get defaultPrevented() {
- return this.#canceledFlag;
- }
-
- get eventPhase() {
- return this.#attributes.eventPhase;
- }
-
- set eventPhase(value) {
- this.#attributes = {
- type: this.type,
- bubbles: this.bubbles,
- cancelable: this.cancelable,
- composed: this.composed,
- currentTarget: this.currentTarget,
- eventPhase: value,
- target: this.target,
- timeStamp: this.timeStamp,
- };
- }
-
- get initialized() {
- return true;
- }
-
- get target() {
- return this.#attributes.target;
- }
-
- set target(value) {
- this.#attributes = {
- type: this.type,
- bubbles: this.bubbles,
- cancelable: this.cancelable,
- composed: this.composed,
- currentTarget: this.currentTarget,
- eventPhase: this.eventPhase,
- target: value,
- timeStamp: this.timeStamp,
- };
- }
-
- get timeStamp() {
- return this.#attributes.timeStamp;
- }
-
- get type() {
- return this.#attributes.type;
- }
-
- composedPath() {
- const path = eventData.get(this).path;
- if (path.length === 0) {
- return [];
- }
-
- if (!this.currentTarget) {
- throw new Error("assertion error");
- }
- const composedPath = [
- {
- item: this.currentTarget,
- itemInShadowTree: false,
- relatedTarget: null,
- rootOfClosedTree: false,
- slotInClosedTree: false,
- target: null,
- touchTargetList: [],
- },
- ];
-
- let currentTargetIndex = 0;
- let currentTargetHiddenSubtreeLevel = 0;
-
- for (let index = path.length - 1; index >= 0; index--) {
- const { item, rootOfClosedTree, slotInClosedTree } = path[index];
-
- if (rootOfClosedTree) {
- currentTargetHiddenSubtreeLevel++;
- }
-
- if (item === this.currentTarget) {
- currentTargetIndex = index;
- break;
- }
-
- if (slotInClosedTree) {
- currentTargetHiddenSubtreeLevel--;
- }
- }
-
- let currentHiddenLevel = currentTargetHiddenSubtreeLevel;
- let maxHiddenLevel = currentTargetHiddenSubtreeLevel;
-
- for (let i = currentTargetIndex - 1; i >= 0; i--) {
- const { item, rootOfClosedTree, slotInClosedTree } = path[i];
-
- if (rootOfClosedTree) {
- currentHiddenLevel++;
- }
-
- if (currentHiddenLevel <= maxHiddenLevel) {
- composedPath.unshift({
- item,
- itemInShadowTree: false,
- relatedTarget: null,
- rootOfClosedTree: false,
- slotInClosedTree: false,
- target: null,
- touchTargetList: [],
- });
- }
-
- if (slotInClosedTree) {
- currentHiddenLevel--;
-
- if (currentHiddenLevel < maxHiddenLevel) {
- maxHiddenLevel = currentHiddenLevel;
- }
- }
- }
-
- currentHiddenLevel = currentTargetHiddenSubtreeLevel;
- maxHiddenLevel = currentTargetHiddenSubtreeLevel;
-
- for (let index = currentTargetIndex + 1; index < path.length; index++) {
- const { item, rootOfClosedTree, slotInClosedTree } = path[index];
-
- if (slotInClosedTree) {
- currentHiddenLevel++;
- }
-
- if (currentHiddenLevel <= maxHiddenLevel) {
- composedPath.push({
- item,
- itemInShadowTree: false,
- relatedTarget: null,
- rootOfClosedTree: false,
- slotInClosedTree: false,
- target: null,
- touchTargetList: [],
- });
- }
-
- if (rootOfClosedTree) {
- currentHiddenLevel--;
-
- if (currentHiddenLevel < maxHiddenLevel) {
- maxHiddenLevel = currentHiddenLevel;
- }
- }
- }
- return composedPath.map((p) => p.item);
- }
-
- preventDefault() {
- if (this.cancelable && !eventData.get(this).inPassiveListener) {
- this.#canceledFlag = true;
- }
- }
-
- stopPropagation() {
- this.#stopPropagationFlag = true;
- }
-
- stopImmediatePropagation() {
- this.#stopPropagationFlag = true;
- eventData.get(this).stopImmediatePropagation = true;
- }
-
- get NONE() {
- return Event.NONE;
- }
-
- get CAPTURING_PHASE() {
- return Event.CAPTURING_PHASE;
- }
-
- get AT_TARGET() {
- return Event.AT_TARGET;
- }
-
- get BUBBLING_PHASE() {
- return Event.BUBBLING_PHASE;
- }
-
- static get NONE() {
- return 0;
- }
-
- static get CAPTURING_PHASE() {
- return 1;
- }
-
- static get AT_TARGET() {
- return 2;
- }
-
- static get BUBBLING_PHASE() {
- return 3;
- }
- }
-
- function defineEnumerableProps(
- Ctor,
- props,
- ) {
- for (const prop of props) {
- Reflect.defineProperty(Ctor.prototype, prop, { enumerable: true });
- }
- }
-
- defineEnumerableProps(Event, [
- "bubbles",
- "cancelable",
- "composed",
- "currentTarget",
- "defaultPrevented",
- "eventPhase",
- "target",
- "timeStamp",
- "type",
- ]);
-
- // This is currently the only node type we are using, so instead of implementing
- // the whole of the Node interface at the moment, this just gives us the one
- // value to power the standards based logic
- const DOCUMENT_FRAGMENT_NODE = 11;
-
- // DOM Logic Helper functions and type guards
-
- /** Get the parent node, for event targets that have a parent.
- *
- * Ref: https://dom.spec.whatwg.org/#get-the-parent */
- function getParent(eventTarget) {
- return isNode(eventTarget) ? eventTarget.parentNode : null;
- }
-
- function getRoot(eventTarget) {
- return isNode(eventTarget)
- ? eventTarget.getRootNode({ composed: true })
- : null;
- }
-
- function isNode(
- eventTarget,
- ) {
- return Boolean(eventTarget && "nodeType" in eventTarget);
- }
-
- // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor
- function isShadowInclusiveAncestor(
- ancestor,
- node,
- ) {
- while (isNode(node)) {
- if (node === ancestor) {
- return true;
- }
-
- if (isShadowRoot(node)) {
- node = node && getHost(node);
- } else {
- node = getParent(node);
- }
- }
-
- return false;
- }
-
- function isShadowRoot(nodeImpl) {
- return Boolean(
- nodeImpl &&
- isNode(nodeImpl) &&
- nodeImpl.nodeType === DOCUMENT_FRAGMENT_NODE &&
- getHost(nodeImpl) != null,
- );
- }
-
- function isSlotable(
- nodeImpl,
- ) {
- return Boolean(isNode(nodeImpl) && "assignedSlot" in nodeImpl);
- }
-
- // DOM Logic functions
-
- /** Append a path item to an event's path.
- *
- * Ref: https://dom.spec.whatwg.org/#concept-event-path-append
- */
- function appendToEventPath(
- eventImpl,
- target,
- targetOverride,
- relatedTarget,
- touchTargets,
- slotInClosedTree,
- ) {
- const itemInShadowTree = isNode(target) && isShadowRoot(getRoot(target));
- const rootOfClosedTree = isShadowRoot(target) &&
- getMode(target) === "closed";
-
- getPath(eventImpl).push({
- item: target,
- itemInShadowTree,
- target: targetOverride,
- relatedTarget,
- touchTargetList: touchTargets,
- rootOfClosedTree,
- slotInClosedTree,
- });
- }
-
- function dispatch(
- targetImpl,
- eventImpl,
- targetOverride,
- ) {
- let clearTargets = false;
- let activationTarget = null;
-
- setDispatched(eventImpl, true);
-
- targetOverride = targetOverride ?? targetImpl;
- const eventRelatedTarget = hasRelatedTarget(eventImpl)
- ? eventImpl.relatedTarget
- : null;
- let relatedTarget = retarget(eventRelatedTarget, targetImpl);
-
- if (targetImpl !== relatedTarget || targetImpl === eventRelatedTarget) {
- const touchTargets = [];
-
- appendToEventPath(
- eventImpl,
- targetImpl,
- targetOverride,
- relatedTarget,
- touchTargets,
- false,
- );
-
- const isActivationEvent = eventImpl.type === "click";
-
- if (isActivationEvent && getHasActivationBehavior(targetImpl)) {
- activationTarget = targetImpl;
- }
-
- let slotInClosedTree = false;
- let slotable = isSlotable(targetImpl) && getAssignedSlot(targetImpl)
- ? targetImpl
- : null;
- let parent = getParent(targetImpl);
-
- // Populate event path
- // https://dom.spec.whatwg.org/#event-path
- while (parent !== null) {
- if (slotable !== null) {
- slotable = null;
-
- const parentRoot = getRoot(parent);
- if (
- isShadowRoot(parentRoot) &&
- parentRoot &&
- getMode(parentRoot) === "closed"
- ) {
- slotInClosedTree = true;
- }
- }
-
- relatedTarget = retarget(eventRelatedTarget, parent);
-
- if (
- isNode(parent) &&
- isShadowInclusiveAncestor(getRoot(targetImpl), parent)
- ) {
- appendToEventPath(
- eventImpl,
- parent,
- null,
- relatedTarget,
- touchTargets,
- slotInClosedTree,
- );
- } else if (parent === relatedTarget) {
- parent = null;
- } else {
- targetImpl = parent;
-
- if (
- isActivationEvent &&
- activationTarget === null &&
- getHasActivationBehavior(targetImpl)
- ) {
- activationTarget = targetImpl;
- }
-
- appendToEventPath(
- eventImpl,
- parent,
- targetImpl,
- relatedTarget,
- touchTargets,
- slotInClosedTree,
- );
- }
-
- if (parent !== null) {
- parent = getParent(parent);
- }
-
- slotInClosedTree = false;
- }
-
- let clearTargetsTupleIndex = -1;
- const path = getPath(eventImpl);
- for (
- let i = path.length - 1;
- i >= 0 && clearTargetsTupleIndex === -1;
- i--
- ) {
- if (path[i].target !== null) {
- clearTargetsTupleIndex = i;
- }
- }
- const clearTargetsTuple = path[clearTargetsTupleIndex];
-
- clearTargets = (isNode(clearTargetsTuple.target) &&
- isShadowRoot(getRoot(clearTargetsTuple.target))) ||
- (isNode(clearTargetsTuple.relatedTarget) &&
- isShadowRoot(getRoot(clearTargetsTuple.relatedTarget)));
-
- setEventPhase(eventImpl, Event.CAPTURING_PHASE);
-
- for (let i = path.length - 1; i >= 0; --i) {
- const tuple = path[i];
-
- if (tuple.target === null) {
- invokeEventListeners(tuple, eventImpl);
- }
- }
-
- for (let i = 0; i < path.length; i++) {
- const tuple = path[i];
-
- if (tuple.target !== null) {
- setEventPhase(eventImpl, Event.AT_TARGET);
- } else {
- setEventPhase(eventImpl, Event.BUBBLING_PHASE);
- }
-
- if (
- (eventImpl.eventPhase === Event.BUBBLING_PHASE &&
- eventImpl.bubbles) ||
- eventImpl.eventPhase === Event.AT_TARGET
- ) {
- invokeEventListeners(tuple, eventImpl);
- }
- }
- }
-
- setEventPhase(eventImpl, Event.NONE);
- setCurrentTarget(eventImpl, null);
- setPath(eventImpl, []);
- setDispatched(eventImpl, false);
- eventImpl.cancelBubble = false;
- setStopImmediatePropagation(eventImpl, false);
-
- if (clearTargets) {
- setTarget(eventImpl, null);
- setRelatedTarget(eventImpl, null);
- }
-
- // TODO: invoke activation targets if HTML nodes will be implemented
- // if (activationTarget !== null) {
- // if (!eventImpl.defaultPrevented) {
- // activationTarget._activationBehavior();
- // }
- // }
-
- return !eventImpl.defaultPrevented;
- }
-
- /** Inner invoking of the event listeners where the resolved listeners are
- * called.
- *
- * Ref: https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke */
- function innerInvokeEventListeners(
- eventImpl,
- targetListeners,
- ) {
- let found = false;
-
- const { type } = eventImpl;
-
- if (!targetListeners || !targetListeners[type]) {
- return found;
- }
-
- // Copy event listeners before iterating since the list can be modified during the iteration.
- const handlers = targetListeners[type].slice();
-
- for (let i = 0; i < handlers.length; i++) {
- const listener = handlers[i];
-
- let capture, once, passive;
- if (typeof listener.options === "boolean") {
- capture = listener.options;
- once = false;
- passive = false;
- } else {
- capture = listener.options.capture;
- once = listener.options.once;
- passive = listener.options.passive;
- }
-
- // Check if the event listener has been removed since the listeners has been cloned.
- if (!targetListeners[type].includes(listener)) {
- continue;
- }
-
- found = true;
-
- if (
- (eventImpl.eventPhase === Event.CAPTURING_PHASE && !capture) ||
- (eventImpl.eventPhase === Event.BUBBLING_PHASE && capture)
- ) {
- continue;
- }
-
- if (once) {
- targetListeners[type].splice(
- targetListeners[type].indexOf(listener),
- 1,
- );
- }
-
- if (passive) {
- setInPassiveListener(eventImpl, true);
- }
-
- if (typeof listener.callback === "object") {
- if (typeof listener.callback.handleEvent === "function") {
- listener.callback.handleEvent(eventImpl);
- }
- } else {
- listener.callback.call(eventImpl.currentTarget, eventImpl);
- }
-
- setInPassiveListener(eventImpl, false);
-
- if (getStopImmediatePropagation(eventImpl)) {
- return found;
- }
- }
-
- return found;
- }
-
- /** Invokes the listeners on a given event path with the supplied event.
- *
- * Ref: https://dom.spec.whatwg.org/#concept-event-listener-invoke */
- function invokeEventListeners(tuple, eventImpl) {
- const path = getPath(eventImpl);
- const tupleIndex = path.indexOf(tuple);
- for (let i = tupleIndex; i >= 0; i--) {
- const t = path[i];
- if (t.target) {
- setTarget(eventImpl, t.target);
- break;
- }
- }
-
- setRelatedTarget(eventImpl, tuple.relatedTarget);
-
- if (eventImpl.cancelBubble) {
- return;
- }
-
- setCurrentTarget(eventImpl, tuple.item);
-
- innerInvokeEventListeners(eventImpl, getListeners(tuple.item));
- }
-
- function normalizeAddEventHandlerOptions(
- options,
- ) {
- if (typeof options === "boolean" || typeof options === "undefined") {
- return {
- capture: Boolean(options),
- once: false,
- passive: false,
- };
- } else {
- return options;
- }
- }
-
- function normalizeEventHandlerOptions(
- options,
- ) {
- if (typeof options === "boolean" || typeof options === "undefined") {
- return {
- capture: Boolean(options),
- };
- } else {
- return options;
- }
- }
-
- /** Retarget the target following the spec logic.
- *
- * Ref: https://dom.spec.whatwg.org/#retarget */
- function retarget(a, b) {
- while (true) {
- if (!isNode(a)) {
- return a;
- }
-
- const aRoot = a.getRootNode();
-
- if (aRoot) {
- if (
- !isShadowRoot(aRoot) ||
- (isNode(b) && isShadowInclusiveAncestor(aRoot, b))
- ) {
- return a;
- }
-
- a = getHost(aRoot);
- }
- }
- }
-
- // Accessors for non-public data
-
- const eventTargetData = new WeakMap();
-
- function setEventTargetData(value) {
- eventTargetData.set(value, getDefaultTargetData());
- }
-
- function getAssignedSlot(target) {
- return Boolean(eventTargetData.get(target)?.assignedSlot);
- }
-
- function getHasActivationBehavior(target) {
- return Boolean(
- eventTargetData.get(target)?.hasActivationBehavior,
- );
- }
-
- function getHost(target) {
- return eventTargetData.get(target)?.host ?? null;
- }
-
- function getListeners(target) {
- return eventTargetData.get(target)?.listeners ?? {};
- }
-
- function getMode(target) {
- return eventTargetData.get(target)?.mode ?? null;
- }
-
- function getDefaultTargetData() {
- return {
- assignedSlot: false,
- hasActivationBehavior: false,
- host: null,
- listeners: Object.create(null),
- mode: "",
- };
- }
-
- class EventTarget {
- constructor() {
- eventTargetData.set(this, getDefaultTargetData());
- }
-
- addEventListener(
- type,
- callback,
- options,
- ) {
- requiredArguments("EventTarget.addEventListener", arguments.length, 2);
- if (callback === null) {
- return;
- }
-
- options = normalizeAddEventHandlerOptions(options);
- const { listeners } = eventTargetData.get(this ?? globalThis);
-
- if (!(type in listeners)) {
- listeners[type] = [];
- }
-
- for (const listener of listeners[type]) {
- if (
- ((typeof listener.options === "boolean" &&
- listener.options === options.capture) ||
- (typeof listener.options === "object" &&
- listener.options.capture === options.capture)) &&
- listener.callback === callback
- ) {
- return;
- }
- }
-
- listeners[type].push({ callback, options });
- }
-
- removeEventListener(
- type,
- callback,
- options,
- ) {
- requiredArguments("EventTarget.removeEventListener", arguments.length, 2);
-
- const listeners = eventTargetData.get(this ?? globalThis).listeners;
- if (callback !== null && type in listeners) {
- listeners[type] = listeners[type].filter(
- (listener) => listener.callback !== callback,
- );
- } else if (callback === null || !listeners[type]) {
- return;
- }
-
- options = normalizeEventHandlerOptions(options);
-
- for (let i = 0; i < listeners[type].length; ++i) {
- const listener = listeners[type][i];
- if (
- ((typeof listener.options === "boolean" &&
- listener.options === options.capture) ||
- (typeof listener.options === "object" &&
- listener.options.capture === options.capture)) &&
- listener.callback === callback
- ) {
- listeners[type].splice(i, 1);
- break;
- }
- }
- }
-
- dispatchEvent(event) {
- requiredArguments("EventTarget.dispatchEvent", arguments.length, 1);
- const self = this ?? globalThis;
-
- const listeners = eventTargetData.get(self).listeners;
- if (!(event.type in listeners)) {
- return true;
- }
-
- if (getDispatched(event)) {
- throw new DOMException("Invalid event state.", "InvalidStateError");
- }
-
- if (event.eventPhase !== Event.NONE) {
- throw new DOMException("Invalid event state.", "InvalidStateError");
- }
-
- return dispatch(self, event);
- }
-
- get [Symbol.toStringTag]() {
- return "EventTarget";
- }
-
- getParent(_event) {
- return null;
- }
- }
-
- defineEnumerableProps(EventTarget, [
- "addEventListener",
- "removeEventListener",
- "dispatchEvent",
- ]);
-
- class ErrorEvent extends Event {
- #message = "";
- #filename = "";
- #lineno = "";
- #colno = "";
- #error = "";
-
- get message() {
- return this.#message;
- }
- get filename() {
- return this.#filename;
- }
- get lineno() {
- return this.#lineno;
- }
- get colno() {
- return this.#colno;
- }
- get error() {
- return this.#error;
- }
-
- constructor(
- type,
- {
- bubbles,
- cancelable,
- composed,
- message = "",
- filename = "",
- lineno = 0,
- colno = 0,
- error = null,
- } = {},
- ) {
- super(type, {
- bubbles: bubbles,
- cancelable: cancelable,
- composed: composed,
- });
-
- this.#message = message;
- this.#filename = filename;
- this.#lineno = lineno;
- this.#colno = colno;
- this.#error = error;
- }
-
- get [Symbol.toStringTag]() {
- return "ErrorEvent";
- }
- }
-
- defineEnumerableProps(ErrorEvent, [
- "message",
- "filename",
- "lineno",
- "colno",
- "error",
- ]);
-
- class CustomEvent extends Event {
- #detail = null;
-
- constructor(type, eventInitDict = {}) {
- super(type, eventInitDict);
- requiredArguments("CustomEvent", arguments.length, 1);
- const { detail } = eventInitDict;
- this.#detail = detail;
- }
-
- get detail() {
- return this.#detail;
- }
-
- get [Symbol.toStringTag]() {
- return "CustomEvent";
- }
- }
-
- Reflect.defineProperty(CustomEvent.prototype, "detail", {
- enumerable: true,
- });
-
- window.Event = Event;
- window.EventTarget = EventTarget;
- window.ErrorEvent = ErrorEvent;
- window.CustomEvent = CustomEvent;
- window.__bootstrap.eventTarget = {
- setEventTargetData,
- };
-})(this);
diff --git a/cli/tsc/01_internals.js b/cli/tsc/01_internals.js
deleted file mode 100644
index eee9eeaf7..000000000
--- a/cli/tsc/01_internals.js
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- const internalSymbol = Symbol("Deno.internal");
-
- // The object where all the internal fields for testing will be living.
- const internalObject = {};
-
- // Register a field to internalObject for test access,
- // through Deno[Deno.internal][name].
- function exposeForTest(name, value) {
- Object.defineProperty(internalObject, name, {
- value,
- enumerable: false,
- });
- }
-
- window.__bootstrap.internals = {
- internalSymbol,
- internalObject,
- exposeForTest,
- };
-})(this);
diff --git a/cli/tsc/01_version.js b/cli/tsc/01_version.js
deleted file mode 100644
index 325e1156f..000000000
--- a/cli/tsc/01_version.js
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- const version = {
- deno: "",
- v8: "",
- typescript: "",
- };
-
- function setVersions(
- denoVersion,
- v8Version,
- tsVersion,
- ) {
- version.deno = denoVersion;
- version.v8 = v8Version;
- version.typescript = tsVersion;
-
- Object.freeze(version);
- }
-
- window.__bootstrap.version = {
- version,
- setVersions,
- };
-})(this);
diff --git a/cli/tsc/01_web_util.js b/cli/tsc/01_web_util.js
deleted file mode 100644
index 596dcbfcd..000000000
--- a/cli/tsc/01_web_util.js
+++ /dev/null
@@ -1,202 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- function isTypedArray(x) {
- return ArrayBuffer.isView(x) && !(x instanceof DataView);
- }
-
- function isInvalidDate(x) {
- return isNaN(x.getTime());
- }
-
- function requiredArguments(
- name,
- length,
- required,
- ) {
- if (length < required) {
- const errMsg = `${name} requires at least ${required} argument${
- required === 1 ? "" : "s"
- }, but only ${length} present`;
- throw new TypeError(errMsg);
- }
- }
-
- function immutableDefine(
- o,
- p,
- value,
- ) {
- Object.defineProperty(o, p, {
- value,
- configurable: false,
- writable: false,
- });
- }
-
- function hasOwnProperty(obj, v) {
- if (obj == null) {
- return false;
- }
- return Object.prototype.hasOwnProperty.call(obj, v);
- }
-
- /** Returns whether o is iterable. */
- function isIterable(
- o,
- ) {
- // checks for null and undefined
- if (o == null) {
- return false;
- }
- return (
- typeof (o)[Symbol.iterator] === "function"
- );
- }
-
- const objectCloneMemo = new WeakMap();
-
- function cloneArrayBuffer(
- srcBuffer,
- srcByteOffset,
- srcLength,
- _cloneConstructor,
- ) {
- // this function fudges the return type but SharedArrayBuffer is disabled for a while anyway
- return srcBuffer.slice(
- srcByteOffset,
- srcByteOffset + srcLength,
- );
- }
-
- /** Clone a value in a similar way to structured cloning. It is similar to a
- * StructureDeserialize(StructuredSerialize(...)). */
- function cloneValue(value) {
- switch (typeof value) {
- case "number":
- case "string":
- case "boolean":
- case "undefined":
- case "bigint":
- return value;
- case "object": {
- if (objectCloneMemo.has(value)) {
- return objectCloneMemo.get(value);
- }
- if (value === null) {
- return value;
- }
- if (value instanceof Date) {
- return new Date(value.valueOf());
- }
- if (value instanceof RegExp) {
- return new RegExp(value);
- }
- if (value instanceof SharedArrayBuffer) {
- return value;
- }
- if (value instanceof ArrayBuffer) {
- const cloned = cloneArrayBuffer(
- value,
- 0,
- value.byteLength,
- ArrayBuffer,
- );
- objectCloneMemo.set(value, cloned);
- return cloned;
- }
- if (ArrayBuffer.isView(value)) {
- const clonedBuffer = cloneValue(value.buffer);
- // Use DataViewConstructor type purely for type-checking, can be a
- // DataView or TypedArray. They use the same constructor signature,
- // only DataView has a length in bytes and TypedArrays use a length in
- // terms of elements, so we adjust for that.
- let length;
- if (value instanceof DataView) {
- length = value.byteLength;
- } else {
- length = value.length;
- }
- return new (value.constructor)(
- clonedBuffer,
- value.byteOffset,
- length,
- );
- }
- if (value instanceof Map) {
- const clonedMap = new Map();
- objectCloneMemo.set(value, clonedMap);
- value.forEach((v, k) => clonedMap.set(k, cloneValue(v)));
- return clonedMap;
- }
- if (value instanceof Set) {
- const clonedSet = new Map();
- objectCloneMemo.set(value, clonedSet);
- value.forEach((v, k) => clonedSet.set(k, cloneValue(v)));
- return clonedSet;
- }
-
- const clonedObj = {};
- objectCloneMemo.set(value, clonedObj);
- const sourceKeys = Object.getOwnPropertyNames(value);
- for (const key of sourceKeys) {
- clonedObj[key] = cloneValue(value[key]);
- }
- return clonedObj;
- }
- case "symbol":
- case "function":
- default:
- throw new DOMException("Uncloneable value in stream", "DataCloneError");
- }
- }
-
- /** A helper function which ensures accessors are enumerable, as they normally
- * are not. */
- function defineEnumerableProps(
- Ctor,
- props,
- ) {
- for (const prop of props) {
- Reflect.defineProperty(Ctor.prototype, prop, { enumerable: true });
- }
- }
-
- function getHeaderValueParams(value) {
- const params = new Map();
- // Forced to do so for some Map constructor param mismatch
- value
- .split(";")
- .slice(1)
- .map((s) => s.trim().split("="))
- .filter((arr) => arr.length > 1)
- .map(([k, v]) => [k, v.replace(/^"([^"]*)"$/, "$1")])
- .forEach(([k, v]) => params.set(k, v));
- return params;
- }
-
- function hasHeaderValueOf(s, value) {
- return new RegExp(`^${value}[\t\s]*;?`).test(s);
- }
-
- /** An internal function which provides a function name for some generated
- * functions, so stack traces are a bit more readable.
- */
- function setFunctionName(fn, value) {
- Object.defineProperty(fn, "name", { value, configurable: true });
- }
-
- window.__bootstrap.webUtil = {
- isTypedArray,
- isInvalidDate,
- requiredArguments,
- immutableDefine,
- hasOwnProperty,
- isIterable,
- cloneValue,
- defineEnumerableProps,
- getHeaderValueParams,
- hasHeaderValueOf,
- setFunctionName,
- };
-})(this);
diff --git a/cli/tsc/02_console.js b/cli/tsc/02_console.js
deleted file mode 100644
index 5a9dd4186..000000000
--- a/cli/tsc/02_console.js
+++ /dev/null
@@ -1,1183 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- const exposeForTest = window.__bootstrap.internals.exposeForTest;
- const {
- stripColor,
- yellow,
- dim,
- cyan,
- red,
- green,
- magenta,
- bold,
- } = window.__bootstrap.colors;
-
- const {
- isTypedArray,
- isInvalidDate,
- hasOwnProperty,
- } = window.__bootstrap.webUtil;
-
- // Copyright Joyent, Inc. and other Node contributors. MIT license.
- // Forked from Node's lib/internal/cli_table.js
-
- const tableChars = {
- middleMiddle: "─",
- rowMiddle: "┌",
- topRight: "┐",
- topLeft: "┌",
- leftMiddle: "├",
- topMiddle: "┬",
- bottomRight: "┘",
- bottomLeft: "└",
- bottomMiddle: "┮",
- rightMiddle: "─",
- left: "│ ",
- right: " │",
- middle: " │ ",
- };
-
- function isFullWidthCodePoint(code) {
- // Code points are partially derived from:
- // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt
- return (
- code >= 0x1100 &&
- (code <= 0x115f || // Hangul Jamo
- code === 0x2329 || // LEFT-POINTING ANGLE BRACKET
- code === 0x232a || // RIGHT-POINTING ANGLE BRACKET
- // CJK Radicals Supplement .. Enclosed CJK Letters and Months
- (code >= 0x2e80 && code <= 0x3247 && code !== 0x303f) ||
- // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
- (code >= 0x3250 && code <= 0x4dbf) ||
- // CJK Unified Ideographs .. Yi Radicals
- (code >= 0x4e00 && code <= 0xa4c6) ||
- // Hangul Jamo Extended-A
- (code >= 0xa960 && code <= 0xa97c) ||
- // Hangul Syllables
- (code >= 0xac00 && code <= 0xd7a3) ||
- // CJK Compatibility Ideographs
- (code >= 0xf900 && code <= 0xfaff) ||
- // Vertical Forms
- (code >= 0xfe10 && code <= 0xfe19) ||
- // CJK Compatibility Forms .. Small Form Variants
- (code >= 0xfe30 && code <= 0xfe6b) ||
- // Halfwidth and Fullwidth Forms
- (code >= 0xff01 && code <= 0xff60) ||
- (code >= 0xffe0 && code <= 0xffe6) ||
- // Kana Supplement
- (code >= 0x1b000 && code <= 0x1b001) ||
- // Enclosed Ideographic Supplement
- (code >= 0x1f200 && code <= 0x1f251) ||
- // Miscellaneous Symbols and Pictographs 0x1f300 - 0x1f5ff
- // Emoticons 0x1f600 - 0x1f64f
- (code >= 0x1f300 && code <= 0x1f64f) ||
- // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
- (code >= 0x20000 && code <= 0x3fffd))
- );
- }
-
- function getStringWidth(str) {
- str = stripColor(str).normalize("NFC");
- let width = 0;
-
- for (const ch of str) {
- width += isFullWidthCodePoint(ch.codePointAt(0)) ? 2 : 1;
- }
-
- return width;
- }
-
- function renderRow(row, columnWidths) {
- let out = tableChars.left;
- for (let i = 0; i < row.length; i++) {
- const cell = row[i];
- const len = getStringWidth(cell);
- const needed = (columnWidths[i] - len) / 2;
- // round(needed) + ceil(needed) will always add up to the amount
- // of spaces we need while also left justifying the output.
- out += `${" ".repeat(needed)}${cell}${" ".repeat(Math.ceil(needed))}`;
- if (i !== row.length - 1) {
- out += tableChars.middle;
- }
- }
- out += tableChars.right;
- return out;
- }
-
- function cliTable(head, columns) {
- const rows = [];
- const columnWidths = head.map((h) => getStringWidth(h));
- const longestColumn = columns.reduce(
- (n, a) => Math.max(n, a.length),
- 0,
- );
-
- for (let i = 0; i < head.length; i++) {
- const column = columns[i];
- for (let j = 0; j < longestColumn; j++) {
- if (rows[j] === undefined) {
- rows[j] = [];
- }
- const value = (rows[j][i] = hasOwnProperty(column, j) ? column[j] : "");
- const width = columnWidths[i] || 0;
- const counted = getStringWidth(value);
- columnWidths[i] = Math.max(width, counted);
- }
- }
-
- const divider = columnWidths.map((i) =>
- tableChars.middleMiddle.repeat(i + 2)
- );
-
- let result = `${tableChars.topLeft}${divider.join(tableChars.topMiddle)}` +
- `${tableChars.topRight}\n${renderRow(head, columnWidths)}\n` +
- `${tableChars.leftMiddle}${divider.join(tableChars.rowMiddle)}` +
- `${tableChars.rightMiddle}\n`;
-
- for (const row of rows) {
- result += `${renderRow(row, columnWidths)}\n`;
- }
-
- result +=
- `${tableChars.bottomLeft}${divider.join(tableChars.bottomMiddle)}` +
- tableChars.bottomRight;
-
- return result;
- }
- /* End of forked part */
-
- const DEFAULT_INSPECT_OPTIONS = {
- depth: 4,
- indentLevel: 0,
- sorted: false,
- trailingComma: false,
- compact: true,
- iterableLimit: 100,
- };
-
- const DEFAULT_INDENT = " "; // Default indent string
-
- const LINE_BREAKING_LENGTH = 80;
- const MIN_GROUP_LENGTH = 6;
- const STR_ABBREVIATE_SIZE = 100;
- // Char codes
- const CHAR_PERCENT = 37; /* % */
- const CHAR_LOWERCASE_S = 115; /* s */
- const CHAR_LOWERCASE_D = 100; /* d */
- const CHAR_LOWERCASE_I = 105; /* i */
- const CHAR_LOWERCASE_F = 102; /* f */
- const CHAR_LOWERCASE_O = 111; /* o */
- const CHAR_UPPERCASE_O = 79; /* O */
- const CHAR_LOWERCASE_C = 99; /* c */
-
- const PROMISE_STRING_BASE_LENGTH = 12;
-
- class CSI {
- static kClear = "\x1b[1;1H";
- static kClearScreenDown = "\x1b[0J";
- }
-
- /* eslint-disable @typescript-eslint/no-use-before-define */
-
- function getClassInstanceName(instance) {
- if (typeof instance !== "object") {
- return "";
- }
- if (!instance) {
- return "";
- }
-
- const proto = Object.getPrototypeOf(instance);
- if (proto && proto.constructor) {
- return proto.constructor.name; // could be "Object" or "Array"
- }
-
- return "";
- }
-
- function inspectFunction(value, _ctx) {
- // Might be Function/AsyncFunction/GeneratorFunction
- const cstrName = Object.getPrototypeOf(value).constructor.name;
- if (value.name && value.name !== "anonymous") {
- // from MDN spec
- return `[${cstrName}: ${value.name}]`;
- }
- return `[${cstrName}]`;
- }
-
- function inspectIterable(
- value,
- ctx,
- level,
- options,
- inspectOptions,
- ) {
- if (level >= inspectOptions.depth) {
- return cyan(`[${options.typeName}]`);
- }
- ctx.add(value);
-
- const entries = [];
-
- const iter = value.entries();
- let entriesLength = 0;
- const next = () => {
- return iter.next();
- };
- for (const el of iter) {
- if (entriesLength < inspectOptions.iterableLimit) {
- entries.push(
- options.entryHandler(
- el,
- ctx,
- level + 1,
- inspectOptions,
- next.bind(iter),
- ),
- );
- }
- entriesLength++;
- }
- ctx.delete(value);
-
- if (options.sort) {
- entries.sort();
- }
-
- if (entriesLength > inspectOptions.iterableLimit) {
- const nmore = entriesLength - inspectOptions.iterableLimit;
- entries.push(`... ${nmore} more items`);
- }
-
- const iPrefix = `${options.displayName ? options.displayName + " " : ""}`;
-
- const initIndentation = `\n${DEFAULT_INDENT.repeat(level + 1)}`;
- const entryIndentation = `,\n${DEFAULT_INDENT.repeat(level + 1)}`;
- const closingIndentation = `${inspectOptions.trailingComma ? "," : ""}\n${
- DEFAULT_INDENT.repeat(level)
- }`;
-
- let iContent;
- if (options.group && entries.length > MIN_GROUP_LENGTH) {
- const groups = groupEntries(entries, level, value);
- iContent = `${initIndentation}${
- groups.join(entryIndentation)
- }${closingIndentation}`;
- } else {
- iContent = entries.length === 0 ? "" : ` ${entries.join(", ")} `;
- if (
- stripColor(iContent).length > LINE_BREAKING_LENGTH ||
- !inspectOptions.compact
- ) {
- iContent = `${initIndentation}${
- entries.join(entryIndentation)
- }${closingIndentation}`;
- }
- }
-
- return `${iPrefix}${options.delims[0]}${iContent}${options.delims[1]}`;
- }
-
- // Ported from Node.js
- // Copyright Node.js contributors. All rights reserved.
- function groupEntries(
- entries,
- level,
- value,
- iterableLimit = 100,
- ) {
- let totalLength = 0;
- let maxLength = 0;
- let entriesLength = entries.length;
- if (iterableLimit < entriesLength) {
- // This makes sure the "... n more items" part is not taken into account.
- entriesLength--;
- }
- const separatorSpace = 2; // Add 1 for the space and 1 for the separator.
- const dataLen = new Array(entriesLength);
- // Calculate the total length of all output entries and the individual max
- // entries length of all output entries.
- // IN PROGRESS: Colors are being taken into account.
- for (let i = 0; i < entriesLength; i++) {
- // Taking colors into account: removing the ANSI color
- // codes from the string before measuring its length
- const len = stripColor(entries[i]).length;
- dataLen[i] = len;
- totalLength += len + separatorSpace;
- if (maxLength < len) maxLength = len;
- }
- // Add two to `maxLength` as we add a single whitespace character plus a comma
- // in-between two entries.
- const actualMax = maxLength + separatorSpace;
- // Check if at least three entries fit next to each other and prevent grouping
- // of arrays that contains entries of very different length (i.e., if a single
- // entry is longer than 1/5 of all other entries combined). Otherwise the
- // space in-between small entries would be enormous.
- if (
- actualMax * 3 + (level + 1) < LINE_BREAKING_LENGTH &&
- (totalLength / actualMax > 5 || maxLength <= 6)
- ) {
- const approxCharHeights = 2.5;
- const averageBias = Math.sqrt(actualMax - totalLength / entries.length);
- const biasedMax = Math.max(actualMax - 3 - averageBias, 1);
- // Dynamically check how many columns seem possible.
- const columns = Math.min(
- // Ideally a square should be drawn. We expect a character to be about 2.5
- // times as high as wide. This is the area formula to calculate a square
- // which contains n rectangles of size `actualMax * approxCharHeights`.
- // Divide that by `actualMax` to receive the correct number of columns.
- // The added bias increases the columns for short entries.
- Math.round(
- Math.sqrt(approxCharHeights * biasedMax * entriesLength) / biasedMax,
- ),
- // Do not exceed the breakLength.
- Math.floor((LINE_BREAKING_LENGTH - (level + 1)) / actualMax),
- // Limit the columns to a maximum of fifteen.
- 15,
- );
- // Return with the original output if no grouping should happen.
- if (columns <= 1) {
- return entries;
- }
- const tmp = [];
- const maxLineLength = [];
- for (let i = 0; i < columns; i++) {
- let lineMaxLength = 0;
- for (let j = i; j < entries.length; j += columns) {
- if (dataLen[j] > lineMaxLength) lineMaxLength = dataLen[j];
- }
- lineMaxLength += separatorSpace;
- maxLineLength[i] = lineMaxLength;
- }
- let order = "padStart";
- if (value !== undefined) {
- for (let i = 0; i < entries.length; i++) {
- /* eslint-disable @typescript-eslint/no-explicit-any */
- if (
- typeof value[i] !== "number" &&
- typeof value[i] !== "bigint"
- ) {
- order = "padEnd";
- break;
- }
- /* eslint-enable */
- }
- }
- // Each iteration creates a single line of grouped entries.
- for (let i = 0; i < entriesLength; i += columns) {
- // The last lines may contain less entries than columns.
- const max = Math.min(i + columns, entriesLength);
- let str = "";
- let j = i;
- for (; j < max - 1; j++) {
- // In future, colors should be taken here into the account
- const padding = maxLineLength[j - i];
- str += `${entries[j]}, `[order](padding, " ");
- }
- if (order === "padStart") {
- const padding = maxLineLength[j - i] +
- entries[j].length -
- dataLen[j] -
- separatorSpace;
- str += entries[j].padStart(padding, " ");
- } else {
- str += entries[j];
- }
- tmp.push(str);
- }
- if (iterableLimit < entries.length) {
- tmp.push(entries[entriesLength]);
- }
- entries = tmp;
- }
- return entries;
- }
-
- function inspectValue(
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- switch (typeof value) {
- case "string":
- return value;
- case "number": // Numbers are yellow
- // Special handling of -0
- return yellow(Object.is(value, -0) ? "-0" : `${value}`);
- case "boolean": // booleans are yellow
- return yellow(String(value));
- case "undefined": // undefined is dim
- return dim(String(value));
- case "symbol": // Symbols are green
- return green(String(value));
- case "bigint": // Bigints are yellow
- return yellow(`${value}n`);
- case "function": // Function string is cyan
- return cyan(inspectFunction(value, ctx));
- case "object": // null is bold
- if (value === null) {
- return bold("null");
- }
-
- if (ctx.has(value)) {
- // Circular string is cyan
- return cyan("[Circular]");
- }
-
- return inspectObject(value, ctx, level, inspectOptions);
- default:
- // Not implemented is red
- return red("[Not Implemented]");
- }
- }
-
- // We can match Node's quoting behavior exactly by swapping the double quote and
- // single quote in this array. That would give preference to single quotes.
- // However, we prefer double quotes as the default.
- const QUOTES = ['"', "'", "`"];
-
- /** Surround the string in quotes.
- *
- * The quote symbol is chosen by taking the first of the `QUOTES` array which
- * does not occur in the string. If they all occur, settle with `QUOTES[0]`.
- *
- * Insert a backslash before any occurrence of the chosen quote symbol and
- * before any backslash. */
- function quoteString(string) {
- const quote = QUOTES.find((c) => !string.includes(c)) ?? QUOTES[0];
- const escapePattern = new RegExp(`(?=[${quote}\\\\])`, "g");
- return `${quote}${string.replace(escapePattern, "\\")}${quote}`;
- }
-
- // Print strings when they are inside of arrays or objects with quotes
- function inspectValueWithQuotes(
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- switch (typeof value) {
- case "string":
- const trunc = value.length > STR_ABBREVIATE_SIZE
- ? value.slice(0, STR_ABBREVIATE_SIZE) + "..."
- : value;
- return green(quoteString(trunc)); // Quoted strings are green
- default:
- return inspectValue(value, ctx, level, inspectOptions);
- }
- }
-
- function inspectArray(
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- const options = {
- typeName: "Array",
- displayName: "",
- delims: ["[", "]"],
- entryHandler: (entry, ctx, level, inspectOptions, next) => {
- const [index, val] = entry;
- let i = index;
- if (!value.hasOwnProperty(i)) {
- i++;
- while (!value.hasOwnProperty(i) && i < value.length) {
- next();
- i++;
- }
- const emptyItems = i - index;
- const ending = emptyItems > 1 ? "s" : "";
- return dim(`<${emptyItems} empty item${ending}>`);
- } else {
- return inspectValueWithQuotes(val, ctx, level, inspectOptions);
- }
- },
- group: inspectOptions.compact,
- sort: false,
- };
- return inspectIterable(value, ctx, level, options, inspectOptions);
- }
-
- function inspectTypedArray(
- typedArrayName,
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- const valueLength = value.length;
- const options = {
- typeName: typedArrayName,
- displayName: `${typedArrayName}(${valueLength})`,
- delims: ["[", "]"],
- entryHandler: (entry, ctx, level, inspectOptions) => {
- const val = entry[1];
- return inspectValueWithQuotes(val, ctx, level + 1, inspectOptions);
- },
- group: inspectOptions.compact,
- sort: false,
- };
- return inspectIterable(value, ctx, level, options, inspectOptions);
- }
-
- function inspectSet(
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- const options = {
- typeName: "Set",
- displayName: "Set",
- delims: ["{", "}"],
- entryHandler: (entry, ctx, level, inspectOptions) => {
- const val = entry[1];
- return inspectValueWithQuotes(val, ctx, level + 1, inspectOptions);
- },
- group: false,
- sort: inspectOptions.sorted,
- };
- return inspectIterable(value, ctx, level, options, inspectOptions);
- }
-
- function inspectMap(
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- const options = {
- typeName: "Map",
- displayName: "Map",
- delims: ["{", "}"],
- entryHandler: (entry, ctx, level, inspectOptions) => {
- const [key, val] = entry;
- return `${
- inspectValueWithQuotes(
- key,
- ctx,
- level + 1,
- inspectOptions,
- )
- } => ${inspectValueWithQuotes(val, ctx, level + 1, inspectOptions)}`;
- },
- group: false,
- sort: inspectOptions.sorted,
- };
- return inspectIterable(
- value,
- ctx,
- level,
- options,
- inspectOptions,
- );
- }
-
- function inspectWeakSet() {
- return `WeakSet { ${cyan("[items unknown]")} }`; // as seen in Node, with cyan color
- }
-
- function inspectWeakMap() {
- return `WeakMap { ${cyan("[items unknown]")} }`; // as seen in Node, with cyan color
- }
-
- function inspectDate(value) {
- // without quotes, ISO format, in magenta like before
- return magenta(isInvalidDate(value) ? "Invalid Date" : value.toISOString());
- }
-
- function inspectRegExp(value) {
- return red(value.toString()); // RegExps are red
- }
-
- function inspectStringObject(value) {
- return cyan(`[String: "${value.toString()}"]`); // wrappers are in cyan
- }
-
- function inspectBooleanObject(value) {
- return cyan(`[Boolean: ${value.toString()}]`); // wrappers are in cyan
- }
-
- function inspectNumberObject(value) {
- return cyan(`[Number: ${value.toString()}]`); // wrappers are in cyan
- }
-
- const PromiseState = {
- Pending: 0,
- Fulfilled: 1,
- Rejected: 2,
- };
-
- function inspectPromise(
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- const [state, result] = Deno.core.getPromiseDetails(value);
-
- if (state === PromiseState.Pending) {
- return `Promise { ${cyan("<pending>")} }`;
- }
-
- const prefix = state === PromiseState.Fulfilled
- ? ""
- : `${red("<rejected>")} `;
-
- const str = `${prefix}${
- inspectValueWithQuotes(
- result,
- ctx,
- level + 1,
- inspectOptions,
- )
- }`;
-
- if (str.length + PROMISE_STRING_BASE_LENGTH > LINE_BREAKING_LENGTH) {
- return `Promise {\n${DEFAULT_INDENT.repeat(level + 1)}${str}\n}`;
- }
-
- return `Promise { ${str} }`;
- }
-
- // TODO: Proxy
-
- function inspectRawObject(
- value,
- ctx,
- level,
- inspectOptions,
- ) {
- if (level >= inspectOptions.depth) {
- return cyan("[Object]"); // wrappers are in cyan
- }
- ctx.add(value);
-
- let baseString;
-
- let shouldShowDisplayName = false;
- let displayName = value[
- Symbol.toStringTag
- ];
- if (!displayName) {
- displayName = getClassInstanceName(value);
- }
- if (
- displayName && displayName !== "Object" && displayName !== "anonymous"
- ) {
- shouldShowDisplayName = true;
- }
-
- const entries = [];
- const stringKeys = Object.keys(value);
- const symbolKeys = Object.getOwnPropertySymbols(value);
- if (inspectOptions.sorted) {
- stringKeys.sort();
- symbolKeys.sort((s1, s2) =>
- (s1.description ?? "").localeCompare(s2.description ?? "")
- );
- }
-
- for (const key of stringKeys) {
- entries.push(
- `${key}: ${
- inspectValueWithQuotes(
- value[key],
- ctx,
- level + 1,
- inspectOptions,
- )
- }`,
- );
- }
- for (const key of symbolKeys) {
- entries.push(
- `${key.toString()}: ${
- inspectValueWithQuotes(
- value[key],
- ctx,
- level + 1,
- inspectOptions,
- )
- }`,
- );
- }
- // Making sure color codes are ignored when calculating the total length
- const totalLength = entries.length + level +
- stripColor(entries.join("")).length;
-
- ctx.delete(value);
-
- if (entries.length === 0) {
- baseString = "{}";
- } else if (totalLength > LINE_BREAKING_LENGTH || !inspectOptions.compact) {
- const entryIndent = DEFAULT_INDENT.repeat(level + 1);
- const closingIndent = DEFAULT_INDENT.repeat(level);
- baseString = `{\n${entryIndent}${entries.join(`,\n${entryIndent}`)}${
- inspectOptions.trailingComma ? "," : ""
- }\n${closingIndent}}`;
- } else {
- baseString = `{ ${entries.join(", ")} }`;
- }
-
- if (shouldShowDisplayName) {
- baseString = `${displayName} ${baseString}`;
- }
-
- return baseString;
- }
-
- function inspectObject(
- value,
- consoleContext,
- level,
- inspectOptions,
- ) {
- if (customInspect in value && typeof value[customInspect] === "function") {
- try {
- return String(value[customInspect]());
- } catch {}
- }
- if (value instanceof Error) {
- return String(value.stack);
- } else if (Array.isArray(value)) {
- return inspectArray(value, consoleContext, level, inspectOptions);
- } else if (value instanceof Number) {
- return inspectNumberObject(value);
- } else if (value instanceof Boolean) {
- return inspectBooleanObject(value);
- } else if (value instanceof String) {
- return inspectStringObject(value);
- } else if (value instanceof Promise) {
- return inspectPromise(value, consoleContext, level, inspectOptions);
- } else if (value instanceof RegExp) {
- return inspectRegExp(value);
- } else if (value instanceof Date) {
- return inspectDate(value);
- } else if (value instanceof Set) {
- return inspectSet(value, consoleContext, level, inspectOptions);
- } else if (value instanceof Map) {
- return inspectMap(value, consoleContext, level, inspectOptions);
- } else if (value instanceof WeakSet) {
- return inspectWeakSet();
- } else if (value instanceof WeakMap) {
- return inspectWeakMap();
- } else if (isTypedArray(value)) {
- return inspectTypedArray(
- Object.getPrototypeOf(value).constructor.name,
- value,
- consoleContext,
- level,
- inspectOptions,
- );
- } else {
- // Otherwise, default object formatting
- return inspectRawObject(value, consoleContext, level, inspectOptions);
- }
- }
-
- function inspectArgs(
- args,
- inspectOptions = {},
- ) {
- const rInspectOptions = { ...DEFAULT_INSPECT_OPTIONS, ...inspectOptions };
- const first = args[0];
- let a = 0;
- let str = "";
- let join = "";
-
- if (typeof first === "string") {
- let tempStr;
- let lastPos = 0;
-
- for (let i = 0; i < first.length - 1; i++) {
- if (first.charCodeAt(i) === CHAR_PERCENT) {
- const nextChar = first.charCodeAt(++i);
- if (a + 1 !== args.length) {
- switch (nextChar) {
- case CHAR_LOWERCASE_S:
- // format as a string
- tempStr = String(args[++a]);
- break;
- case CHAR_LOWERCASE_D:
- case CHAR_LOWERCASE_I:
- // format as an integer
- const tempInteger = args[++a];
- if (typeof tempInteger === "bigint") {
- tempStr = `${tempInteger}n`;
- } else if (typeof tempInteger === "symbol") {
- tempStr = "NaN";
- } else {
- tempStr = `${parseInt(String(tempInteger), 10)}`;
- }
- break;
- case CHAR_LOWERCASE_F:
- // format as a floating point value
- const tempFloat = args[++a];
- if (typeof tempFloat === "symbol") {
- tempStr = "NaN";
- } else {
- tempStr = `${parseFloat(String(tempFloat))}`;
- }
- break;
- case CHAR_LOWERCASE_O:
- case CHAR_UPPERCASE_O:
- // format as an object
- tempStr = inspectValue(
- args[++a],
- new Set(),
- 0,
- rInspectOptions,
- );
- break;
- case CHAR_PERCENT:
- str += first.slice(lastPos, i);
- lastPos = i + 1;
- continue;
- case CHAR_LOWERCASE_C:
- // TODO: applies CSS style rules to the output string as specified
- continue;
- default:
- // any other character is not a correct placeholder
- continue;
- }
-
- if (lastPos !== i - 1) {
- str += first.slice(lastPos, i - 1);
- }
-
- str += tempStr;
- lastPos = i + 1;
- } else if (nextChar === CHAR_PERCENT) {
- str += first.slice(lastPos, i);
- lastPos = i + 1;
- }
- }
- }
-
- if (lastPos !== 0) {
- a++;
- join = " ";
- if (lastPos < first.length) {
- str += first.slice(lastPos);
- }
- }
- }
-
- while (a < args.length) {
- const value = args[a];
- str += join;
- if (typeof value === "string") {
- str += value;
- } else {
- // use default maximum depth for null or undefined argument
- str += inspectValue(value, new Set(), 0, rInspectOptions);
- }
- join = " ";
- a++;
- }
-
- if (rInspectOptions.indentLevel > 0) {
- const groupIndent = DEFAULT_INDENT.repeat(rInspectOptions.indentLevel);
- if (str.indexOf("\n") !== -1) {
- str = str.replace(/\n/g, `\n${groupIndent}`);
- }
- str = groupIndent + str;
- }
-
- return str;
- }
-
- const countMap = new Map();
- const timerMap = new Map();
- const isConsoleInstance = Symbol("isConsoleInstance");
-
- class Console {
- #printFunc = null;
- [isConsoleInstance] = false;
-
- constructor(printFunc) {
- this.#printFunc = printFunc;
- this.indentLevel = 0;
- this[isConsoleInstance] = true;
-
- // ref https://console.spec.whatwg.org/#console-namespace
- // For historical web-compatibility reasons, the namespace object for
- // console must have as its [[Prototype]] an empty object, created as if
- // by ObjectCreate(%ObjectPrototype%), instead of %ObjectPrototype%.
- const console = Object.create({});
- Object.assign(console, this);
- return console;
- }
-
- log = (...args) => {
- this.#printFunc(
- inspectArgs(args, {
- indentLevel: this.indentLevel,
- }) + "\n",
- false,
- );
- };
-
- debug = this.log;
- info = this.log;
-
- dir = (obj, options = {}) => {
- this.#printFunc(inspectArgs([obj], options) + "\n", false);
- };
-
- dirxml = this.dir;
-
- warn = (...args) => {
- this.#printFunc(
- inspectArgs(args, {
- indentLevel: this.indentLevel,
- }) + "\n",
- true,
- );
- };
-
- error = this.warn;
-
- assert = (condition = false, ...args) => {
- if (condition) {
- return;
- }
-
- if (args.length === 0) {
- this.error("Assertion failed");
- return;
- }
-
- const [first, ...rest] = args;
-
- if (typeof first === "string") {
- this.error(`Assertion failed: ${first}`, ...rest);
- return;
- }
-
- this.error(`Assertion failed:`, ...args);
- };
-
- count = (label = "default") => {
- label = String(label);
-
- if (countMap.has(label)) {
- const current = countMap.get(label) || 0;
- countMap.set(label, current + 1);
- } else {
- countMap.set(label, 1);
- }
-
- this.info(`${label}: ${countMap.get(label)}`);
- };
-
- countReset = (label = "default") => {
- label = String(label);
-
- if (countMap.has(label)) {
- countMap.set(label, 0);
- } else {
- this.warn(`Count for '${label}' does not exist`);
- }
- };
-
- table = (data, properties) => {
- if (properties !== undefined && !Array.isArray(properties)) {
- throw new Error(
- "The 'properties' argument must be of type Array. " +
- "Received type string",
- );
- }
-
- if (data === null || typeof data !== "object") {
- return this.log(data);
- }
-
- const objectValues = {};
- const indexKeys = [];
- const values = [];
-
- const stringifyValue = (value) =>
- inspectValueWithQuotes(value, new Set(), 0, {
- ...DEFAULT_INSPECT_OPTIONS,
- depth: 1,
- });
- const toTable = (header, body) => this.log(cliTable(header, body));
- const createColumn = (value, shift) => [
- ...(shift ? [...new Array(shift)].map(() => "") : []),
- stringifyValue(value),
- ];
-
- let resultData;
- const isSet = data instanceof Set;
- const isMap = data instanceof Map;
- const valuesKey = "Values";
- const indexKey = isSet || isMap ? "(iter idx)" : "(idx)";
-
- if (data instanceof Set) {
- resultData = [...data];
- } else if (data instanceof Map) {
- let idx = 0;
- resultData = {};
-
- data.forEach((v, k) => {
- resultData[idx] = { Key: k, Values: v };
- idx++;
- });
- } else {
- resultData = data;
- }
-
- let hasPrimitives = false;
- Object.keys(resultData).forEach((k, idx) => {
- const value = resultData[k];
- const primitive = value === null ||
- (typeof value !== "function" && typeof value !== "object");
- if (properties === undefined && primitive) {
- hasPrimitives = true;
- values.push(stringifyValue(value));
- } else {
- const valueObj = value || {};
- const keys = properties || Object.keys(valueObj);
- for (const k of keys) {
- if (primitive || !valueObj.hasOwnProperty(k)) {
- if (objectValues[k]) {
- // fill with blanks for idx to avoid misplacing from later values
- objectValues[k].push("");
- }
- } else {
- if (objectValues[k]) {
- objectValues[k].push(stringifyValue(valueObj[k]));
- } else {
- objectValues[k] = createColumn(valueObj[k], idx);
- }
- }
- }
- values.push("");
- }
-
- indexKeys.push(k);
- });
-
- const headerKeys = Object.keys(objectValues);
- const bodyValues = Object.values(objectValues);
- const header = [
- indexKey,
- ...(properties ||
- [...headerKeys, !isMap && hasPrimitives && valuesKey]),
- ].filter(Boolean);
- const body = [indexKeys, ...bodyValues, values];
-
- toTable(header, body);
- };
-
- time = (label = "default") => {
- label = String(label);
-
- if (timerMap.has(label)) {
- this.warn(`Timer '${label}' already exists`);
- return;
- }
-
- timerMap.set(label, Date.now());
- };
-
- timeLog = (label = "default", ...args) => {
- label = String(label);
-
- if (!timerMap.has(label)) {
- this.warn(`Timer '${label}' does not exists`);
- return;
- }
-
- const startTime = timerMap.get(label);
- const duration = Date.now() - startTime;
-
- this.info(`${label}: ${duration}ms`, ...args);
- };
-
- timeEnd = (label = "default") => {
- label = String(label);
-
- if (!timerMap.has(label)) {
- this.warn(`Timer '${label}' does not exists`);
- return;
- }
-
- const startTime = timerMap.get(label);
- timerMap.delete(label);
- const duration = Date.now() - startTime;
-
- this.info(`${label}: ${duration}ms`);
- };
-
- group = (...label) => {
- if (label.length > 0) {
- this.log(...label);
- }
- this.indentLevel += 2;
- };
-
- groupCollapsed = this.group;
-
- groupEnd = () => {
- if (this.indentLevel > 0) {
- this.indentLevel -= 2;
- }
- };
-
- clear = () => {
- this.indentLevel = 0;
- this.#printFunc(CSI.kClear, false);
- this.#printFunc(CSI.kClearScreenDown, false);
- };
-
- trace = (...args) => {
- const message = inspectArgs(args, { indentLevel: 0 });
- const err = {
- name: "Trace",
- message,
- };
- Error.captureStackTrace(err, this.trace);
- this.error(err.stack);
- };
-
- static [Symbol.hasInstance](instance) {
- return instance[isConsoleInstance];
- }
- }
-
- const customInspect = Symbol("Deno.customInspect");
-
- function inspect(
- value,
- inspectOptions = {},
- ) {
- if (typeof value === "string") {
- return value;
- } else {
- return inspectValue(value, new Set(), 0, {
- ...DEFAULT_INSPECT_OPTIONS,
- ...inspectOptions,
- // TODO(nayeemrmn): Indent level is not supported.
- indentLevel: 0,
- });
- }
- }
-
- // Expose these fields to internalObject for tests.
- exposeForTest("Console", Console);
- exposeForTest("inspectArgs", inspectArgs);
-
- window.__bootstrap.console = {
- CSI,
- inspectArgs,
- Console,
- customInspect,
- inspect,
- };
-})(this);
diff --git a/cli/tsc/06_util.js b/cli/tsc/06_util.js
index 086275bd8..b6a582f9e 100644
--- a/cli/tsc/06_util.js
+++ b/cli/tsc/06_util.js
@@ -1,8 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
((window) => {
- const { build } = window.__bootstrap.build;
- const internals = window.__bootstrap.internals;
+ const core = Deno.core;
let logDebug = false;
let logSource = "JS";
@@ -15,9 +14,8 @@
function log(...args) {
if (logDebug) {
- // if we destructure `console` off `globalThis` too early, we don't bind to
- // the right console, therefore we don't log anything out.
- globalThis.console.log(`DEBUG ${logSource} -`, ...args);
+ const stringifiedArgs = args.map(JSON.stringify).join(" ");
+ core.print(`DEBUG ${logSource} - ${stringifiedArgs}\n`);
}
}
@@ -50,93 +48,6 @@
throw new Error("not implemented");
}
- function immutableDefine(
- o,
- p,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- value,
- ) {
- Object.defineProperty(o, p, {
- value,
- configurable: false,
- writable: false,
- });
- }
-
- function pathFromURLWin32(url) {
- const hostname = url.hostname;
- const pathname = decodeURIComponent(url.pathname.replace(/\//g, "\\"));
-
- if (hostname !== "") {
- //TODO(actual-size) Node adds a punycode decoding step, we should consider adding this
- return `\\\\${hostname}${pathname}`;
- }
-
- const validPath = /^\\(?<driveLetter>[A-Za-z]):\\/;
- const matches = validPath.exec(pathname);
-
- if (!matches?.groups?.driveLetter) {
- throw new TypeError("A URL with the file schema must be absolute.");
- }
-
- // we don't want a leading slash on an absolute path in Windows
- return pathname.slice(1);
- }
-
- function pathFromURLPosix(url) {
- if (url.hostname !== "") {
- throw new TypeError(`Host must be empty.`);
- }
-
- return decodeURIComponent(url.pathname);
- }
-
- function pathFromURL(pathOrUrl) {
- if (pathOrUrl instanceof URL) {
- if (pathOrUrl.protocol != "file:") {
- throw new TypeError("Must be a file URL.");
- }
-
- return build.os == "windows"
- ? pathFromURLWin32(pathOrUrl)
- : pathFromURLPosix(pathOrUrl);
- }
- return pathOrUrl;
- }
-
- internals.exposeForTest("pathFromURL", pathFromURL);
-
- function writable(value) {
- return {
- value,
- writable: true,
- enumerable: true,
- configurable: true,
- };
- }
-
- function nonEnumerable(value) {
- return {
- value,
- writable: true,
- configurable: true,
- };
- }
-
- function readOnly(value) {
- return {
- value,
- enumerable: true,
- };
- }
-
- function getterOnly(getter) {
- return {
- get: getter,
- enumerable: true,
- };
- }
-
window.__bootstrap.util = {
log,
setLogDebug,
@@ -144,11 +55,5 @@
createResolvable,
assert,
AssertionError,
- immutableDefine,
- pathFromURL,
- writable,
- nonEnumerable,
- readOnly,
- getterOnly,
};
})(this);
diff --git a/cli/tsc/08_text_encoding.js b/cli/tsc/08_text_encoding.js
deleted file mode 100644
index 1aa5d43c0..000000000
--- a/cli/tsc/08_text_encoding.js
+++ /dev/null
@@ -1,638 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-// The following code is based off of text-encoding at:
-// https://github.com/inexorabletash/text-encoding
-//
-// Anyone is free to copy, modify, publish, use, compile, sell, or
-// distribute this software, either in source code form or as a compiled
-// binary, for any purpose, commercial or non-commercial, and by any
-// means.
-//
-// In jurisdictions that recognize copyright laws, the author or authors
-// of this software dedicate any and all copyright interest in the
-// software to the public domain. We make this dedication for the benefit
-// of the public at large and to the detriment of our heirs and
-// successors. We intend this dedication to be an overt act of
-// relinquishment in perpetuity of all present and future rights to this
-// software under copyright law.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
-// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-
-((window) => {
- const core = Deno.core;
-
- const CONTINUE = null;
- const END_OF_STREAM = -1;
- const FINISHED = -1;
-
- function decoderError(fatal) {
- if (fatal) {
- throw new TypeError("Decoder error.");
- }
- return 0xfffd; // default code point
- }
-
- function inRange(a, min, max) {
- return min <= a && a <= max;
- }
-
- function isASCIIByte(a) {
- return inRange(a, 0x00, 0x7f);
- }
-
- function stringToCodePoints(input) {
- const u = [];
- for (const c of input) {
- u.push(c.codePointAt(0));
- }
- return u;
- }
-
- class UTF8Encoder {
- handler(codePoint) {
- if (codePoint === END_OF_STREAM) {
- return "finished";
- }
-
- if (inRange(codePoint, 0x00, 0x7f)) {
- return [codePoint];
- }
-
- let count;
- let offset;
- if (inRange(codePoint, 0x0080, 0x07ff)) {
- count = 1;
- offset = 0xc0;
- } else if (inRange(codePoint, 0x0800, 0xffff)) {
- count = 2;
- offset = 0xe0;
- } else if (inRange(codePoint, 0x10000, 0x10ffff)) {
- count = 3;
- offset = 0xf0;
- } else {
- throw TypeError(
- `Code point out of range: \\x${codePoint.toString(16)}`,
- );
- }
-
- const bytes = [(codePoint >> (6 * count)) + offset];
-
- while (count > 0) {
- const temp = codePoint >> (6 * (count - 1));
- bytes.push(0x80 | (temp & 0x3f));
- count--;
- }
-
- return bytes;
- }
- }
-
- class SingleByteDecoder {
- #index = [];
- #fatal = false;
-
- constructor(
- index,
- { ignoreBOM = false, fatal = false } = {},
- ) {
- if (ignoreBOM) {
- throw new TypeError("Ignoring the BOM is available only with utf-8.");
- }
- this.#fatal = fatal;
- this.#index = index;
- }
- handler(_stream, byte) {
- if (byte === END_OF_STREAM) {
- return FINISHED;
- }
- if (isASCIIByte(byte)) {
- return byte;
- }
- const codePoint = this.#index[byte - 0x80];
-
- if (codePoint == null) {
- return decoderError(this.#fatal);
- }
-
- return codePoint;
- }
- }
-
- // The encodingMap is a hash of labels that are indexed by the conical
- // encoding.
- const encodingMap = {
- "windows-1252": [
- "ansi_x3.4-1968",
- "ascii",
- "cp1252",
- "cp819",
- "csisolatin1",
- "ibm819",
- "iso-8859-1",
- "iso-ir-100",
- "iso8859-1",
- "iso88591",
- "iso_8859-1",
- "iso_8859-1:1987",
- "l1",
- "latin1",
- "us-ascii",
- "windows-1252",
- "x-cp1252",
- ],
- "utf-8": ["unicode-1-1-utf-8", "utf-8", "utf8"],
- };
- // We convert these into a Map where every label resolves to its canonical
- // encoding type.
- const encodings = new Map();
- for (const key of Object.keys(encodingMap)) {
- const labels = encodingMap[key];
- for (const label of labels) {
- encodings.set(label, key);
- }
- }
-
- // A map of functions that return new instances of a decoder indexed by the
- // encoding type.
- const decoders = new Map();
-
- // Single byte decoders are an array of code point lookups
- const encodingIndexes = new Map();
- // deno-fmt-ignore
- encodingIndexes.set("windows-1252", [
- 8364,
- 129,
- 8218,
- 402,
- 8222,
- 8230,
- 8224,
- 8225,
- 710,
- 8240,
- 352,
- 8249,
- 338,
- 141,
- 381,
- 143,
- 144,
- 8216,
- 8217,
- 8220,
- 8221,
- 8226,
- 8211,
- 8212,
- 732,
- 8482,
- 353,
- 8250,
- 339,
- 157,
- 382,
- 376,
- 160,
- 161,
- 162,
- 163,
- 164,
- 165,
- 166,
- 167,
- 168,
- 169,
- 170,
- 171,
- 172,
- 173,
- 174,
- 175,
- 176,
- 177,
- 178,
- 179,
- 180,
- 181,
- 182,
- 183,
- 184,
- 185,
- 186,
- 187,
- 188,
- 189,
- 190,
- 191,
- 192,
- 193,
- 194,
- 195,
- 196,
- 197,
- 198,
- 199,
- 200,
- 201,
- 202,
- 203,
- 204,
- 205,
- 206,
- 207,
- 208,
- 209,
- 210,
- 211,
- 212,
- 213,
- 214,
- 215,
- 216,
- 217,
- 218,
- 219,
- 220,
- 221,
- 222,
- 223,
- 224,
- 225,
- 226,
- 227,
- 228,
- 229,
- 230,
- 231,
- 232,
- 233,
- 234,
- 235,
- 236,
- 237,
- 238,
- 239,
- 240,
- 241,
- 242,
- 243,
- 244,
- 245,
- 246,
- 247,
- 248,
- 249,
- 250,
- 251,
- 252,
- 253,
- 254,
- 255,
- ]);
- for (const [key, index] of encodingIndexes) {
- decoders.set(
- key,
- (options) => {
- return new SingleByteDecoder(index, options);
- },
- );
- }
-
- function codePointsToString(codePoints) {
- let s = "";
- for (const cp of codePoints) {
- s += String.fromCodePoint(cp);
- }
- return s;
- }
-
- class Stream {
- #tokens = [];
- constructor(tokens) {
- this.#tokens = [...tokens];
- this.#tokens.reverse();
- }
-
- endOfStream() {
- return !this.#tokens.length;
- }
-
- read() {
- return !this.#tokens.length ? END_OF_STREAM : this.#tokens.pop();
- }
-
- prepend(token) {
- if (Array.isArray(token)) {
- while (token.length) {
- this.#tokens.push(token.pop());
- }
- } else {
- this.#tokens.push(token);
- }
- }
-
- push(token) {
- if (Array.isArray(token)) {
- while (token.length) {
- this.#tokens.unshift(token.shift());
- }
- } else {
- this.#tokens.unshift(token);
- }
- }
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- function isEitherArrayBuffer(x) {
- return x instanceof SharedArrayBuffer || x instanceof ArrayBuffer;
- }
-
- class TextDecoder {
- #encoding = "";
-
- get encoding() {
- return this.#encoding;
- }
- fatal = false;
- ignoreBOM = false;
-
- constructor(label = "utf-8", options = { fatal: false }) {
- if (options.ignoreBOM) {
- this.ignoreBOM = true;
- }
- if (options.fatal) {
- this.fatal = true;
- }
- label = String(label).trim().toLowerCase();
- const encoding = encodings.get(label);
- if (!encoding) {
- throw new RangeError(
- `The encoding label provided ('${label}') is invalid.`,
- );
- }
- if (!decoders.has(encoding) && encoding !== "utf-8") {
- throw new TypeError(`Internal decoder ('${encoding}') not found.`);
- }
- this.#encoding = encoding;
- }
-
- decode(
- input,
- options = { stream: false },
- ) {
- if (options.stream) {
- throw new TypeError("Stream not supported.");
- }
-
- let bytes;
- if (input instanceof Uint8Array) {
- bytes = input;
- } else if (isEitherArrayBuffer(input)) {
- bytes = new Uint8Array(input);
- } else if (
- typeof input === "object" &&
- "buffer" in input &&
- isEitherArrayBuffer(input.buffer)
- ) {
- bytes = new Uint8Array(
- input.buffer,
- input.byteOffset,
- input.byteLength,
- );
- } else {
- bytes = new Uint8Array(0);
- }
-
- // For simple utf-8 decoding "Deno.core.decode" can be used for performance
- if (
- this.#encoding === "utf-8" &&
- this.fatal === false &&
- this.ignoreBOM === false
- ) {
- return core.decode(bytes);
- }
-
- // For performance reasons we utilise a highly optimised decoder instead of
- // the general decoder.
- if (this.#encoding === "utf-8") {
- return decodeUtf8(bytes, this.fatal, this.ignoreBOM);
- }
-
- const decoder = decoders.get(this.#encoding)({
- fatal: this.fatal,
- ignoreBOM: this.ignoreBOM,
- });
- const inputStream = new Stream(bytes);
- const output = [];
-
- while (true) {
- const result = decoder.handler(inputStream, inputStream.read());
- if (result === FINISHED) {
- break;
- }
-
- if (result !== CONTINUE) {
- output.push(result);
- }
- }
-
- if (output.length > 0 && output[0] === 0xfeff) {
- output.shift();
- }
-
- return codePointsToString(output);
- }
-
- get [Symbol.toStringTag]() {
- return "TextDecoder";
- }
- }
-
- class TextEncoder {
- encoding = "utf-8";
- encode(input = "") {
- // Deno.core.encode() provides very efficient utf-8 encoding
- if (this.encoding === "utf-8") {
- return core.encode(input);
- }
-
- const encoder = new UTF8Encoder();
- const inputStream = new Stream(stringToCodePoints(input));
- const output = [];
-
- while (true) {
- const result = encoder.handler(inputStream.read());
- if (result === "finished") {
- break;
- }
- output.push(...result);
- }
-
- return new Uint8Array(output);
- }
- encodeInto(input, dest) {
- const encoder = new UTF8Encoder();
- const inputStream = new Stream(stringToCodePoints(input));
-
- let written = 0;
- let read = 0;
- while (true) {
- const result = encoder.handler(inputStream.read());
- if (result === "finished") {
- break;
- }
- if (dest.length - written >= result.length) {
- read++;
- dest.set(result, written);
- written += result.length;
- if (result.length > 3) {
- // increment read a second time if greater than U+FFFF
- read++;
- }
- } else {
- break;
- }
- }
-
- return {
- read,
- written,
- };
- }
- get [Symbol.toStringTag]() {
- return "TextEncoder";
- }
- }
-
- // This function is based on Bjoern Hoehrmann's DFA UTF-8 decoder.
- // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
- //
- // Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- // SOFTWARE.
- function decodeUtf8(
- input,
- fatal,
- ignoreBOM,
- ) {
- let outString = "";
-
- // Prepare a buffer so that we don't have to do a lot of string concats, which
- // are very slow.
- const outBufferLength = Math.min(1024, input.length);
- const outBuffer = new Uint16Array(outBufferLength);
- let outIndex = 0;
-
- let state = 0;
- let codepoint = 0;
- let type;
-
- let i =
- ignoreBOM && input[0] === 0xef && input[1] === 0xbb && input[2] === 0xbf
- ? 3
- : 0;
-
- for (; i < input.length; ++i) {
- // Encoding error handling
- if (state === 12 || (state !== 0 && (input[i] & 0xc0) !== 0x80)) {
- if (fatal) {
- throw new TypeError(
- `Decoder error. Invalid byte in sequence at position ${i} in data.`,
- );
- }
- outBuffer[outIndex++] = 0xfffd; // Replacement character
- if (outIndex === outBufferLength) {
- outString += String.fromCharCode.apply(null, outBuffer);
- outIndex = 0;
- }
- state = 0;
- }
-
- // deno-fmt-ignore
- type = [
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
- 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
- 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
- 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8
- ][input[i]];
- codepoint = state !== 0
- ? (input[i] & 0x3f) | (codepoint << 6)
- : (0xff >> type) & input[i];
- // deno-fmt-ignore
- state = [
- 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
- 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
- 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
- 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
- 12,36,12,12,12,12,12,12,12,12,12,12
- ][state + type];
-
- if (state !== 0) continue;
-
- // Add codepoint to buffer (as charcodes for utf-16), and flush buffer to
- // string if needed.
- if (codepoint > 0xffff) {
- outBuffer[outIndex++] = 0xd7c0 + (codepoint >> 10);
- if (outIndex === outBufferLength) {
- outString += String.fromCharCode.apply(null, outBuffer);
- outIndex = 0;
- }
- outBuffer[outIndex++] = 0xdc00 | (codepoint & 0x3ff);
- if (outIndex === outBufferLength) {
- outString += String.fromCharCode.apply(null, outBuffer);
- outIndex = 0;
- }
- } else {
- outBuffer[outIndex++] = codepoint;
- if (outIndex === outBufferLength) {
- outString += String.fromCharCode.apply(null, outBuffer);
- outIndex = 0;
- }
- }
- }
-
- // Add a replacement character if we ended in the middle of a sequence or
- // encountered an invalid code at the end.
- if (state !== 0) {
- if (fatal) throw new TypeError(`Decoder error. Unexpected end of data.`);
- outBuffer[outIndex++] = 0xfffd; // Replacement character
- }
-
- // Final flush of buffer
- outString += String.fromCharCode.apply(
- null,
- outBuffer.subarray(0, outIndex),
- );
-
- return outString;
- }
-
- window.TextEncoder = TextEncoder;
- window.TextDecoder = TextDecoder;
-})(this);
diff --git a/cli/tsc/11_timers.js b/cli/tsc/11_timers.js
deleted file mode 100644
index 59fc0dc76..000000000
--- a/cli/tsc/11_timers.js
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- const dispatchJson = window.__bootstrap.dispatchJson;
-
- function opNow() {
- return dispatchJson.sendSync("op_now");
- }
-
- window.__bootstrap.timers = { opNow };
-})(this);
diff --git a/cli/tsc/11_workers.js b/cli/tsc/11_workers.js
deleted file mode 100644
index 8ae0d5ad5..000000000
--- a/cli/tsc/11_workers.js
+++ /dev/null
@@ -1,231 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-/* eslint-disable @typescript-eslint/no-explicit-any */
-
-((window) => {
- const { log } = window.__bootstrap.util;
- const { sendSync, sendAsync } = window.__bootstrap.dispatchJson;
- /*
- import { blobURLMap } from "./web/url.ts";
- */
-
- function createWorker(
- specifier,
- hasSourceCode,
- sourceCode,
- useDenoNamespace,
- name,
- ) {
- return sendSync("op_create_worker", {
- specifier,
- hasSourceCode,
- sourceCode,
- name,
- useDenoNamespace,
- });
- }
-
- function hostTerminateWorker(id) {
- sendSync("op_host_terminate_worker", { id });
- }
-
- function hostPostMessage(id, data) {
- sendSync("op_host_post_message", { id }, data);
- }
-
- function hostGetMessage(id) {
- return sendAsync("op_host_get_message", { id });
- }
-
- const encoder = new TextEncoder();
- const decoder = new TextDecoder();
-
- class MessageEvent extends Event {
- constructor(type, eventInitDict) {
- super(type, {
- bubbles: eventInitDict?.bubbles ?? false,
- cancelable: eventInitDict?.cancelable ?? false,
- composed: eventInitDict?.composed ?? false,
- });
-
- this.data = eventInitDict?.data ?? null;
- this.origin = eventInitDict?.origin ?? "";
- this.lastEventId = eventInitDict?.lastEventId ?? "";
- }
- }
-
- function encodeMessage(data) {
- const dataJson = JSON.stringify(data);
- return encoder.encode(dataJson);
- }
-
- function decodeMessage(dataIntArray) {
- const dataJson = decoder.decode(dataIntArray);
- return JSON.parse(dataJson);
- }
-
- class Worker extends EventTarget {
- #id = 0;
- #name = "";
- #terminated = false;
-
- constructor(specifier, options) {
- super();
- const { type = "classic", name = "unknown" } = options ?? {};
-
- if (type !== "module") {
- throw new Error(
- 'Not yet implemented: only "module" type workers are supported',
- );
- }
-
- this.#name = name;
- const hasSourceCode = false;
- const sourceCode = decoder.decode(new Uint8Array());
-
- /* TODO(bartlomieju):
- // Handle blob URL.
- if (specifier.startsWith("blob:")) {
- hasSourceCode = true;
- const b = blobURLMap.get(specifier);
- if (!b) {
- throw new Error("No Blob associated with the given URL is found");
- }
- const blobBytes = blobBytesWeakMap.get(b!);
- if (!blobBytes) {
- throw new Error("Invalid Blob");
- }
- sourceCode = blobBytes!;
- }
- */
-
- const useDenoNamespace = options ? !!options.deno : false;
-
- const { id } = createWorker(
- specifier,
- hasSourceCode,
- sourceCode,
- useDenoNamespace,
- options?.name,
- );
- this.#id = id;
- this.#poll();
- }
-
- #handleMessage = (msgData) => {
- let data;
- try {
- data = decodeMessage(new Uint8Array(msgData));
- } catch (e) {
- const msgErrorEvent = new MessageEvent("messageerror", {
- cancelable: false,
- data,
- });
- if (this.onmessageerror) {
- this.onmessageerror(msgErrorEvent);
- }
- return;
- }
-
- const msgEvent = new MessageEvent("message", {
- cancelable: false,
- data,
- });
-
- if (this.onmessage) {
- this.onmessage(msgEvent);
- }
-
- this.dispatchEvent(msgEvent);
- };
-
- #handleError = (e) => {
- const event = new ErrorEvent("error", {
- cancelable: true,
- message: e.message,
- lineno: e.lineNumber ? e.lineNumber + 1 : undefined,
- colno: e.columnNumber ? e.columnNumber + 1 : undefined,
- filename: e.fileName,
- error: null,
- });
-
- let handled = false;
- if (this.onerror) {
- this.onerror(event);
- }
-
- this.dispatchEvent(event);
- if (event.defaultPrevented) {
- handled = true;
- }
-
- return handled;
- };
-
- #poll = async () => {
- while (!this.#terminated) {
- const event = await hostGetMessage(this.#id);
-
- // If terminate was called then we ignore all messages
- if (this.#terminated) {
- return;
- }
-
- const type = event.type;
-
- if (type === "terminalError") {
- this.#terminated = true;
- if (!this.#handleError(event.error)) {
- throw Error(event.error.message);
- }
- continue;
- }
-
- if (type === "msg") {
- this.#handleMessage(event.data);
- continue;
- }
-
- if (type === "error") {
- if (!this.#handleError(event.error)) {
- throw Error(event.error.message);
- }
- continue;
- }
-
- if (type === "close") {
- log(`Host got "close" message from worker: ${this.#name}`);
- this.#terminated = true;
- return;
- }
-
- throw new Error(`Unknown worker event: "${type}"`);
- }
- };
-
- postMessage(message, transferOrOptions) {
- if (transferOrOptions) {
- throw new Error(
- "Not yet implemented: `transfer` and `options` are not supported.",
- );
- }
-
- if (this.#terminated) {
- return;
- }
-
- hostPostMessage(this.#id, encodeMessage(message));
- }
-
- terminate() {
- if (!this.#terminated) {
- this.#terminated = true;
- hostTerminateWorker(this.#id);
- }
- }
- }
-
- window.__bootstrap.worker = {
- Worker,
- MessageEvent,
- };
-})(this);
diff --git a/cli/tsc/40_diagnostics.js b/cli/tsc/40_diagnostics.js
deleted file mode 100644
index 110d3d767..000000000
--- a/cli/tsc/40_diagnostics.js
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-// Diagnostic provides an abstraction for advice/errors received from a
-// compiler, which is strongly influenced by the format of TypeScript
-// diagnostics.
-
-((window) => {
- const DiagnosticCategory = {
- 0: "Log",
- 1: "Debug",
- 2: "Info",
- 3: "Error",
- 4: "Warning",
- 5: "Suggestion",
-
- Log: 0,
- Debug: 1,
- Info: 2,
- Error: 3,
- Warning: 4,
- Suggestion: 5,
- };
-
- window.__bootstrap.diagnostics = {
- DiagnosticCategory,
- };
-})(this);
diff --git a/cli/tsc/40_error_stack.js b/cli/tsc/40_error_stack.js
index 80f4fc5ed..77321eb12 100644
--- a/cli/tsc/40_error_stack.js
+++ b/cli/tsc/40_error_stack.js
@@ -3,22 +3,19 @@
((window) => {
// Some of the code here is adapted directly from V8 and licensed under a BSD
// style license available here: https://github.com/v8/v8/blob/24886f2d1c565287d33d71e4109a53bf0b54b75c/LICENSE.v8
- const colors = window.__bootstrap.colors;
const assert = window.__bootstrap.util.assert;
- const internals = window.__bootstrap.internals;
- const dispatchJson = window.__bootstrap.dispatchJson;
- function opFormatDiagnostics(items) {
- return dispatchJson.sendSync("op_format_diagnostic", { items });
- }
-
- function opApplySourceMap(location) {
- const res = dispatchJson.sendSync("op_apply_source_map", location);
- return {
- fileName: res.fileName,
- lineNumber: res.lineNumber,
- columnNumber: res.columnNumber,
- };
+ // https://github.com/chalk/ansi-regex/blob/2b56fb0c7a07108e5b54241e8faec160d393aedb/index.js
+ const ANSI_PATTERN = new RegExp(
+ [
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
+ ].join("|"),
+ "g",
+ );
+
+ function stripColor(string) {
+ return string.replace(ANSI_PATTERN, "");
}
function patchCallSite(callSite, location) {
@@ -109,12 +106,9 @@
return result;
}
- function getFileLocation(callSite, internal = false) {
- const cyan = internal ? colors.gray : colors.cyan;
- const yellow = internal ? colors.gray : colors.yellow;
- const black = internal ? colors.gray : (s) => s;
+ function getFileLocation(callSite) {
if (callSite.isNative()) {
- return cyan("native");
+ return "native";
}
let result = "";
@@ -123,32 +117,29 @@
if (!fileName && callSite.isEval()) {
const evalOrigin = callSite.getEvalOrigin();
assert(evalOrigin != null);
- result += cyan(`${evalOrigin}, `);
+ result += `${evalOrigin}, `;
}
if (fileName) {
- result += cyan(fileName);
+ result += fileName;
} else {
- result += cyan("<anonymous>");
+ result += "<anonymous>";
}
const lineNumber = callSite.getLineNumber();
if (lineNumber != null) {
- result += `${black(":")}${yellow(lineNumber.toString())}`;
+ result += `:${lineNumber.toString()}`;
const columnNumber = callSite.getColumnNumber();
if (columnNumber != null) {
- result += `${black(":")}${yellow(columnNumber.toString())}`;
+ result += `:${columnNumber.toString()}`;
}
}
return result;
}
- function callSiteToString(callSite, internal = false) {
- const cyan = internal ? colors.gray : colors.cyan;
- const black = internal ? colors.gray : (s) => s;
-
+ function callSiteToString(callSite) {
let result = "";
const functionName = callSite.getFunctionName();
@@ -159,35 +150,29 @@
const isMethodCall = !(isTopLevel || isConstructor);
if (isAsync) {
- result += colors.gray("async ");
+ result += "async ";
}
if (isPromiseAll) {
- result += colors.bold(
- colors.italic(
- black(`Promise.all (index ${callSite.getPromiseIndex()})`),
- ),
- );
+ result += `Promise.all (index ${callSite.getPromiseIndex()})`;
return result;
}
if (isMethodCall) {
- result += colors.bold(colors.italic(black(getMethodCall(callSite))));
+ result += getMethodCall(callSite);
} else if (isConstructor) {
- result += colors.gray("new ");
+ result += "new ";
if (functionName) {
- result += colors.bold(colors.italic(black(functionName)));
+ result += functionName;
} else {
- result += cyan("<anonymous>");
+ result += "<anonymous>";
}
} else if (functionName) {
- result += colors.bold(colors.italic(black(functionName)));
+ result += functionName;
} else {
- result += getFileLocation(callSite, internal);
+ result += getFileLocation(callSite);
return result;
}
- result += ` ${black("(")}${getFileLocation(callSite, internal)}${
- black(")")
- }`;
+ result += ` (${getFileLocation(callSite)})`;
return result;
}
@@ -224,11 +209,11 @@
if (fileName && lineNumber != null && columnNumber != null) {
return patchCallSite(
callSite,
- opApplySourceMap({
+ {
fileName,
lineNumber,
columnNumber,
- }),
+ },
);
}
return callSite;
@@ -240,15 +225,14 @@
});
for (const callSite of mappedCallSites) {
error.__callSiteEvals.push(Object.freeze(evaluateCallSite(callSite)));
- const isInternal = callSite.getFileName()?.startsWith("$deno$") ?? false;
- error.__formattedFrames.push(callSiteToString(callSite, isInternal));
+ error.__formattedFrames.push(callSiteToString(callSite));
}
Object.freeze(error.__callSiteEvals);
Object.freeze(error.__formattedFrames);
return (
`${error.name}: ${error.message}\n` +
error.__formattedFrames
- .map((s) => ` at ${colors.stripColor(s)}`)
+ .map((s) => ` at ${stripColor(s)}`)
.join("\n")
);
}
@@ -257,11 +241,7 @@
ErrorConstructor.prepareStackTrace = prepareStackTrace;
}
- internals.exposeForTest("setPrepareStackTrace", setPrepareStackTrace);
-
window.__bootstrap.errorStack = {
setPrepareStackTrace,
- opApplySourceMap,
- opFormatDiagnostics,
};
})(this);
diff --git a/cli/tsc/40_performance.js b/cli/tsc/40_performance.js
deleted file mode 100644
index 768c43a6a..000000000
--- a/cli/tsc/40_performance.js
+++ /dev/null
@@ -1,321 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-((window) => {
- const { opNow } = window.__bootstrap.timers;
- const { customInspect, inspect } = window.__bootstrap.console;
- const { cloneValue } = window.__bootstrap.webUtil;
-
- let performanceEntries = [];
-
- function findMostRecent(
- name,
- type,
- ) {
- return performanceEntries
- .slice()
- .reverse()
- .find((entry) => entry.name === name && entry.entryType === type);
- }
-
- function convertMarkToTimestamp(mark) {
- if (typeof mark === "string") {
- const entry = findMostRecent(mark, "mark");
- if (!entry) {
- throw new SyntaxError(`Cannot find mark: "${mark}".`);
- }
- return entry.startTime;
- }
- if (mark < 0) {
- throw new TypeError("Mark cannot be negative.");
- }
- return mark;
- }
-
- function filterByNameType(
- name,
- type,
- ) {
- return performanceEntries.filter(
- (entry) =>
- (name ? entry.name === name : true) &&
- (type ? entry.entryType === type : true),
- );
- }
-
- function now() {
- const res = opNow();
- return res.seconds * 1e3 + res.subsecNanos / 1e6;
- }
-
- class PerformanceEntry {
- #name = "";
- #entryType = "";
- #startTime = 0;
- #duration = 0;
-
- get name() {
- return this.#name;
- }
-
- get entryType() {
- return this.#entryType;
- }
-
- get startTime() {
- return this.#startTime;
- }
-
- get duration() {
- return this.#duration;
- }
-
- constructor(
- name,
- entryType,
- startTime,
- duration,
- ) {
- this.#name = name;
- this.#entryType = entryType;
- this.#startTime = startTime;
- this.#duration = duration;
- }
-
- toJSON() {
- return {
- name: this.#name,
- entryType: this.#entryType,
- startTime: this.#startTime,
- duration: this.#duration,
- };
- }
-
- [customInspect]() {
- return `${this.constructor.name} { name: "${this.name}", entryType: "${this.entryType}", startTime: ${this.startTime}, duration: ${this.duration} }`;
- }
- }
-
- class PerformanceMark extends PerformanceEntry {
- #detail = null;
-
- get detail() {
- return this.#detail;
- }
-
- get entryType() {
- return "mark";
- }
-
- constructor(
- name,
- { detail = null, startTime = now() } = {},
- ) {
- super(name, "mark", startTime, 0);
- if (startTime < 0) {
- throw new TypeError("startTime cannot be negative");
- }
- this.#detail = cloneValue(detail);
- }
-
- toJSON() {
- return {
- name: this.name,
- entryType: this.entryType,
- startTime: this.startTime,
- duration: this.duration,
- detail: this.detail,
- };
- }
-
- [customInspect]() {
- return this.detail
- ? `${this.constructor.name} {\n detail: ${
- inspect(this.detail, { depth: 3 })
- },\n name: "${this.name}",\n entryType: "${this.entryType}",\n startTime: ${this.startTime},\n duration: ${this.duration}\n}`
- : `${this.constructor.name} { detail: ${this.detail}, name: "${this.name}", entryType: "${this.entryType}", startTime: ${this.startTime}, duration: ${this.duration} }`;
- }
- }
-
- class PerformanceMeasure extends PerformanceEntry {
- #detail = null;
-
- get detail() {
- return this.#detail;
- }
-
- get entryType() {
- return "measure";
- }
-
- constructor(
- name,
- startTime,
- duration,
- detail = null,
- ) {
- super(name, "measure", startTime, duration);
- this.#detail = cloneValue(detail);
- }
-
- toJSON() {
- return {
- name: this.name,
- entryType: this.entryType,
- startTime: this.startTime,
- duration: this.duration,
- detail: this.detail,
- };
- }
-
- [customInspect]() {
- return this.detail
- ? `${this.constructor.name} {\n detail: ${
- inspect(this.detail, { depth: 3 })
- },\n name: "${this.name}",\n entryType: "${this.entryType}",\n startTime: ${this.startTime},\n duration: ${this.duration}\n}`
- : `${this.constructor.name} { detail: ${this.detail}, name: "${this.name}", entryType: "${this.entryType}", startTime: ${this.startTime}, duration: ${this.duration} }`;
- }
- }
-
- class Performance {
- clearMarks(markName) {
- if (markName == null) {
- performanceEntries = performanceEntries.filter(
- (entry) => entry.entryType !== "mark",
- );
- } else {
- performanceEntries = performanceEntries.filter(
- (entry) => !(entry.name === markName && entry.entryType === "mark"),
- );
- }
- }
-
- clearMeasures(measureName) {
- if (measureName == null) {
- performanceEntries = performanceEntries.filter(
- (entry) => entry.entryType !== "measure",
- );
- } else {
- performanceEntries = performanceEntries.filter(
- (entry) =>
- !(entry.name === measureName && entry.entryType === "measure"),
- );
- }
- }
-
- getEntries() {
- return filterByNameType();
- }
-
- getEntriesByName(
- name,
- type,
- ) {
- return filterByNameType(name, type);
- }
-
- getEntriesByType(type) {
- return filterByNameType(undefined, type);
- }
-
- mark(
- markName,
- options = {},
- ) {
- // 3.1.1.1 If the global object is a Window object and markName uses the
- // same name as a read only attribute in the PerformanceTiming interface,
- // throw a SyntaxError. - not implemented
- const entry = new PerformanceMark(markName, options);
- // 3.1.1.7 Queue entry - not implemented
- performanceEntries.push(entry);
- return entry;
- }
-
- measure(
- measureName,
- startOrMeasureOptions = {},
- endMark,
- ) {
- if (startOrMeasureOptions && typeof startOrMeasureOptions === "object") {
- if (endMark) {
- throw new TypeError("Options cannot be passed with endMark.");
- }
- if (
- !("start" in startOrMeasureOptions) &&
- !("end" in startOrMeasureOptions)
- ) {
- throw new TypeError(
- "A start or end mark must be supplied in options.",
- );
- }
- if (
- "start" in startOrMeasureOptions &&
- "duration" in startOrMeasureOptions &&
- "end" in startOrMeasureOptions
- ) {
- throw new TypeError(
- "Cannot specify start, end, and duration together in options.",
- );
- }
- }
- let endTime;
- if (endMark) {
- endTime = convertMarkToTimestamp(endMark);
- } else if (
- typeof startOrMeasureOptions === "object" &&
- "end" in startOrMeasureOptions
- ) {
- endTime = convertMarkToTimestamp(startOrMeasureOptions.end);
- } else if (
- typeof startOrMeasureOptions === "object" &&
- "start" in startOrMeasureOptions &&
- "duration" in startOrMeasureOptions
- ) {
- const start = convertMarkToTimestamp(startOrMeasureOptions.start);
- const duration = convertMarkToTimestamp(startOrMeasureOptions.duration);
- endTime = start + duration;
- } else {
- endTime = now();
- }
- let startTime;
- if (
- typeof startOrMeasureOptions === "object" &&
- "start" in startOrMeasureOptions
- ) {
- startTime = convertMarkToTimestamp(startOrMeasureOptions.start);
- } else if (
- typeof startOrMeasureOptions === "object" &&
- "end" in startOrMeasureOptions &&
- "duration" in startOrMeasureOptions
- ) {
- const end = convertMarkToTimestamp(startOrMeasureOptions.end);
- const duration = convertMarkToTimestamp(startOrMeasureOptions.duration);
- startTime = end - duration;
- } else if (typeof startOrMeasureOptions === "string") {
- startTime = convertMarkToTimestamp(startOrMeasureOptions);
- } else {
- startTime = 0;
- }
- const entry = new PerformanceMeasure(
- measureName,
- startTime,
- endTime - startTime,
- typeof startOrMeasureOptions === "object"
- ? startOrMeasureOptions.detail ?? null
- : null,
- );
- performanceEntries.push(entry);
- return entry;
- }
-
- now() {
- return now();
- }
- }
-
- window.__bootstrap.performance = {
- PerformanceEntry,
- PerformanceMark,
- PerformanceMeasure,
- Performance,
- };
-})(this);
diff --git a/cli/tsc/90_deno_ns.js b/cli/tsc/90_deno_ns.js
deleted file mode 100644
index 0c2d4e39b..000000000
--- a/cli/tsc/90_deno_ns.js
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-// This module exports stable Deno APIs.
-
-((window) => {
- window.__bootstrap.denoNs = {
- version: window.__bootstrap.version.version,
- build: window.__bootstrap.build.build,
- errors: window.__bootstrap.errors.errors,
- customInspect: window.__bootstrap.console.customInspect,
- inspect: window.__bootstrap.console.inspect,
- };
-})(this);
diff --git a/cli/tsc/99_main.js b/cli/tsc/99_main.js
deleted file mode 100644
index 9b85e2f60..000000000
--- a/cli/tsc/99_main.js
+++ /dev/null
@@ -1,217 +0,0 @@
-// Removes the `__proto__` for security reasons. This intentionally makes
-// Deno non compliant with ECMA-262 Annex B.2.2.1
-//
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-delete Object.prototype.__proto__;
-
-((window) => {
- const core = Deno.core;
- const util = window.__bootstrap.util;
- const eventTarget = window.__bootstrap.eventTarget;
- const dispatchJson = window.__bootstrap.dispatchJson;
- const build = window.__bootstrap.build;
- const version = window.__bootstrap.version;
- const errorStack = window.__bootstrap.errorStack;
- const Console = window.__bootstrap.console.Console;
- const worker = window.__bootstrap.worker;
- const { internalSymbol, internalObject } = window.__bootstrap.internals;
- const performance = window.__bootstrap.performance;
- const crypto = window.__bootstrap.crypto;
- const denoNs = window.__bootstrap.denoNs;
-
- const encoder = new TextEncoder();
-
- function workerClose() {
- if (isClosing) {
- return;
- }
-
- isClosing = true;
- opCloseWorker();
- }
-
- // TODO(bartlomieju): remove these funtions
- // Stuff for workers
- const onmessage = () => {};
- const onerror = () => {};
-
- function postMessage(data) {
- const dataJson = JSON.stringify(data);
- const dataIntArray = encoder.encode(dataJson);
- opPostMessage(dataIntArray);
- }
-
- let isClosing = false;
- async function workerMessageRecvCallback(data) {
- const msgEvent = new worker.MessageEvent("message", {
- cancelable: false,
- data,
- });
-
- try {
- if (globalThis["onmessage"]) {
- const result = globalThis.onmessage(msgEvent);
- if (result && "then" in result) {
- await result;
- }
- }
- globalThis.dispatchEvent(msgEvent);
- } catch (e) {
- let handled = false;
-
- const errorEvent = new ErrorEvent("error", {
- cancelable: true,
- message: e.message,
- lineno: e.lineNumber ? e.lineNumber + 1 : undefined,
- colno: e.columnNumber ? e.columnNumber + 1 : undefined,
- filename: e.fileName,
- error: null,
- });
-
- if (globalThis["onerror"]) {
- const ret = globalThis.onerror(
- e.message,
- e.fileName,
- e.lineNumber,
- e.columnNumber,
- e,
- );
- handled = ret === true;
- }
-
- globalThis.dispatchEvent(errorEvent);
- if (errorEvent.defaultPrevented) {
- handled = true;
- }
-
- if (!handled) {
- throw e;
- }
- }
- }
-
- function opPostMessage(data) {
- dispatchJson.sendSync("op_worker_post_message", {}, data);
- }
-
- function opCloseWorker() {
- dispatchJson.sendSync("op_worker_close");
- }
-
- function opStart() {
- return dispatchJson.sendSync("op_start");
- }
-
- // TODO(bartlomieju): temporary solution, must be fixed when moving
- // dispatches to separate crates
- function initOps() {
- const opsMap = core.ops();
- for (const [_name, opId] of Object.entries(opsMap)) {
- core.setAsyncHandler(opId, dispatchJson.asyncMsgFromRust);
- }
- }
-
- function runtimeStart(source) {
- initOps();
- // First we send an empty `Start` message to let the privileged side know we
- // are ready. The response should be a `StartRes` message containing the CLI
- // args and other info.
- const s = opStart();
- version.setVersions(s.denoVersion, s.v8Version, s.tsVersion);
- build.setBuildInfo(s.target);
- util.setLogDebug(s.debugFlag, source);
- errorStack.setPrepareStackTrace(Error);
- return s;
- }
-
- // Other properties shared between WindowScope and WorkerGlobalScope
- const windowOrWorkerGlobalScopeProperties = {
- console: util.writable(new Console(core.print)),
- crypto: util.readOnly(crypto),
- CustomEvent: util.nonEnumerable(CustomEvent),
- ErrorEvent: util.nonEnumerable(ErrorEvent),
- Event: util.nonEnumerable(Event),
- EventTarget: util.nonEnumerable(EventTarget),
- performance: util.writable(new performance.Performance()),
- Performance: util.nonEnumerable(performance.Performance),
- PerformanceEntry: util.nonEnumerable(performance.PerformanceEntry),
- PerformanceMark: util.nonEnumerable(performance.PerformanceMark),
- PerformanceMeasure: util.nonEnumerable(performance.PerformanceMeasure),
- TextDecoder: util.nonEnumerable(TextDecoder),
- TextEncoder: util.nonEnumerable(TextEncoder),
- Worker: util.nonEnumerable(worker.Worker),
- };
-
- const eventTargetProperties = {
- addEventListener: util.readOnly(
- EventTarget.prototype.addEventListener,
- ),
- dispatchEvent: util.readOnly(EventTarget.prototype.dispatchEvent),
- removeEventListener: util.readOnly(
- EventTarget.prototype.removeEventListener,
- ),
- };
-
- const workerRuntimeGlobalProperties = {
- self: util.readOnly(globalThis),
- onmessage: util.writable(onmessage),
- onerror: util.writable(onerror),
- // TODO: should be readonly?
- close: util.nonEnumerable(workerClose),
- postMessage: util.writable(postMessage),
- workerMessageRecvCallback: util.nonEnumerable(workerMessageRecvCallback),
- };
-
- let hasBootstrapped = false;
-
- function bootstrapWorkerRuntime(name, useDenoNamespace, internalName) {
- if (hasBootstrapped) {
- throw new Error("Worker runtime already bootstrapped");
- }
- // Remove bootstrapping methods from global scope
- globalThis.__bootstrap = undefined;
- globalThis.bootstrap = undefined;
- util.log("bootstrapWorkerRuntime");
- hasBootstrapped = true;
- Object.defineProperties(globalThis, windowOrWorkerGlobalScopeProperties);
- Object.defineProperties(globalThis, workerRuntimeGlobalProperties);
- Object.defineProperties(globalThis, eventTargetProperties);
- Object.defineProperties(globalThis, { name: util.readOnly(name) });
- eventTarget.setEventTargetData(globalThis);
- const { noColor, args } = runtimeStart(
- internalName ?? name,
- );
-
- const finalDenoNs = {
- core,
- internal: internalSymbol,
- [internalSymbol]: internalObject,
- ...denoNs,
- };
- if (useDenoNamespace) {
- Object.defineProperties(finalDenoNs, {
- noColor: util.readOnly(noColor),
- args: util.readOnly(Object.freeze(args)),
- });
- // Setup `Deno` global - we're actually overriding already
- // existing global `Deno` with `Deno` namespace from "./deno.ts".
- util.immutableDefine(globalThis, "Deno", finalDenoNs);
- Object.freeze(globalThis.Deno);
- Object.freeze(globalThis.Deno.core);
- Object.freeze(globalThis.Deno.core.sharedQueue);
- } else {
- delete globalThis.Deno;
- util.assert(globalThis.Deno === undefined);
- }
- }
-
- Object.defineProperties(globalThis, {
- bootstrap: {
- value: {
- workerRuntime: bootstrapWorkerRuntime,
- },
- configurable: true,
- writable: true,
- },
- });
-})(this);
diff --git a/cli/tsc/99_main_compiler.js b/cli/tsc/99_main_compiler.js
index d64896862..a97449175 100644
--- a/cli/tsc/99_main_compiler.js
+++ b/cli/tsc/99_main_compiler.js
@@ -3,10 +3,13 @@
// This module is the entry point for "compiler" isolate, ie. the one
// that is created when Deno needs to compile TS/WASM to JS.
//
-// It provides a single functions that should be called by Rust:
-// - `bootstrapTsCompilerRuntime`
+// It provides two functions that should be called by Rust:
+// - `bootstrapCompilerRuntime`
// This functions must be called when creating isolate
// to properly setup runtime.
+// - `tsCompilerOnMessage`
+// This function must be called when sending a request
+// to the compiler.
// Removes the `__proto__` for security reasons. This intentionally makes
// Deno non compliant with ECMA-262 Annex B.2.2.1
@@ -16,9 +19,31 @@ delete Object.prototype.__proto__;
((window) => {
const core = Deno.core;
- const { bold, cyan, yellow } = window.__bootstrap.colors;
const { assert, log, notImplemented } = window.__bootstrap.util;
- const { DiagnosticCategory } = window.__bootstrap.diagnostics;
+ const dispatchJson = window.__bootstrap.dispatchJson;
+ const util = window.__bootstrap.util;
+ const errorStack = window.__bootstrap.errorStack;
+
+ function opNow() {
+ const res = dispatchJson.sendSync("op_now");
+ return res.seconds * 1e3 + res.subsecNanos / 1e6;
+ }
+
+ const DiagnosticCategory = {
+ 0: "Log",
+ 1: "Debug",
+ 2: "Info",
+ 3: "Error",
+ 4: "Warning",
+ 5: "Suggestion",
+
+ Log: 0,
+ Debug: 1,
+ Info: 2,
+ Error: 3,
+ Warning: 4,
+ Suggestion: 5,
+ };
const unstableDenoGlobalProperties = [
"umask",
@@ -1136,7 +1161,7 @@ delete Object.prototype.__proto__;
function performanceStart() {
stats.length = 0;
// TODO(kitsonk) replace with performance.mark() when landed
- statsStart = performance.now();
+ statsStart = opNow();
ts.performance.enable();
}
@@ -1176,7 +1201,7 @@ delete Object.prototype.__proto__;
function performanceEnd() {
// TODO(kitsonk) replace with performance.measure() when landed
- const duration = performance.now() - statsStart;
+ const duration = opNow() - statsStart;
stats.push({ key: "Compile time", value: duration });
return stats;
}
@@ -1188,11 +1213,11 @@ delete Object.prototype.__proto__;
) {
const { ignoredOptions, diagnostics } = configResult;
if (ignoredOptions) {
- console.warn(
- yellow(`Unsupported compiler options in "${configPath}"\n`) +
- cyan(` The following options were ignored:\n`) +
- ` ${ignoredOptions.map((value) => bold(value)).join(", ")}`,
- );
+ const msg =
+ `Unsupported compiler options in "${configPath}"\n The following options were ignored:\n ${
+ ignoredOptions.map((value) => value).join(", ")
+ }\n`;
+ core.print(msg, true);
}
return diagnostics;
}
@@ -1545,6 +1570,7 @@ delete Object.prototype.__proto__;
cwd,
sourceFileMap,
type,
+ performance,
}) {
if (performance) {
performanceStart();
@@ -1804,64 +1830,83 @@ delete Object.prototype.__proto__;
return Promise.resolve(result);
}
- async function tsCompilerOnMessage({
- data: request,
- }) {
+ function opCompilerRespond(msg) {
+ dispatchJson.sendSync("op_compiler_respond", msg);
+ }
+
+ async function tsCompilerOnMessage(msg) {
+ const request = msg.data;
switch (request.type) {
case CompilerRequestType.Compile: {
const result = compile(request);
- globalThis.postMessage(result);
+ opCompilerRespond(result);
break;
}
case CompilerRequestType.Transpile: {
const result = transpile(request);
- globalThis.postMessage(result);
+ opCompilerRespond(result);
break;
}
case CompilerRequestType.Bundle: {
const result = bundle(request);
- globalThis.postMessage(result);
+ opCompilerRespond(result);
break;
}
case CompilerRequestType.RuntimeCompile: {
const result = runtimeCompile(request);
- globalThis.postMessage(result);
+ opCompilerRespond(result);
break;
}
case CompilerRequestType.RuntimeBundle: {
const result = runtimeBundle(request);
- globalThis.postMessage(result);
+ opCompilerRespond(result);
break;
}
case CompilerRequestType.RuntimeTranspile: {
const result = await runtimeTranspile(request);
- globalThis.postMessage(result);
+ opCompilerRespond(result);
break;
}
default:
- log(
+ throw new Error(
`!!! unhandled CompilerRequestType: ${request.type} (${
CompilerRequestType[request.type]
})`,
);
}
- // Shutdown after single request
- globalThis.close();
}
- function bootstrapTsCompilerRuntime() {
- globalThis.bootstrap.workerRuntime("TS", false);
- globalThis.onmessage = tsCompilerOnMessage;
+ // TODO(bartlomieju): temporary solution, must be fixed when moving
+ // dispatches to separate crates
+ function initOps() {
+ const opsMap = core.ops();
+ for (const [_name, opId] of Object.entries(opsMap)) {
+ core.setAsyncHandler(opId, dispatchJson.asyncMsgFromRust);
+ }
}
- Object.defineProperties(globalThis, {
- bootstrap: {
- value: {
- ...globalThis.bootstrap,
- tsCompilerRuntime: bootstrapTsCompilerRuntime,
- },
- configurable: true,
- writable: true,
- },
- });
+ function runtimeStart(source) {
+ initOps();
+ // First we send an empty `Start` message to let the privileged side know we
+ // are ready. The response should be a `StartRes` message containing the CLI
+ // args and other info.
+ const s = dispatchJson.sendSync("op_start");
+ util.setLogDebug(s.debugFlag, source);
+ errorStack.setPrepareStackTrace(Error);
+ return s;
+ }
+
+ let hasBootstrapped = false;
+
+ function bootstrapCompilerRuntime() {
+ if (hasBootstrapped) {
+ throw new Error("Worker runtime already bootstrapped");
+ }
+ hasBootstrapped = true;
+ globalThis.__bootstrap = undefined;
+ runtimeStart("TS");
+ }
+
+ globalThis.bootstrapCompilerRuntime = bootstrapCompilerRuntime;
+ globalThis.tsCompilerOnMessage = tsCompilerOnMessage;
})(this);