All files / src/compiler/phases/3-transform utils.js

99.55% Statements 447/449
98.24% Branches 168/171
100% Functions 12/12
99.54% Lines 438/440

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 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 4412x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 699x 699x 699x 622x 699x 77x 77x 622x 622x 2x 2x 2x 2x 2x 2x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 12495x 29374x 248x 248x 248x 434x 248x 248x 248x 248x 248x 248x 248x 248x 248x 984x 984x 984x 816x 816x 816x 984x 248x 248x 248x 434x 434x 29374x 29126x 29126x 29374x 12495x 12495x 12380x 12380x 115x 115x 115x 115x 10544x 434x 1094x 58x 58x 1094x 434x 115x 115x 12495x 1x 1x 1x 114x 114x 114x 114x 114x 114x 464x 218x 218x 246x 464x 590x 590x 590x 246x 246x 246x 114x 10406x 432x 432x 114x 114x 114x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 12495x 12495x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 38259x 93x 93x 38166x 38166x 38234x 38259x 38259x 38259x 38259x 38259x 38259x 37770x 38259x 478x 478x 38259x 37688x 37688x 38259x 15942x 15942x 15942x 15942x 15828x 15828x 15828x 15828x 15828x 15828x 15828x 11824x 15828x 8428x 8428x 15828x 15828x 3396x 3396x 3396x 15828x 15828x 15828x 15828x 6525x 15828x 4014x 4014x 15828x 15828x 2511x 2511x 2511x 15828x 15828x 15828x 15828x 15828x 15568x 7488x 7488x 7488x 7488x 7488x 7488x 7488x 7488x 15828x 15828x 15828x 15828x 15828x 15828x 15828x 25131x 25131x 25131x 25131x 25131x 8315x 7043x 7043x 7043x 7043x 7043x 7043x 7043x 7043x 7043x 7043x 7043x 8315x 6232x 6232x 6232x 8315x 8180x 8180x 25131x 16816x 16816x 25131x 15828x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 15942x 10339x 10309x 10309x 10309x 763x 763x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 15943x 5328x 15943x 15943x 2x 2x 2x 2x 2x 2x 2x 2x 8199x     8199x 8199x 142x 16x 16x 142x 142x 8057x 8057x 8057x 8199x 8199x 8199x 8199x 8199x 8199x 2378x 8199x 5767x 5767x 4058x 4058x 5767x 3999x 3999x 3999x 2x 2x 2x 2x 2x 2x 2x 2x 5767x 5767x 5767x 5767x 5767x 5767x 4076x 3968x 3968x 4076x 94x 94x 5767x 5767x 5767x 12462x 12462x 12462x 12462x 12462x 17558x 17558x 17558x 17558x 17558x 17558x 17558x 17558x 11368x 17558x 13739x 13739x 12462x 12462x 12462x 12462x 7549x 360x 360x 7549x 12462x 12462x 12462x 12462x 12462x 1799x 1799x 1799x 2x 2x 2x 2x 2x 2x 2x 2x 7892x 10x 10x 7882x 7892x 182x 182x 7700x 7892x 7892x 2x 2x 2x 2x 2x 2x 2x 26x 26x 26x 26x 24x 26x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 26x 20x 20x 20x 26x  
/** @import { Context } from 'zimmerframe' */
/** @import { TransformState } from './types.js' */
/** @import { Ast, Binding, Namespace, ValidatedCompileOptions } from '#compiler' */
/** @import { Node, Expression, CallExpression } from 'estree' */
import {
	regex_ends_with_whitespaces,
	regex_not_whitespace,
	regex_starts_with_whitespaces
} from '../patterns.js';
import * as b from '../../utils/builders.js';
import * as e from '../../errors.js';
import { walk } from 'zimmerframe';
import { extract_identifiers } from '../../utils/ast.js';
import check_graph_for_cycles from '../2-analyze/utils/check_graph_for_cycles.js';
import is_reference from 'is-reference';
import { set_scope } from '../scope.js';
import { dev } from '../../state.js';
 
/**
 * @param {Node} node
 * @returns {boolean}
 */
export function is_hoisted_function(node) {
	if (
		node.type === 'ArrowFunctionExpression' ||
		node.type === 'FunctionExpression' ||
		node.type === 'FunctionDeclaration'
	) {
		return node.metadata?.hoisted === true;
	}
	return false;
}
 
