deno_web 0.286.0

Collection of Web APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
// Copyright 2018-2026 the Deno authors. MIT license.

/// <reference path="../../core/internal.d.ts" />

// The console/inspect implementation lives in Rust (ext/web/console/); this
// file is a thin shim that wires the cppgc-wrapped `Console` class and the
// inspect ops into the historical JS export surface.

(function () {
const { core, internals, primordials } = __bootstrap;
const {
  op_console_css_to_ansi,
  op_console_format_value,
  op_console_get_string_width,
  op_console_inspect,
  op_console_inspect_args,
  op_console_parse_css,
  op_console_parse_css_color,
  op_console_quote_string,
  op_console_strip_vt,
  Console: ConsoleWrap,
} = core.ops;
const {
  AggregateError,
  AggregateErrorPrototype,
  Array,
  ArrayBuffer,
  ArrayBufferPrototype,
  ArrayPrototype,
  BigIntPrototypeValueOf,
  Boolean,
  BooleanPrototype,
  BooleanPrototypeValueOf,
  DataView,
  DataViewPrototype,
  Date,
  DatePrototype,
  Error,
  ErrorCaptureStackTrace,
  ErrorPrototype,
  Function,
  FunctionPrototype,
  FunctionPrototypeToString,
  Map,
  MapPrototype,
  Number,
  NumberPrototype,
  NumberPrototypeValueOf,
  Object,
  ObjectAssign,
  ObjectCreate,
  ObjectDefineProperty,
  ObjectIs,
  ObjectPrototype,
  ObjectPrototypeIsPrototypeOf,
  ObjectSetPrototypeOf,
  Promise,
  PromisePrototype,
  RangeError,
  RangeErrorPrototype,
  ReflectGetOwnPropertyDescriptor,
  ReflectGetPrototypeOf,
  RegExp,
  RegExpPrototype,
  RegExpPrototypeToString,
  SafeArrayIterator,
  SafeRegExp,
  Set,
  SetPrototype,
  String,
  StringPrototype,
  StringPrototypeValueOf,
  Symbol,
  SymbolFor,
  SymbolHasInstance,
  SymbolPrototypeValueOf,
  SymbolToStringTag,
  TypedArray,
  TypedArrayPrototype,
  TypeError,
  TypeErrorPrototype,
  WeakMap,
  WeakMapPrototype,
  WeakSet,
  WeakSetPrototype,
} = primordials;

// ---------------------------------------------------------------------------
// no-color hooks (installed by the runtime bootstrap)

let noColorStdout = () => false;
let noColorStderr = () => false;

function setNoColorFns(stdoutFn, stderrFn) {
  noColorStdout = stdoutFn;
  noColorStderr = stderrFn;
}

function getStdoutNoColor() {
  return noColorStdout();
}

function getStderrNoColor() {
  return noColorStderr();
}

// ---------------------------------------------------------------------------
// styles / colors tables (exported; node's util.inspect builds on these)

const styles = {
  special: "cyan",
  number: "yellow",
  bigint: "yellow",
  boolean: "yellow",
  undefined: "grey",
  null: "bold",
  string: "green",
  symbol: "green",
  date: "magenta",
  // "name": intentionally not styling
  regexp: "red",
  module: "underline",
  internalError: "red",
  temporal: "cyan",
};

const defaultFG = 39;
const defaultBG = 49;

// Set Graphics Rendition https://en.wikipedia.org/wiki/ANSI_escape_code#graphics
// Each color consists of an array with the color code as first entry and the
// reset code as second entry.
const colors = {
  reset: [0, 0],
  bold: [1, 22],
  dim: [2, 22], // Alias: faint
  italic: [3, 23],
  underline: [4, 24],
  blink: [5, 25],
  // Swap foreground and background colors
  inverse: [7, 27], // Alias: swapcolors, swapColors
  hidden: [8, 28], // Alias: conceal
  strikethrough: [9, 29], // Alias: strikeThrough, crossedout, crossedOut
  doubleunderline: [21, 24], // Alias: doubleUnderline
  black: [30, defaultFG],
  red: [31, defaultFG],
  green: [32, defaultFG],
  yellow: [33, defaultFG],
  blue: [34, defaultFG],
  magenta: [35, defaultFG],
  cyan: [36, defaultFG],
  white: [37, defaultFG],
  bgBlack: [40, defaultBG],
  bgRed: [41, defaultBG],
  bgGreen: [42, defaultBG],
  bgYellow: [43, defaultBG],
  bgBlue: [44, defaultBG],
  bgMagenta: [45, defaultBG],
  bgCyan: [46, defaultBG],
  bgWhite: [47, defaultBG],
  framed: [51, 54],
  overlined: [53, 55],
  gray: [90, defaultFG], // Alias: grey, blackBright
  redBright: [91, defaultFG],
  greenBright: [92, defaultFG],
  yellowBright: [93, defaultFG],
  blueBright: [94, defaultFG],
  magentaBright: [95, defaultFG],
  cyanBright: [96, defaultFG],
  whiteBright: [97, defaultFG],
  bgGray: [100, defaultBG], // Alias: bgGrey, bgBlackBright
  bgRedBright: [101, defaultBG],
  bgGreenBright: [102, defaultBG],
  bgYellowBright: [103, defaultBG],
  bgBlueBright: [104, defaultBG],
  bgMagentaBright: [105, defaultBG],
  bgCyanBright: [106, defaultBG],
  bgWhiteBright: [107, defaultBG],
};

function defineColorAlias(target, alias) {
  ObjectDefineProperty(colors, alias, {
    __proto__: null,
    get() {
      return this[target];
    },
    set(value) {
      this[target] = value;
    },
    configurable: true,
    enumerable: false,
  });
}

defineColorAlias("gray", "grey");
defineColorAlias("gray", "blackBright");
defineColorAlias("bgGray", "bgGrey");
defineColorAlias("bgGray", "bgBlackBright");
defineColorAlias("dim", "faint");
defineColorAlias("strikethrough", "crossedout");
defineColorAlias("strikethrough", "strikeThrough");
defineColorAlias("strikethrough", "crossedOut");
defineColorAlias("hidden", "conceal");
defineColorAlias("inverse", "swapColors");
defineColorAlias("inverse", "swapcolors");
defineColorAlias("doubleunderline", "doubleUnderline");

// ---------------------------------------------------------------------------
// stylize helpers

// Marker recognized by the Rust engine so the table lookup runs natively.
const stylizeMarker = SymbolFor("Deno.privateConsoleStylize");

function stylizeNoColor(str) {
  return str;
}
ObjectDefineProperty(stylizeNoColor, stylizeMarker, {
  __proto__: null,
  value: "noColor",
  enumerable: false,
});

function createStylizeWithColor(styles, colors) {
  function stylizeWithColor(str, styleType) {
    const style = styles[styleType];
    if (style !== undefined) {
      const color = colors[style];
      if (color !== undefined) {
        return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
      }
    }
    return str;
  }
  ObjectDefineProperty(stylizeWithColor, stylizeMarker, {
    __proto__: null,
    value: [styles, colors],
    enumerable: false,
  });
  return stylizeWithColor;
}

// ---------------------------------------------------------------------------
// intrinsics handed to the Rust engine on every call (captured here at
// module initialization so they are primordial-safe and snapshot-safe)

let _URLPrototype;
function getURLPrototype() {
  if (!_URLPrototype) {
    _URLPrototype = core.loadExtScript("ext:deno_web/00_url.js").URLPrototype;
  }
  return _URLPrototype;
}

function getCwd() {
  try {
    return Deno.cwd();
  } catch {
    return undefined;
  }
}

function makeCrossContextStylize(stylize) {
  return ObjectSetPrototypeOf((value, flavour) => {
    let stylized;
    try {
      stylized = `${stylize(value, flavour)}`;
    } catch {
      // Continue regardless of error.
    }

    if (typeof stylized !== "string") return value;
    return stylized;
  }, null);
}

const intrinsics = {
  __proto__: null,
  functionToString: function functionToString() {
    return FunctionPrototypeToString(this);
  },
  regExpToString: function regExpToString() {
    // When the prototype was detached (e.g. `Object.setPrototypeOf(re, null)`),
    // `source`/`flags` are no longer reachable as properties and
    // RegExpPrototypeToString would yield "/undefined/undefined". Reconstruct a
    // real RegExp from the internal slots first (matches the old console).
    const re = ObjectPrototypeIsPrototypeOf(RegExpPrototype, this)
      ? this
      : new SafeRegExp(this);
    return RegExpPrototypeToString(re);
  },
  numberValueOf: function numberValueOf() {
    return NumberPrototypeValueOf(this);
  },
  stringValueOf: function stringValueOf() {
    return StringPrototypeValueOf(this);
  },
  booleanValueOf: function booleanValueOf() {
    return BooleanPrototypeValueOf(this);
  },
  bigIntValueOf: function bigIntValueOf() {
    return BigIntPrototypeValueOf(this);
  },
  symbolValueOf: function symbolValueOf() {
    return SymbolPrototypeValueOf(this);
  },
  inspect,
  stylizeNoColor,
  createStylizeWithColor,
  styles,
  colors,
  objectPrototype: ObjectPrototype,
  errorPrototype: ErrorPrototype,
  // Special-cased builtin prototypes (`wellKnownPrototypes`), as flat
  // [prototype, name, constructor] triples.
  wellKnown: [
    ArrayPrototype,
    "Array",
    Array,
    ArrayBufferPrototype,
    "ArrayBuffer",
    ArrayBuffer,
    FunctionPrototype,
    "Function",
    Function,
    MapPrototype,
    "Map",
    Map,
    SetPrototype,
    "Set",
    Set,
    ObjectPrototype,
    "Object",
    Object,
    TypedArrayPrototype,
    "TypedArray",
    TypedArray,
    RegExpPrototype,
    "RegExp",
    RegExp,
    DatePrototype,
    "Date",
    Date,
    DataViewPrototype,
    "DataView",
    DataView,
    ErrorPrototype,
    "Error",
    Error,
    AggregateErrorPrototype,
    "AggregateError",
    AggregateError,
    RangeErrorPrototype,
    "RangeError",
    RangeError,
    TypeErrorPrototype,
    "TypeError",
    TypeError,
    BooleanPrototype,
    "Boolean",
    Boolean,
    NumberPrototype,
    "Number",
    Number,
    StringPrototype,
    "String",
    String,
    PromisePrototype,
    "Promise",
    Promise,
    WeakMapPrototype,
    "WeakMap",
    WeakMap,
    WeakSetPrototype,
    "WeakSet",
    WeakSet,
  ],
  getURLPrototype,
  getCwd,
  makeCrossContextStylize,
};

// ---------------------------------------------------------------------------
// inspect entry points

const denoInspectDefaultOptions = {
  indentationLvl: 0,
  currentDepth: 0,
  stylize: stylizeNoColor,

  showHidden: false,
  depth: 4,
  colors: false,
  showProxy: false,
  breakLength: 80,
  escapeSequences: true,
  compact: 3,
  sorted: false,
  getters: false,

  // node only
  maxArrayLength: 100,
  maxStringLength: 10_000, // deno: strAbbreviateSize: 10_000
  customInspect: true,

  // deno only
  quotes: ['"', "'", "`"],
  iterableLimit: 100, // similar to node's maxArrayLength
  trailingComma: false,

  inspect,

  indentLevel: 0,
};

function getDefaultInspectOptions() {
  return {
    budget: {},
    seen: [],
    ...denoInspectDefaultOptions,
  };
}

class CSI {
  static kClear = "\x1b[1;1H";
  static kClearScreenDown = "\x1b[0J";
}

function quoteString(string, ctx) {
  return op_console_quote_string(string, ctx);
}

function getStringWidth(str, removeControlChars = true) {
  return op_console_get_string_width(str, removeControlChars);
}

function stripVTControlCharacters(str) {
  return op_console_strip_vt(str);
}

function formatNumber(fn, value) {
  // Format -0 as '-0'. Checking `value === -0` won't distinguish 0 from -0.
  return fn(ObjectIs(value, -0) ? "-0" : `${value}`, "number");
}

function formatBigInt(fn, value) {
  return fn(`${value}n`, "bigint");
}

function formatValue(ctx, value, recurseTimes) {
  return op_console_format_value(intrinsics, ctx, value, recurseTimes ?? 0);
}

function inspectArgs(args, inspectOptions = { __proto__: null }) {
  const colors = inspectOptions.colors ?? !noColorStdout();
  return op_console_inspect_args(intrinsics, args, {
    __proto__: null,
    ...inspectOptions,
    colors,
  });
}

function inspect(
  value,
  inspectOptions = { __proto__: null },
) {
  return op_console_inspect(intrinsics, value, inspectOptions);
}

function cssToAnsi(css, prevCss = null) {
  return op_console_css_to_ansi(css, prevCss);
}

function parseCss(cssString) {
  return op_console_parse_css(cssString);
}

function parseCssColor(colorString) {
  return op_console_parse_css_color(colorString);
}

/** @param noColor {boolean} */
function getConsoleInspectOptions(noColor) {
  return {
    ...getDefaultInspectOptions(),
    colors: !noColor,
    stylize: noColor ? stylizeNoColor : createStylizeWithColor(styles, colors),
  };
}

// ---------------------------------------------------------------------------
// Console

const isConsoleInstance = Symbol("isConsoleInstance");

class Console {
  #wrap = null;
  #printFunc = null;
  // Reference to the namespace object returned from the constructor; `group`
  // routes its label through the namespace's (possibly inspector-wrapped)
  // `log` so DevTools renders the label inside the group container.
  #consoleRef = null;
  [isConsoleInstance] = false;

  #indentLevel = 0;

  // The cppgc-backed implementation can't be created while snapshotting
  // (no cppgc heap exists yet), so it is created lazily on first use.
  #getWrap() {
    if (this.#wrap === null) {
      this.#wrap = new ConsoleWrap(
        this.#printFunc,
        intrinsics,
        getStdoutNoColor,
        getStderrNoColor,
      );
      this.#wrap.indentLevel = this.#indentLevel;
    }
    return this.#wrap;
  }

  constructor(printFunc) {
    this.#printFunc = printFunc;
    ObjectDefineProperty(this, "indentLevel", {
      __proto__: null,
      get: () => {
        return this.#wrap === null ? this.#indentLevel : this.#wrap.indentLevel;
      },
      set: (value) => {
        if (this.#wrap === null) {
          this.#indentLevel = value;
        } else {
          this.#wrap.indentLevel = value;
        }
      },
      enumerable: true,
      configurable: true,
    });
    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 = ObjectCreate({}, {
      [SymbolToStringTag]: {
        enumerable: false,
        writable: false,
        configurable: true,
        value: "console",
      },
    });
    ObjectAssign(console, this);
    this.#consoleRef = console;
    return console;
  }

  // The cppgc-backed wrap methods are exposed as ops, whose `()` Rust return
  // maps to JS `null`. Console methods must return `undefined` per the spec
  // (e.g. the REPL prints the eval result of `console.log(1)` as `undefined`),
  // so these wrappers discard the wrap's return value.
  log = (...args) => {
    this.#getWrap().log(...new SafeArrayIterator(args));
  };

  debug = (...args) => {
    this.#getWrap().debug(...new SafeArrayIterator(args));
  };

  info = (...args) => {
    this.#getWrap().info(...new SafeArrayIterator(args));
  };

  dir = (obj = undefined, options = { __proto__: null }) => {
    this.#getWrap().dir(obj, options);
  };

  // Per https://console.spec.whatwg.org/#dirxml, dirxml uses the log
  // printer (not dir). Use a fresh arrow so the method's .name is "dirxml".
  dirxml = (...args) => {
    this.log(...new SafeArrayIterator(args));
  };

  warn = (...args) => {
    this.#getWrap().warn(...new SafeArrayIterator(args));
  };

  error = (...args) => {
    this.#getWrap().error(...new SafeArrayIterator(args));
  };

  assert = (condition = false, ...args) => {
    // `#[op2]` converts the `bool` arg with strict identity (=== true), not
    // ToBoolean, so coerce here to match the WHATWG console spec (truthy
    // condition passes).
    this.#getWrap().assert(!!condition, ...new SafeArrayIterator(args));
  };

  count = (label = "default") => {
    this.#getWrap().count(String(label));
  };

  countReset = (label = "default") => {
    this.#getWrap().countReset(String(label));
  };

  table = (data = undefined, properties = undefined) => {
    this.#getWrap().table(data, properties);
  };

  time = (label = "default") => {
    this.#getWrap().time(String(label));
  };

  timeLog = (label = "default", ...args) => {
    this.#getWrap().timeLog(String(label), ...new SafeArrayIterator(args));
  };

  timeEnd = (label = "default") => {
    this.#getWrap().timeEnd(String(label));
  };

  group = (...label) => {
    if (label.length > 0) {
      // Route through the namespace object's `log` so that, when the
      // inspector wraps console methods, both the V8 console binding (for
      // DevTools) and the internal `log` (for the terminal) are invoked.
      this.#consoleRef.log(...new SafeArrayIterator(label));
    }
    this.#getWrap().indentLevel++;
  };

  groupCollapsed = this.group;

  groupEnd = () => {
    const wrap = this.#getWrap();
    if (wrap.indentLevel > 0) {
      wrap.indentLevel--;
    }
  };

  clear = () => {
    this.#getWrap().clear();
  };

  trace = (...args) => {
    const message = inspectArgs(
      args,
      {
        ...getConsoleInspectOptions(noColorStderr()),
        indentLevel: 0,
      },
    );
    const err = {
      name: "Trace",
      message,
    };
    ErrorCaptureStackTrace(err, this.trace);
    this.#printFunc(err.stack, 4);
    this.#printFunc("\n", 4);
  };

  // These methods are noops, but when the inspector is connected, they
  // call into V8.
  profile = (_label) => {};
  profileEnd = (_label) => {};
  timeStamp = (_label) => {};

  static [SymbolHasInstance](instance) {
    return instance[isConsoleInstance];
  }
}

