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

98.94% Statements 753/761
94.94% Branches 244/257
100% Functions 17/17
98.94% Lines 750/758

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 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 749 750 751 752 753 754 755 756 757 758 7592x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1439x 1146x 1146x 1146x 1146x 99x 99x 99x 99x 1146x 1439x 293x 293x 293x 14x 293x 12x 12x 12x 12x 2x 2x 2x 2x 12x 292x 281x 281x 1439x 2x 2x 2x 2x 2x 2x 2x 6122x 6122x 1988x 6122x 6122x 2x 2x 2x 2x 2x 2x 2x 13910x 13910x 13910x 3598x 3598x 3598x 10312x 13910x 8x 8x 8x 10304x 13910x 275x 275x 10029x 13910x 1303x 1303x 8726x 13910x 3011x 2857x 2857x 154x 154x 154x 154x 154x     5715x 13910x 9x 9x 5706x 5706x 13910x 13910x 3866x 13910x 1933x 1933x 3773x 3773x 3773x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1805x 1805x 1805x 1805x 1805x 1805x 1753x 1805x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 99x 99x 99x 99x 99x 99x 99x 52x 52x       52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 21x 52x 31x 31x 52x 1753x 1805x     1753x 1753x 1805x 521x 521x 40x 521x 14x 14x 14x 12x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x 7x 7x 7x 7x 7x 7x 7x 4x 4x 7x 7x 7x 12x 521x 507x 507x 25x 507x 12x 12x 12x 12x 12x 12x 12x 10x 12x 9x 9x 9x 9x 9x 9x 9x 9x 9x 12x 521x 1733x 1733x 1733x 1805x 28x 28x 1705x 1705x 1705x 1805x 1699x 1805x 66x 66x 1633x 1805x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1631x 1631x 1805x 1805x 1805x 1805x 1805x 1805x 1805x 1805x 1805x 350x 1805x 284x 284x 284x 1347x 1347x 1347x 1347x 1347x 1126x 1126x 661x 661x 661x 1126x 1126x 323x 1126x 42x 803x 761x 761x 675x 675x 675x 675x 675x 282x 675x 675x 675x 761x 3x 3x 3x 3x 3x 3x 3x 3x 3x 83x 83x 18x 83x 18x 18x 18x 18x 18x 2x 18x 18x 18x 83x 65x 65x 761x 761x 30x 761x 731x 731x 761x 1347x 221x 24x 24x 24x 24x 24x 24x 24x 24x 24x 57x 33x 33x 33x 33x 33x 33x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   57x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 221x 197x 73x 73x 197x 138x 69x 69x 69x 69x 69x 69x 69x 69x 69x 138x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 197x 59x 59x 7x 59x 7x 7x 7x 7x 7x 59x 52x 52x 52x 52x 52x 52x 221x 1347x 1347x 1805x 1x 1x 1346x 1346x 1346x 2x 2x 2x 2x 2x 2x 2x 171x 171x 20x 20x 20x 20x 20x 20x 20x 171x 171x 2x 2x 2x 2x 2x 2x 1266x 1266x 1266x 1266x 1266x 159x 159x 159x 159x 1266x 1107x 1107x 1266x 1266x 170x 170x 170x 170x 170x 170x 170x 170x 1096x 1096x 1096x 2x 2x 2x 2x 2x 2x 191x 191x 191x 191x 191x 191x 191x 191x 191x 191x 191x 213x 213x 213x 213x 191x 191x 278x 278x 278x 212x 6x 6x 6x 6x 6x 6x 212x 212x 212x 212x 212x 212x 212x 212x 212x 1x 212x 1x 212x 211x 211x 24x 211x 5x 211x 206x 206x 206x 200x 200x 200x 200x 200x 1x 1x 200x 212x 278x 191x 191x 2x 2x 2x 2x 2x 2x 2x 191x 191x 191x 191x 191x 191x 191x 180x 167x 167x 167x 191x 11x 11x 11x 11x 191x 191x 191x 191x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2013x 2013x 2013x 2013x 2013x 2013x 69x 69x 2013x 2013x 61x 61x 2013x 2013x 2013x 92x 92x 92x 2013x 1948x 1948x 2013x 2013x 2013x 2013x 2013x 1005x 1005x 777x 1005x 228x 228x 228x 19x 228x 10x 228x 218x 218x 228x 228x 228x 1005x 2013x 2013x 1994x 1994x 1994x 2013x 2013x 2013x 2x 2x 2x 2x 2x 2x 2x 2x 3186x 3186x 3186x 3186x 3186x 3186x 314x 314x 3186x 3186x 3186x 2x 2x 2x 2x 2x 2x 1474x 1474x 1474x 1474x 1474x 1474x 1474x 1474x 783x 1474x 742x 742x 1474x 91x 91x 91x 91x 91x 91x 91x 91x 91x 21x 91x 21x 21x 91x 711x 711x 2x 2x 2x 2x 2x 2x 2x 2x 2x 912x 739x 739x 173x 173x 2x 2x 2x 2x 2x 2x 2x 112x 77x 77x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 97x 89x 89x 89x 89x 35x 35x 35x 2x 2x 2x 2x 2x 2x 2x 389x 389x  
import * as b from '../../../utils/builders.js';
import {
	extract_identifiers,
	extract_paths,
	is_expression_async,
	is_simple_expression,
	object
} from '../../../utils/ast.js';
import {
	PROPS_IS_LAZY_INITIAL,
	PROPS_IS_IMMUTABLE,
	PROPS_IS_RUNES,
	PROPS_IS_UPDATED
} from '../../../../constants.js';
 