/**
 * Match Svelte 4 behaviour by sorting ConstTag nodes in topological order
 * @param {Ast.SvelteNode[]} nodes
 * @param {TransformState} state
 */
function sort_const_tags(nodes, state) {
	/**
	 * @typedef {{
	 *   node: Ast.ConstTag;
	 *   deps: Set<Binding>;
	 * }} Tag
	 */
 
	const other = [];
 
	/** @type {Map<Binding, Tag>} */
	const tags = new Map();
 
	for (const node of nodes) {
		if (node.type === 'ConstTag') {
			const declaration = node.declaration.declarations[0];
 
			const bindings = extract_identifiers(declaration.id).map((id) => {
				return /** @type {Binding} */ (state.scope.get(id.name));
			});
 
			/** @type {Set<Binding>} */
			const deps = new Set();
 
			walk(declaration.init, state, {
				// @ts-expect-error don't know, don't care
				_: set_scope,
				Identifier(node, context) {
					const parent = /** @type {Expression} */ (context.path.at(-1));
 
					if (is_reference(node, parent)) {
						const binding = context.state.scope.get(node.name);
						if (binding) deps.add(binding);
					}
				}
			});
 
			for (const binding of bindings) {
				tags.set(binding, { node, deps });
			}
		} else {
			other.push(node);
		}
	}
 
	if (tags.size === 0) {
		return nodes;
	}
 
	/** @type {Array<[Binding, Binding]>} */
	const edges = [];
 
	for (const [id, tag] of tags) {
		for (const dep of tag.deps) {
			if (tags.has(dep)) {
				edges.push([id, dep]);
			}
		}
	}
 
	const cycle = check_graph_for_cycles(edges);
	if (cycle?.length) {
		const tag = /** @type {Tag} */ (tags.get(cycle[0]));
		e.const_tag_cycle(tag.node, cycle.map((binding) => binding.node.name).join(' → '));
	}
 
	/** @type {Ast.ConstTag[]} */
	const sorted = [];
 
	/** @param {Tag} tag */
	function add(tag) {
		if (sorted.includes(tag.node)) {
			return;
		}
 
		for (const dep of tag.deps) {
			const dep_tag = tags.get(dep);
			if (dep_tag) add(dep_tag);
		}
 
		sorted.push(tag.node);
	}
 
	for (const tag of tags.values()) {
		add(tag);
	}
 
	return [...sorted, ...other];
}
 
/**
 * Extract nodes that are hoisted and trim whitespace according to the following rules:
 * - trim leading and trailing whitespace, regardless of surroundings
 * - keep leading / trailing whitespace of inbetween text nodes,
 *   unless it's whitespace-only, in which case collapse to a single whitespace for all cases
 *   except when it's children of certain elements where we know ignore whitespace (like td/option/head),
 *   in which case we remove it entirely
 * @param {Ast.SvelteNode} parent
 * @param {Ast.SvelteNode[]} nodes
 * @param {Ast.SvelteNode[]} path
 * @param {Namespace} namespace
 * @param {TransformState & { options: ValidatedCompileOptions }} state
 * @param {boolean} preserve_whitespace
 * @param {boolean} preserve_comments
 */
