deno_core 0.398.0

A modern JavaScript/TypeScript runtime built with V8, Rust, and Tokio
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
// Copyright 2018-2026 the Deno authors. MIT license.
"use strict";

((window) => {
  const {
    MathMax,
    MathTrunc,
    NumberMIN_SAFE_INTEGER,
  } = window.__bootstrap.primordials;
  const {
    op_timer_schedule,
    op_timer_track,
    op_timer_untrack,
    op_timer_now,
    op_leak_tracing_submit,
  } = window.Deno.core.ops;
  const {
    ErrorCaptureStackTrace,
    StringPrototypeSlice,
  } = window.__bootstrap.primordials;
  const { __isLeakTracingEnabled } = window.__infra;

  // ---------------------------------------------------------------------------
  // Linked list helpers (matches Node.js lib/internal/linkedlist.js)
  // Circular doubly-linked list where the sentinel's _idleNext points to the
  // tail (newest) and _idlePrev points to the head (oldest/most-idle).
  // ---------------------------------------------------------------------------
  function L_init(list) {
    list._idleNext = list;
    list._idlePrev = list;
  }

  function L_peek(list) {
    if (list._idlePrev === list) return null;
    return list._idlePrev;
  }

  function L_remove(item) {
    if (item._idleNext) {
      item._idleNext._idlePrev = item._idlePrev;
    }
    if (item._idlePrev) {
      item._idlePrev._idleNext = item._idleNext;
    }
    item._idleNext = null;
    item._idlePrev = null;
  }

  function L_append(list, item) {
    if (item._idleNext || item._idlePrev) {
      L_remove(item);
    }
    item._idleNext = list._idleNext;
    item._idlePrev = list;
    list._idleNext._idlePrev = item;
    list._idleNext = item;
  }

  function L_isEmpty(list) {
    return list._idleNext === list;
  }

  // ---------------------------------------------------------------------------
  // Priority queue (binary min-heap, matches Node.js lib/internal/priority_queue.js)
  // ---------------------------------------------------------------------------
  class PriorityQueue {
    #compare;
    #setPosition;
    #heap = [undefined, undefined];
    #size = 0;

    constructor(comparator, setPosition) {
      this.#compare = comparator;
      this.#setPosition = setPosition;
    }

    insert(value) {
      const pos = ++this.#size;
      this.#heap[pos] = value;
      this.#percolateUp(pos);
    }

    peek() {
      return this.#heap[1];
    }

    shift() {
      const value = this.#heap[1];
      if (value === undefined) return;
      this.#removeAt(1);
      return value;
    }

    percolateDown(pos) {
      const compare = this.#compare;
      const setPosition = this.#setPosition;
      const heap = this.#heap;
      const size = this.#size;
      const hsize = size >> 1;
      const item = heap[pos];

      while (pos <= hsize) {
        let child = pos << 1;
        const nextChild = child + 1;
        let childItem = heap[child];

        if (nextChild <= size && compare(heap[nextChild], childItem) < 0) {
          child = nextChild;
          childItem = heap[nextChild];
        }

        if (compare(item, childItem) <= 0) break;

        if (setPosition) setPosition(childItem, pos);
        heap[pos] = childItem;
        pos = child;
      }

      heap[pos] = item;
      if (setPosition) setPosition(item, pos);
    }

    #percolateUp(pos) {
      const heap = this.#heap;
      const compare = this.#compare;
      const setPosition = this.#setPosition;
      const item = heap[pos];

      while (pos > 1) {
        const parent = pos >> 1;
        const parentItem = heap[parent];
        if (compare(parentItem, item) <= 0) break;
        heap[pos] = parentItem;
        if (setPosition) setPosition(parentItem, pos);
        pos = parent;
      }

      heap[pos] = item;
      if (setPosition) setPosition(item, pos);
    }

    #removeAt(pos) {
      const heap = this.#heap;
      let size = this.#size;
      heap[pos] = heap[size];
      heap[size] = undefined;
      size = --this.#size;

      if (size > 0 && pos <= size) {
        if (pos > 1 && this.#compare(heap[pos >> 1], heap[pos]) > 0) {
          this.#percolateUp(pos);
        } else {
          this.percolateDown(pos);
        }
      }
    }
  }

  // ---------------------------------------------------------------------------
  // Timer infrastructure (matches Node.js lib/internal/timers.js)
  // ---------------------------------------------------------------------------
  const TIMEOUT_MAX = 2 ** 31 - 1;

  let timerListId = NumberMIN_SAFE_INTEGER;
  let nextExpiry = Infinity;
  let nextTimerId = 1;

  // Shared buffer with Rust. Index 0: refed timer count.
  // Set by Rust during store_js_callbacks via __setTimerInfo.
  let timerInfo;

  function compareTimersLists(a, b) {
    const expiryDiff = a.expiry - b.expiry;
    if (expiryDiff === 0) {
      return a.id - b.id;
    }
    return expiryDiff;
  }

  function setPosition(node, pos) {
    node.priorityQueuePosition = pos;
  }

  const timerListQueue = new PriorityQueue(compareTimersLists, setPosition);
  const timerListMap = { __proto__: null };

  class TimersList {
    constructor(expiry, msecs) {
      this._idleNext = this;
      this._idlePrev = this;
      this.expiry = expiry;
      this.id = timerListId++;
      this.msecs = msecs;
      this.priorityQueuePosition = null;
    }
  }

  function incRefCount() {
    if (timerInfo[0]++ === 0) {
      op_timer_schedule(-1); // ref the timer handle
    }
  }

  function decRefCount() {
    if (--timerInfo[0] === 0) {
      op_timer_schedule(-2); // unref the timer handle
    }
  }

  // Insert a timer item into the appropriate bucket.
  function insert(item, msecs, start) {
    if (start === undefined) start = op_timer_now();
    msecs = MathTrunc(msecs);
    item._idleStart = start;

    let list = timerListMap[msecs];
    if (list === undefined) {
      const expiry = start + msecs;
      timerListMap[msecs] = list = new TimersList(expiry, msecs);
      timerListQueue.insert(list);

      if (nextExpiry > expiry) {
        op_timer_schedule(msecs);
        nextExpiry = expiry;
      }
    }

    L_append(list, item);
  }

  // Called from Rust when the native timer fires.
  // Returns: positive = next expiry (has refed timers),
  //          negative = next expiry (no refed timers, negate for actual value),
  //          0 = no timers remain.
  function processTimers(now) {
    nextExpiry = Infinity;

    let list;
    let ranAtLeastOneList = false;
    while ((list = timerListQueue.peek()) != null) {
      if (list.expiry > now) {
        nextExpiry = list.expiry;
        return timerInfo[0] > 0 ? nextExpiry : -nextExpiry;
      }
      if (ranAtLeastOneList) {
        runNextTicks();
      } else {
        ranAtLeastOneList = true;
      }
      listOnTimeout(list, now);
    }
    return 0;
  }

  // runNextTicks is set by 01_core.js via setRunNextTicks().
  let runNextTicks = () => {};
  // reportException is set by 01_core.js via setReportException().
  let reportException = (e) => {
    throw e;
  };

  function setRunNextTicks(fn) {
    runNextTicks = fn;
  }

  function setReportException(fn) {
    reportException = fn;
  }

  function listOnTimeout(list, now) {
    const msecs = list.msecs;

    let ranAtLeastOneTimer = false;
    let timer;
    while ((timer = L_peek(list)) != null) {
      const diff = now - timer._idleStart;

      if (diff < msecs) {
        list.expiry = MathMax(timer._idleStart + msecs, now + 1);
        list.id = timerListId++;
        timerListQueue.percolateDown(1);
        return;
      }

      if (ranAtLeastOneTimer) {
        runNextTicks();
      } else {
        ranAtLeastOneTimer = true;
      }

      L_remove(timer);

      if (!timer._onTimeout) {
        if (!timer._destroyed) {
          timer._destroyed = true;
          if (timer[kRefed]) {
            decRefCount();
          }
          op_timer_untrack(timer._timerId);
        }
        continue;
      }

      try {
        const args = timer._timerArgs;
        if (args === undefined) {
          timer._onTimeout();
        } else {
          timer._onTimeout(...args);
        }
      } catch (e) {
        reportException(e);
      } finally {
        if (
          timer._repeat && timer._idleTimeout !== -1 &&
          !timer._idlePrev && !timer._idleNext
        ) {
          timer._idleTimeout = timer._repeat;
          insert(timer, timer._idleTimeout, now);
        } else if (!timer._idleNext && !timer._idlePrev && !timer._destroyed) {
          timer._destroyed = true;
          if (timer[kRefed]) {
            decRefCount();
          }
          op_timer_untrack(timer._timerId);
        }
      }
    }

    // List is empty, clean up.
    if (list === timerListMap[msecs]) {
      delete timerListMap[msecs];
      timerListQueue.shift();
    }
  }

  // Timer item constructor (internal). Callers (web timers, node timers)
  // wrap this with their own validation and async context handling.
  function createTimer(callback, after, args, isRepeat, isRefed, isSystem) {
    if (after === undefined) {
      after = 1;
    } else {
      after *= 1;
    }
    if (!(after >= 1 && after <= TIMEOUT_MAX)) {
      after = 1;
    }

    const id = nextTimerId++;
    const timer = {
      _idleTimeout: after,
      _idlePrev: null,
      _idleNext: null,
      _idleStart: null,
      _onTimeout: callback,
      _timerArgs: args,
      _repeat: isRepeat ? after : null,
      _destroyed: false,
      [kRefed]: isRefed,
      _timerId: id,
    };

    if (isRefed) incRefCount();
    insert(timer, after);
    op_timer_track(id, !!isRepeat, !!isSystem);
    if (__isLeakTracingEnabled()) {
      const error = new Error();
      ErrorCaptureStackTrace(error, createTimer);
      op_leak_tracing_submit(2, id, StringPrototypeSlice(error.stack, 6));
    }
    return timer;
  }

  const kRefed = Symbol("refed");

  function cancelTimer(timer) {
    if (timer._destroyed) return;
    timer._destroyed = true;
    timer._onTimeout = null;
    if (timer[kRefed]) {
      decRefCount();
    }
    L_remove(timer);
    op_timer_untrack(timer._timerId);
  }

  function refreshTimer(timer) {
    // Remove from current list
    if (timer._idlePrev || timer._idleNext) {
      L_remove(timer);
    }
    // Re-insert with current time
    insert(timer, timer._idleTimeout);
  }

  function refTimer(timer) {
    if (!timer[kRefed]) {
      timer[kRefed] = true;
      if (!timer._destroyed) incRefCount();
    }
  }

  function unrefTimer(timer) {
    if (timer[kRefed]) {
      timer[kRefed] = false;
      if (!timer._destroyed) decRefCount();
    }
  }

  // Exported on window.__timers for 01_core.js to pick up.
  window.__timers = {
    processTimers,
    createTimer,
    cancelTimer,
    refreshTimer,
    refTimer,
    unrefTimer,
    insert,
    incRefCount,
    decRefCount,
    kRefed,
    setRunNextTicks,
    setReportException,
    TIMEOUT_MAX,
    L_init,
    L_peek,
    L_remove,
    L_append,
    L_isEmpty,
    __setTimerInfo(buf) {
      timerInfo = buf;
    },
  };
})(globalThis);