/**
 * @template {import('./types').ClientTransformState} State
 * @param {import('estree').AssignmentExpression} node
 * @param {import('zimmerframe').Context<import('#compiler').SvelteNode, State>} context
 * @returns
 */
export function get_assignment_value(node, { state, visit }) {
	if (node.left.type === 'Identifier') {
		const operator = node.operator;
		return operator === '='
			? /** @type {import('estree').Expression} */ (visit(node.right))
			: // turn something like x += 1 into x = x + 1
				b.binary(
					/** @type {import('estree').BinaryOperator} */ (operator.slice(0, -1)),
					serialize_get_binding(node.left, state),
					/** @type {import('estree').Expression} */ (visit(node.right))
				);
	} else if (
		node.left.type === 'MemberExpression' &&
		node.left.object.type === 'ThisExpression' &&
		node.left.property.type === 'PrivateIdentifier' &&
		state.private_state.has(node.left.property.name)
	) {
		const operator = node.operator;
		return operator === '='
			? /** @type {import('estree').Expression} */ (visit(node.right))
			: // turn something like x += 1 into x = x + 1
				b.binary(
					/** @type {import('estree').BinaryOperator} */ (operator.slice(0, -1)),
					/** @type {import('estree').Expression} */ (visit(node.left)),
					/** @type {import('estree').Expression} */ (visit(node.right))
				);
	} else {
		return /** @type {import('estree').Expression} */ (visit(node.right));
	}
}
 
/**
 * @param {import('#compiler').Binding} binding
 * @param {import('./types').ClientTransformState} state
 * @returns {boolean}
 */
export function is_state_source(binding, state) {
	return (
		(binding.kind === 'state' || binding.kind === 'frozen_state') &&
		(!state.analysis.immutable || binding.reassigned || state.analysis.accessors)
	);
}
 
/**
 * @param {import('estree').Identifier} node
 * @param {import('./types').ClientTransformState} state
 * @returns {import('estree').Expression}
 */