export function clean_nodes(
	parent,
	nodes,
	path,
	namespace = 'html',
	state,
	// TODO give these defaults (state.options.preserveWhitespace and state.options.preserveComments).
	// first, we need to make `Component(Client|Server)TransformState` inherit from a new `ComponentTransformState`
	// rather than from `ClientTransformState` and `ServerTransformState`
	preserve_whitespace,
	preserve_comments
) {
	if (!state.analysis.runes) {
		nodes = sort_const_tags(nodes, state);
	}
 
	/** @type {Ast.SvelteNode[]} */
	const hoisted = [];
 
	/** @type {Ast.SvelteNode[]} */
	const regular = [];
 
	for (const node of nodes) {
		if (node.type === 'Comment' && !preserve_comments) {
			continue;
		}
 
		if (
			node.type === 'ConstTag' ||
			node.type === 'DebugTag' ||
			node.type === 'SvelteBody' ||
			node.type === 'SvelteWindow' ||
			node.type === 'SvelteDocument' ||
			node.type === 'SvelteHead' ||
			node.type === 'TitleElement' ||
			node.type === 'SnippetBlock'
		) {
			// TODO others?
			hoisted.push(node);
		} else {
			regular.push(node);
		}
	}
 
	let trimmed = regular;
 
	if (!preserve_whitespace) {
		trimmed = [];
 
		let first, last;
 
		while (
			(first = regular[0]) &&
			first.type === 'Text' &&
			!regex_not_whitespace.test(first.data)
		) {
			regular.shift();
		}
 
		if (first?.type === 'Text') {
			first.raw = first.raw.replace(regex_starts_with_whitespaces, '');
			first.data = first.data.replace(regex_starts_with_whitespaces, '');
		}
 
		while (
			(last = regular.at(-1)) &&
			last.type === 'Text' &&
			!regex_not_whitespace.test(last.data)
		) {
			regular.pop();
		}
 
		if (last?.type === 'Text') {
			last.raw = last.raw.replace(regex_ends_with_whitespaces, '');
			last.data = last.data.replace(regex_ends_with_whitespaces, '');
		}
 
		const can_remove_entirely =
			(namespace === 'svg' &&
				(parent.type !== 'RegularElement' || parent.name !== 'text') &&
				!path.some((n) => n.type === 'RegularElement' && n.name === 'text')) ||
			(parent.type === 'RegularElement' &&
				// TODO others?
				(parent.name === 'select' ||
					parent.name === 'tr' ||
					parent.name === 'table' ||
					parent.name === 'tbody' ||
					parent.name === 'thead' ||
					parent.name === 'tfoot' ||
					parent.name === 'colgroup' ||
					parent.name === 'datalist'));
 
		// Replace any whitespace between a text and non-text node with a single spaceand keep whitespace
		// as-is within text nodes, or between text nodes and expression tags (because in the end they count
		// as one text). This way whitespace is mostly preserved when using CSS with `white-space: pre-line`
		// and default slot content going into a pre tag (which we can't see).
		for (let i = 0; i < regular.length; i++) {
			const prev = regular[i - 1];
			const node = regular[i];
			const next = regular[i + 1];
 
			if (node.type === 'Text') {
				if (prev?.type !== 'ExpressionTag') {
					const prev_is_text_ending_with_whitespace =
						prev?.type === 'Text' && regex_ends_with_whitespaces.test(prev.data);
					node.data = node.data.replace(
						regex_starts_with_whitespaces,
						prev_is_text_ending_with_whitespace ? '' : ' '
					);
					node.raw = node.raw.replace(
						regex_starts_with_whitespaces,
						prev_is_text_ending_with_whitespace ? '' : ' '
					);
				}
				if (next?.type !== 'ExpressionTag') {
					node.data = node.data.replace(regex_ends_with_whitespaces, ' ');
					node.raw = node.raw.replace(regex_ends_with_whitespaces, ' ');
				}
				if (node.data && (node.data !== ' ' || !can_remove_entirely)) {
					trimmed.push(node);
				}
			} else {
				trimmed.push(node);
			}
		}
	}
 
	var first = trimmed[0];
 
	return {
		hoisted,
		trimmed,
		/**
		 * In a case like `{#if x}<Foo />{/if}`, we don't need to wrap the child in
		 * comments — we can just use the parent block's anchor for the component.
		 * TODO extend this optimisation to other cases
		 */
		is_standalone:
			trimmed.length === 1 &&
			((first.type === 'RenderTag' && !first.metadata.dynamic) ||
				(first.type === 'Component' &&
					!state.options.hmr &&
					!first.metadata.dynamic &&
					!first.attributes.some(
						(attribute) => attribute.type === 'Attribute' && attribute.name.startsWith('--')
					))),
		/** if a component or snippet starts with text, we need to add an anchor comment so that its text node doesn't get fused with its surroundings */
		is_text_first:
			(parent.type === 'Fragment' ||
				parent.type === 'SnippetBlock' ||
				parent.type === 'SvelteComponent' ||
				parent.type === 'Component' ||
				parent.type === 'SvelteSelf') &&
			first &&
			(first?.type === 'Text' || first?.type === 'ExpressionTag')
	};
}
 