const customInspect = SymbolFor("Deno.customInspect");

/** Creates an object that represents a subset of the properties of the
 * original object, suitable for handing to `inspect()`. The returned value
 * carries the original object's class name and the listed keys as own
 * enumerable data properties. */
function createFilteredInspectProxy({ object, keys, evaluate }) {
  const cls = class {};
  if (object.constructor?.name) {
    ObjectDefineProperty(cls, "name", {
      __proto__: null,
      value: object.constructor.name,
    });
  }

  const result = new cls();
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const descriptor = evaluate
      ? getEvaluatedDescriptor(object, key)
      : (getDescendantPropertyDescriptor(object, key) ??
        getEvaluatedDescriptor(object, key));
    ObjectDefineProperty(result, key, descriptor);
  }
  return result;

  function getDescendantPropertyDescriptor(object, key) {
    let propertyDescriptor = ReflectGetOwnPropertyDescriptor(object, key);
    if (!propertyDescriptor) {
      const prototype = ReflectGetPrototypeOf(object);
      if (prototype) {
        propertyDescriptor = getDescendantPropertyDescriptor(prototype, key);
      }
    }
    return propertyDescriptor;
  }

  function getEvaluatedDescriptor(object, key) {
    return {
      configurable: true,
      enumerable: true,
      value: object[key],
    };
  }
}

// Expose these fields to internalObject for tests.
internals.Console = Console;
internals.cssToAnsi = cssToAnsi;
internals.inspectArgs = inspectArgs;
internals.parseCss = parseCss;
internals.parseCssColor = parseCssColor;

return {
  colors,
  Console,
  createFilteredInspectProxy,
  createStylizeWithColor,
  CSI,
  customInspect,
  formatBigInt,
  formatNumber,
  formatValue,
  getConsoleInspectOptions,
  getDefaultInspectOptions,
  getStderrNoColor,
  getStringWidth,
  getStdoutNoColor,
  inspect,
  inspectArgs,
  quoteString,
  setNoColorFns,
  stripVTControlCharacters,
  styles,
};
})();