export function serialize_get_binding(node, state) {
	const binding = state.scope.get(node.name);
 
	if (binding === null || node === binding.node) {
		// No associated binding or the declaration itself which shouldn't be transformed
		return node;
	}
 
	if (binding.node.name === '$$props') {
		// Special case for $$props which only exists in the old world
		return b.id('$$sanitized_props');
	}
 
	if (binding.kind === 'store_sub') {
		return b.call(node);
	}
 
	if (binding.expression) {
		return typeof binding.expression === 'function' ? binding.expression(node) : binding.expression;
	}
 
	if (binding.kind === 'prop' || binding.kind === 'bindable_prop') {
		if (is_prop_source(binding, state)) {
			return b.call(node);
		}
 
		if (binding.prop_alias) {
			const key = b.key(binding.prop_alias);
			return b.member(b.id('$$props'), key, key.type === 'Literal');
		}
		return b.member(b.id('$$props'), node);
	}
 
	if (binding.kind === 'legacy_reactive_import') {
		return b.call('$$_import_' + node.name);
	}
 
	if (
		is_state_source(binding, state) ||
		binding.kind === 'derived' ||
		binding.kind === 'legacy_reactive'
	) {
		return b.call('$.get', node);
	}
 
	return node;
}
 
/**
 * @template {import('./types').ClientTransformState} State
 * @param {import('estree').AssignmentExpression} node
 * @param {import('zimmerframe').Context<import('#compiler').SvelteNode, State>} context
 * @param {() => any} fallback
 * @param {boolean | null} [prefix] - If the assignment is a transformed update expression, set this. Else `null`
 * @param {{skip_proxy_and_freeze?: boolean}} [options]
 * @returns {import('estree').Expression}
 */
