All files / src/internal/server context.js

97.91% Statements 94/96
93.75% Branches 15/16
100% Functions 8/8
97.91% Lines 94/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 971x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 28x 1x 1x 1x 1x 1x 1x 1x 1x 29x 29x 29x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 63x 63x     63x 63x 63x 1x 1x 1x 1x 1x 2098x 2098x 2098x 2098x 2098x 2098x 1x 1x 2085x 2085x 2085x 2085x 2085x 22x 22x 2085x 2085x 2085x 1x 1x 1x 1x 1x 51x 51x 51x 51x 45x 45x 28x 28x 17x 17x 23x 23x 23x  
/** @import { Component } from '#server' */
import { DEV } from 'esm-env';
import { on_destroy } from './index.js';
import * as e from '../shared/errors.js';
 
/** @type {Component | null} */
export var current_component = null;
 
/**
 * @template T
 * @param {any} key
 * @returns {T}
 */
export function getContext(key) {
	const context_map = get_or_init_context_map('getContext');
	const result = /** @type {T} */ (context_map.get(key));
 
	return result;
}
 
/**
 * @template T
 * @param {any} key
 * @param {T} context
 * @returns {T}
 */
export function setContext(key, context) {
	get_or_init_context_map('setContext').set(key, context);
	return context;
}
 
/**
 * @param {any} key
 * @returns {boolean}
 */
export function hasContext(key) {
	return get_or_init_context_map('hasContext').has(key);
}
 
/** @returns {Map<any, any>} */
export function getAllContexts() {
	return get_or_init_context_map('getAllContexts');
}
 
/**
 * @param {string} name
 * @returns {Map<unknown, unknown>}
 */
function get_or_init_context_map(name) {
	if (current_component === null) {
		e.lifecycle_outside_component(name);
	}
 
	return (current_component.c ??= new Map(get_parent_context(current_component) || undefined));
}
 
/**
 * @param {Function} [fn]
 */
export function push(fn) {
	current_component = { p: current_component, c: null, d: null };
	if (DEV) {
		// component function
		current_component.function = fn;
	}
}
 
export function pop() {
	var component = /** @type {Component} */ (current_component);
 
	var ondestroy = component.d;
 
	if (ondestroy) {
		on_destroy.push(...ondestroy);
	}
 
	current_component = component.p;
}
 
/**
 * @param {Component} component_context
 * @returns {Map<unknown, unknown> | null}
 */
function get_parent_context(component_context) {
	let parent = component_context.p;
 
	while (parent !== null) {
		const context_map = parent.c;
		if (context_map !== null) {
			return context_map;
		}
		parent = parent.p;
	}
 
	return null;
}