/**
 * Infers the namespace for the children of a node that should be used when creating the `$.template(...)`.
 * @param {Namespace} namespace
 * @param {Ast.SvelteNode} parent
 * @param {Ast.SvelteNode[]} nodes
 */
export function infer_namespace(namespace, parent, nodes) {
	if (parent.type === 'RegularElement' && parent.name === 'foreignObject') {
		return 'html';
	}
 
	if (parent.type === 'RegularElement' || parent.type === 'SvelteElement') {
		if (parent.metadata.svg) {
			return 'svg';
		}
		return parent.metadata.mathml ? 'mathml' : 'html';
	}
 
	// Re-evaluate the namespace inside slot nodes that reset the namespace
	if (
		parent.type === 'Fragment' ||
		parent.type === 'Root' ||
		parent.type === 'Component' ||
		parent.type === 'SvelteComponent' ||
		parent.type === 'SvelteFragment' ||
		parent.type === 'SnippetBlock' ||
		parent.type === 'SlotElement'
	) {
		const new_namespace = check_nodes_for_namespace(nodes, 'keep');
		if (new_namespace !== 'keep' && new_namespace !== 'maybe_html') {
			return new_namespace;
		}
	}
 
	return namespace;
}
 
/**
 * Heuristic: Keep current namespace, unless we find a regular element,
 * in which case we always want html, or we only find svg nodes,
 * in which case we assume svg.
 * @param {Ast.SvelteNode[]} nodes
 * @param {Namespace | 'keep' | 'maybe_html'} namespace
 */
function check_nodes_for_namespace(nodes, namespace) {
	/**
	 * @param {Ast.SvelteElement | Ast.RegularElement} node}
	 * @param {{stop: () => void}} context
	 */
	const RegularElement = (node, { stop }) => {
		if (!node.metadata.svg && !node.metadata.mathml) {
			namespace = 'html';
			stop();
		} else if (namespace === 'keep') {
			namespace = node.metadata.svg ? 'svg' : 'mathml';
		}
	};
 
	for (const node of nodes) {
		walk(
			node,
			{},
			{
				_(node, { next }) {
					if (
						node.type === 'EachBlock' ||
						node.type === 'IfBlock' ||
						node.type === 'AwaitBlock' ||
						node.type === 'Fragment' ||
						node.type === 'KeyBlock' ||
						node.type === 'RegularElement' ||
						node.type === 'SvelteElement' ||
						node.type === 'Text'
					) {
						next();
					}
				},
				SvelteElement: RegularElement,
				RegularElement,
				Text(node) {
					if (node.data.trim() !== '') {
						namespace = 'maybe_html';
					}
				}
			}
		);
 
		if (namespace === 'html') return namespace;
	}
 
	return namespace;
}
 
/**
 * Determines the namespace the children of this node are in.
 * @param {Ast.RegularElement | Ast.SvelteElement} node
 * @param {Namespace} namespace
 * @returns {Namespace}
 */
export function determine_namespace_for_children(node, namespace) {
	if (node.name === 'foreignObject') {
		return 'html';
	}
 
	if (node.metadata.svg) {
		return 'svg';
	}
 
	return node.metadata.mathml ? 'mathml' : 'html';
}
 
/**
 * @template {TransformState} T
 * @param {CallExpression} node
 * @param {Context<any, T>} context
 */
export function transform_inspect_rune(node, context) {
	const { state, visit } = context;
	const as_fn = state.options.generate === 'client';
 
	if (!dev) return b.empty;
 
	if (node.callee.type === 'MemberExpression') {
		const raw_inspect_args = /** @type {CallExpression} */ (node.callee.object).arguments;
		const inspect_args =
			/** @type {Array<Expression>} */
			(raw_inspect_args.map((arg) => visit(arg)));
		const with_arg = /** @type {Expression} */ (visit(node.arguments[0]));
 
		return b.call(
			'$.inspect',
			as_fn ? b.thunk(b.array(inspect_args)) : b.array(inspect_args),
			with_arg
		);
	} else {
		const arg = node.arguments.map((arg) => /** @type {Expression} */ (visit(arg)));
		return b.call('$.inspect', as_fn ? b.thunk(b.array(arg)) : b.array(arg));
	}
}