export function serialize_set_binding(node, context, fallback, prefix, options) {
	const { state, visit } = context;
 
	const assignee = node.left;
	if (
		assignee.type === 'ArrayPattern' ||
		assignee.type === 'ObjectPattern' ||
		assignee.type === 'RestElement'
	) {
		// Turn assignment into an IIFE, so that `$.set` calls etc don't produce invalid code
		const tmp_id = context.state.scope.generate('tmp');
 
		/** @type {import('estree').AssignmentExpression[]} */
		const original_assignments = [];
 
		/** @type {import('estree').Expression[]} */
		const assignments = [];
 
		const paths = extract_paths(assignee);
 
		for (const path of paths) {
			const value = path.expression?.(b.id(tmp_id));
			const assignment = b.assignment('=', path.node, value);
			original_assignments.push(assignment);
			assignments.push(
				serialize_set_binding(assignment, context, () => assignment, prefix, options)
			);
		}
 
		if (assignments.every((assignment, i) => assignment === original_assignments[i])) {
			// No change to output -> nothing to transform -> we can keep the original assignment
			return fallback();
		}
 
		const rhs_expression = /** @type {import('estree').Expression} */ (visit(node.right));
 
		const iife_is_async =
			is_expression_async(rhs_expression) ||
			assignments.some((assignment) => is_expression_async(assignment));
 
		const iife = b.arrow(
			[],
			b.block([
				b.const(tmp_id, rhs_expression),
				b.stmt(b.sequence(assignments)),
				// return because it could be used in a nested expression where the value is needed.
				// example: { foo: ({ bar } = { bar: 1 })}
				b.return(b.id(tmp_id))
			])
		);
 
		if (iife_is_async) {
			return b.await(b.call(b.async(iife)));
		} else {
			return b.call(iife);
		}
	}
 
	if (assignee.type !== 'Identifier' && assignee.type !== 'MemberExpression') {
		throw new Error(`Unexpected assignment type ${assignee.type}`);
	}
 
	// Handle class private/public state assignment cases
	if (assignee.type === 'MemberExpression') {
		if (
			assignee.object.type === 'ThisExpression' &&
			assignee.property.type === 'PrivateIdentifier'
		) {
			const private_state = context.state.private_state.get(assignee.property.name);
			const value = get_assignment_value(node, context);
			if (private_state !== undefined) {
				if (state.in_constructor) {
					// See if we should wrap value in $.proxy
					if (
						context.state.analysis.runes &&
						!options?.skip_proxy_and_freeze &&
						should_proxy_or_freeze(value, context.state.scope)
					) {
						const assignment = fallback();
						if (assignment.type === 'AssignmentExpression') {
							assignment.right =
								private_state.kind === 'frozen_state'
									? b.call('$.freeze', value)
									: serialize_proxy_reassignment(value, private_state.id, state);
							return assignment;
						}
					}
				} else {
					return b.call(
						'$.set',
						assignee,
						context.state.analysis.runes &&
							!options?.skip_proxy_and_freeze &&
							should_proxy_or_freeze(value, context.state.scope)
							? private_state.kind === 'frozen_state'
								? b.call('$.freeze', value)
								: serialize_proxy_reassignment(value, private_state.id, state)
							: value
					);
				}
			}
		} else if (
			assignee.object.type === 'ThisExpression' &&
			assignee.property.type === 'Identifier' &&
			state.in_constructor
		) {
			const public_state = context.state.public_state.get(assignee.property.name);
			const value = get_assignment_value(node, context);
			// See if we should wrap value in $.proxy
			if (
				context.state.analysis.runes &&
				public_state !== undefined &&
				!options?.skip_proxy_and_freeze &&
				should_proxy_or_freeze(value, context.state.scope)
			) {
				const assignment = fallback();
				if (assignment.type === 'AssignmentExpression') {
					assignment.right =
						public_state.kind === 'frozen_state'
							? b.call('$.freeze', value)
							: serialize_proxy_reassignment(value, public_state.id, state);
					return assignment;
				}
			}
		}
	}
 
	const left = object(assignee);
 
	if (left === null) {
		return fallback();
	}
 
	const binding = state.scope.get(left.name);
 
	if (!binding) return fallback();
 
	if (binding.mutation !== null) {
		return binding.mutation(node, context);
	}
 
	if (binding.kind === 'legacy_reactive_import') {
		return b.call(
			'$$_import_' + binding.node.name,
			b.assignment(
				node.operator,
				/** @type {import('estree').Pattern} */ (visit(node.left)),
				/** @type {import('estree').Expression} */ (visit(node.right))
			)
		);
	}
 
	const is_store = binding.kind === 'store_sub';
	const left_name = is_store ? left.name.slice(1) : left.name;
 
	if (
		binding.kind !== 'state' &&
		binding.kind !== 'frozen_state' &&
		binding.kind !== 'prop' &&
		binding.kind !== 'bindable_prop' &&
		binding.kind !== 'each' &&
		binding.kind !== 'legacy_reactive' &&
		!is_store
	) {
		// TODO error if it's a computed (or rest prop)? or does that already happen elsewhere?
		return fallback();
	}
 
	const value = get_assignment_value(node, context);
 
	const serialize = () => {
		if (left === node.left) {
			const is_initial_proxy =
				binding.initial !== null &&
				should_proxy_or_freeze(
					/**@type {import("estree").Expression}*/ (binding.initial),
					context.state.scope
				);
			if ((binding.kind === 'prop' || binding.kind === 'bindable_prop') && !is_initial_proxy) {
				return b.call(left, value);
			} else if (is_store) {
				return b.call('$.store_set', serialize_get_binding(b.id(left_name), state), value);
			} else {
				let call;
				if (binding.kind === 'state') {
					call = b.call(
						'$.set',
						b.id(left_name),
						context.state.analysis.runes &&
							!options?.skip_proxy_and_freeze &&
							should_proxy_or_freeze(value, context.state.scope)
							? serialize_proxy_reassignment(value, left_name, state)
							: value
					);
				} else if (binding.kind === 'frozen_state') {
					call = b.call(
						'$.set',
						b.id(left_name),
						context.state.analysis.runes &&
							!options?.skip_proxy_and_freeze &&
							should_proxy_or_freeze(value, context.state.scope)
							? b.call('$.freeze', value)
							: value
					);
				} else if (
					(binding.kind === 'prop' || binding.kind === 'bindable_prop') &&
					is_initial_proxy
				) {
					call = b.call(
						left,
						context.state.analysis.runes &&
							!options?.skip_proxy_and_freeze &&
							should_proxy_or_freeze(value, context.state.scope) &&
							binding.kind === 'bindable_prop'
							? serialize_proxy_reassignment(value, left_name, state)
							: value
					);
				} else {
					call = b.call('$.set', b.id(left_name), value);
				}
 
				if (state.scope.get(`$${left.name}`)?.kind === 'store_sub') {
					return b.call('$.store_unsub', call, b.literal(`$${left.name}`), b.id('$$stores'));
				} else {
					return call;
				}
			}
		} else {
			if (is_store) {
				// If we are assigning to a store property, we need to ensure we don't
				// capture the read for the store as part of the member expression to
				// keep consistency with how store $ shorthand reads work in Svelte 4.
				/**
				 *
				 * @param {import("estree").Expression | import("estree").Pattern} node
				 * @returns {import("estree").Expression}
				 */
				function visit_node(node) {
					if (node.type === 'MemberExpression') {
						return {
							...node,
							object: visit_node(/** @type {import("estree").Expression} */ (node.object)),
							property: /** @type {import("estree").MemberExpression} */ (visit(node)).property
						};
					}
					if (node.type === 'Identifier') {
						const binding = state.scope.get(node.name);
 
						if (binding !== null && binding.kind === 'store_sub') {
							return b.call(
								'$.untrack',
								b.thunk(/** @type {import('estree').Expression} */ (visit(node)))
							);
						}
					}
					return /** @type {import("estree").Expression} */ (visit(node));
				}
 
				return b.call(
					'$.mutate_store',
					serialize_get_binding(b.id(left_name), state),
					b.assignment(
						node.operator,
						/** @type {import("estree").Pattern}} */ (visit_node(node.left)),
						value
					),
					b.call('$.untrack', b.id('$' + left_name))
				);
			} else if (
				!state.analysis.runes ||
				// this condition can go away once legacy mode is gone; only necessary for interop with legacy parent bindings
				(binding.mutated && binding.kind === 'bindable_prop')
			) {
				if (binding.kind === 'bindable_prop') {
					return b.call(
						left,
						b.assignment(
							node.operator,
							/** @type {import('estree').Pattern} */ (visit(node.left)),
							value
						),
						b.true
					);
				} else {
					return b.call(
						'$.mutate',
						b.id(left_name),
						b.assignment(
							node.operator,
							/** @type {import('estree').Pattern} */ (visit(node.left)),
							value
						)
					);
				}
			} else if (
				node.right.type === 'Literal' &&
				prefix != null &&
				(node.operator === '+=' || node.operator === '-=')
			) {
				return b.update(
					node.operator === '+=' ? '++' : '--',
					/** @type {import('estree').Expression} */ (visit(node.left)),
					prefix
				);
			} else {
				return b.assignment(
					node.operator,
					/** @type {import('estree').Pattern} */ (visit(node.left)),
					/** @type {import('estree').Expression} */ (visit(node.right))
				);
			}
		}
	};
 
	if (value.type === 'BinaryExpression' && /** @type {any} */ (value.operator) === '??') {
		return b.logical('??', serialize_get_binding(b.id(left_name), state), serialize());
	}
 
	return serialize();
}
 
/**
 * @param {import('estree').Expression} value
 * @param {import('estree').PrivateIdentifier | string} proxy_reference
 * @param {import('./types').ClientTransformState} state
 */
export function serialize_proxy_reassignment(value, proxy_reference, state) {
	return state.options.dev
		? b.call(
				'$.proxy',
				value,
				b.null,
				typeof proxy_reference === 'string'
					? b.id(proxy_reference)
					: b.member(b.this, proxy_reference)
			)
		: b.call('$.proxy', value);
}
 
/**
 * @param {import('estree').ArrowFunctionExpression | import('estree').FunctionExpression} node
 * @param {import('./types').ComponentContext} context
 */
export const function_visitor = (node, context) => {
	const metadata = node.metadata;
 
	let state = context.state;
 
	if (node.type === 'FunctionExpression') {
		const parent = /** @type {import('estree').Node} */ (context.path.at(-1));
		const in_constructor = parent.type === 'MethodDefinition' && parent.kind === 'constructor';
 
		state = { ...context.state, in_constructor };
	} else {
		state = { ...context.state, in_constructor: false };
	}
 
	if (metadata?.hoistable === true) {
		const params = serialize_hoistable_params(node, context);
 
		return /** @type {import('estree').FunctionExpression} */ ({
			...node,
			params,
			body: context.visit(node.body, state)
		});
	}
 
	context.next(state);
};
 
/**
 * @param {import('estree').FunctionDeclaration | import('estree').FunctionExpression | import('estree').ArrowFunctionExpression} node
 * @param {import('./types').ComponentContext} context
 * @returns {import('estree').Pattern[]}
 */
function get_hoistable_params(node, context) {
	const scope = context.state.scope;
 
	/** @type {import('estree').Identifier[]} */
	const params = [];
 
	/**
	 * We only want to push if it's not already present to avoid name clashing
	 * @param {import('estree').Identifier} id
	 */
	function push_unique(id) {
		if (!params.find((param) => param.name === id.name)) {
			params.push(id);
		}
	}
 
	for (const [reference] of scope.references) {
		let binding = scope.get(reference);
 
		if (binding !== null && !scope.declarations.has(reference) && binding.initial !== node) {
			if (binding.kind === 'store_sub') {
				// We need both the subscription for getting the value and the store for updating
				push_unique(b.id(binding.node.name));
				binding = /** @type {import('#compiler').Binding} */ (
					scope.get(binding.node.name.slice(1))
				);
			}
 
			if (
				// If it's a destructured derived binding, then we can extract the derived signal reference and use that.
				binding.expression !== null &&
				typeof binding.expression !== 'function' &&
				binding.expression.type === 'MemberExpression' &&
				binding.expression.object.type === 'CallExpression' &&
				binding.expression.object.callee.type === 'Identifier' &&
				binding.expression.object.callee.name === '$.get' &&
				binding.expression.object.arguments[0].type === 'Identifier'
			) {
				push_unique(b.id(binding.expression.object.arguments[0].name));
			} else if (
				// If we are referencing a simple $$props value, then we need to reference the object property instead
				(binding.kind === 'prop' || binding.kind === 'bindable_prop') &&
				!is_prop_source(binding, context.state)
			) {
				push_unique(b.id('$$props'));
			} else if (
				// imports don't need to be hoisted
				binding.declaration_kind !== 'import'
			) {
				// create a copy to remove start/end tags which would mess up source maps
				push_unique(b.id(binding.node.name));
				// rest props are often accessed through the $$props object for optimization reasons,
				// but we can't know if the delegated event handler will use it, so we need to add both as params
				if (binding.kind === 'rest_prop' && context.state.analysis.runes) {
					push_unique(b.id('$$props'));
				}
			}
		}
	}
	return params;
}
 
/**
 * @param {import('estree').FunctionDeclaration | import('estree').FunctionExpression | import('estree').ArrowFunctionExpression} node
 * @param {import('./types').ComponentContext} context
 * @returns {import('estree').Pattern[]}
 */
export function serialize_hoistable_params(node, context) {
	const hoistable_params = get_hoistable_params(node, context);
	node.metadata.hoistable_params = hoistable_params;
 
	/** @type {import('estree').Pattern[]} */
	const params = [];
 
	if (node.params.length === 0) {
		if (hoistable_params.length > 0) {
			// For the event object
			params.push(b.id('_'));
		}
	} else {
		for (const param of node.params) {
			params.push(/** @type {import('estree').Pattern} */ (context.visit(param)));
		}
	}
 
	params.push(...hoistable_params);
	return params;
}
 
/**
 * @param {import('#compiler').Binding} binding
 * @param {import('./types').ComponentClientTransformState} state
 * @param {string} name
 * @param {import('estree').Expression | null} [initial]
 * @returns
 */
export function get_prop_source(binding, state, name, initial) {
	/** @type {import('estree').Expression[]} */
	const args = [b.id('$$props'), b.literal(name)];
 
	let flags = 0;
 
	if (state.analysis.immutable) {
		flags |= PROPS_IS_IMMUTABLE;
	}
 
	if (state.analysis.runes) {
		flags |= PROPS_IS_RUNES;
	}
 
	if (
		state.analysis.accessors ||
		(state.analysis.immutable
			? binding.reassigned || (state.analysis.runes && binding.mutated)
			: binding.mutated)
	) {
		flags |= PROPS_IS_UPDATED;
	}
 
	/** @type {import('estree').Expression | undefined} */
	let arg;
 
	if (initial) {
		// To avoid eagerly evaluating the right-hand-side, we wrap it in a thunk if necessary
		if (is_simple_expression(initial)) {
			arg = initial;
		} else {
			if (
				initial.type === 'CallExpression' &&
				initial.callee.type === 'Identifier' &&
				initial.arguments.length === 0
			) {
				arg = initial.callee;
			} else {
				arg = b.thunk(initial);
			}
 
			flags |= PROPS_IS_LAZY_INITIAL;
		}
	}
 
	if (flags || arg) {
		args.push(b.literal(flags));
		if (arg) args.push(arg);
	}
 
	return b.call('$.prop', ...args);
}
 
/**
 *
 * @param {import('#compiler').Binding} binding
 * @param {import('./types').ClientTransformState} state
 * @returns
 */
export function is_prop_source(binding, state) {
	return (
		(binding.kind === 'prop' || binding.kind === 'bindable_prop') &&
		(!state.analysis.runes ||
			state.analysis.accessors ||
			binding.reassigned ||
			binding.initial ||
			// Until legacy mode is gone, we also need to use the prop source when only mutated is true,
			// because the parent could be a legacy component which needs coarse-grained reactivity
			binding.mutated)
	);
}
 
/**
 * @param {import('estree').Expression} node
 * @param {import("../../scope.js").Scope | null} scope
 */
export function should_proxy_or_freeze(node, scope) {
	if (
		!node ||
		node.type === 'Literal' ||
		node.type === 'TemplateLiteral' ||
		node.type === 'ArrowFunctionExpression' ||
		node.type === 'FunctionExpression' ||
		node.type === 'UnaryExpression' ||
		node.type === 'BinaryExpression' ||
		(node.type === 'Identifier' && node.name === 'undefined')
	) {
		return false;
	}
	if (node.type === 'Identifier' && scope !== null) {
		const binding = scope.get(node.name);
		// Let's see if the reference is something that can be proxied or frozen
		if (
			binding !== null &&
			!binding.reassigned &&
			binding.initial !== null &&
			binding.initial.type !== 'FunctionDeclaration' &&
			binding.initial.type !== 'ClassDeclaration' &&
			binding.initial.type !== 'ImportDeclaration' &&
			binding.initial.type !== 'EachBlock'
		) {
			return should_proxy_or_freeze(binding.initial, null);
		}
	}
	return true;
}
 
/**
 * Port over the location information from the source to the target identifier.
 * but keep the target as-is (i.e. a new id is created).
 * This ensures esrap can generate accurate source maps.
 * @param {import('estree').Identifier} target
 * @param {import('estree').Identifier} source
 */
export function with_loc(target, source) {
	if (source.loc) {
		return { ...target, loc: source.loc };
	}
	return target;
}
 
/**
 * @param {import("estree").Pattern} node
 * @param {import("zimmerframe").Context<import("#compiler").SvelteNode, import("./types").ComponentClientTransformState>} context
 * @returns {{ id: import("estree").Pattern, declarations: null | import("estree").Statement[] }}
 */
export function create_derived_block_argument(node, context) {
	if (node.type === 'Identifier') {
		return { id: node, declarations: null };
	}
 
	const pattern = /** @type {import('estree').Pattern} */ (context.visit(node));
	const identifiers = extract_identifiers(node);
 
	const id = b.id('$$source');
	const value = b.id('$$value');
 
	const block = b.block([
		b.var(pattern, b.call('$.get', id)),
		b.return(b.object(identifiers.map((identifier) => b.prop('init', identifier, identifier))))
	]);
 
	const declarations = [b.var(value, create_derived(context.state, b.thunk(block)))];
 
	for (const id of identifiers) {
		declarations.push(
			b.var(id, create_derived(context.state, b.thunk(b.member(b.call('$.get', value), id))))
		);
	}
 
	return { id, declarations };
}
 
/**
 * Svelte legacy mode should use safe equals in most places, runes mode shouldn't
 * @param {import('./types.js').ComponentClientTransformState} state
 * @param {import('estree').Expression} arg
 */
export function create_derived(state, arg) {
	return b.call(state.analysis.runes ? '$.derived' : '$.derived_safe_equal', arg);
}