Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

utils.ts

756 lines21.4 KB

1import { isServer } from '@tanstack/router-core/isServer'
2import type { RouteIds } from './routeInfo'
3import type { AnyRouter } from './router'
4​
5export type Awaitable<T> = T | Promise<T>
6export type NoInfer<T> = [T][T extends any ? 0 : never]
7export type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue
8 ? TYesResult
9 : TNoResult
10​
11export type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<
12 TValue,
13 TKey
14> &
15 Required<Pick<TValue, TKey>>
16​
17export type PickRequired<T> = {
18 [K in keyof T as undefined extends T[K] ? never : K]: T[K]
20​
21export type PickOptional<T> = {
22 [K in keyof T as undefined extends T[K] ? K : never]: T[K]
24​
25// from https://stackoverflow.com/a/76458160
26export type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never
27​
28export type Expand<T> = T extends object
29 ? T extends infer O
30 ? O extends Function
31 ? O
32 : { [K in keyof O]: O[K] }
33 : never
34 : T
35​
36export type DeepPartial<T> = T extends object
37 ? {
38 [P in keyof T]?: DeepPartial<T[P]>
39 }
40 : T
41​
42export type MakeDifferenceOptional<TLeft, TRight> = keyof TLeft &
43 keyof TRight extends never
44 ? TRight
45 : Omit<TRight, keyof TLeft & keyof TRight> & {
46 [K in keyof TLeft & keyof TRight]?: TRight[K]
47 }
48​
49// from https://stackoverflow.com/a/53955431
50// eslint-disable-next-line @typescript-eslint/naming-convention
51export type IsUnion<T, U extends T = T> = (
52 T extends any ? (U extends T ? false : true) : never
53) extends false
54 ? false
55 : true
56​
57export type IsNonEmptyObject<T> = T extends object
58 ? keyof T extends never
59 ? false
60 : true
61 : false
62​
63export type Assign<TLeft, TRight> = TLeft extends any
64 ? TRight extends any
65 ? IsNonEmptyObject<TLeft> extends false
66 ? TRight
67 : IsNonEmptyObject<TRight> extends false
68 ? TLeft
69 : keyof TLeft & keyof TRight extends never
70 ? TLeft & TRight
71 : Omit<TLeft, keyof TRight> & TRight
72 : never
73 : never
74​
75export type IntersectAssign<TLeft, TRight> = TLeft extends any
76 ? TRight extends any
77 ? IsNonEmptyObject<TLeft> extends false
78 ? TRight
79 : IsNonEmptyObject<TRight> extends false
80 ? TLeft
81 : TRight & TLeft
82 : never
83 : never
84​
85export type Timeout = ReturnType<typeof setTimeout>
86​
87export type Updater<TPrevious, TResult = TPrevious> =
88 | TResult
89 | ((prev?: TPrevious) => TResult)
90​
91export type NonNullableUpdater<TPrevious, TResult = TPrevious> =
92 | TResult
93 | ((prev: TPrevious) => TResult)
94​
95export type ExtractObjects<TUnion> = TUnion extends MergeAllPrimitive
96 ? never
97 : TUnion
98​
99export type PartialMergeAllObject<TUnion> =
100 ExtractObjects<TUnion> extends infer TObj
101 ? [TObj] extends [never]
102 ? never
103 : {
104 [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any
105 ? TKey extends keyof TObj
106 ? TObj[TKey]
107 : never
108 : never
109 }
110 : never
111​
112export type MergeAllPrimitive =
113 | ReadonlyArray<any>
114 | number
115 | string
116 | bigint
117 | boolean
118 | symbol
119 | undefined
120 | null
121​
122export type ExtractPrimitives<TUnion> = TUnion extends MergeAllPrimitive
123 ? TUnion
124 : TUnion extends object
125 ? never
126 : TUnion
127​
128export type PartialMergeAll<TUnion> =
129 | ExtractPrimitives<TUnion>
130 | PartialMergeAllObject<TUnion>
131​
132export type Constrain<T, TConstraint, TDefault = TConstraint> =
133 | (T extends TConstraint ? T : never)
134 | TDefault
135​
136export type ConstrainLiteral<T, TConstraint, TDefault = TConstraint> =
137 | (T & TConstraint)
138 | TDefault
139​
140/**
141 * To be added to router types
142 */
143export type UnionToIntersection<T> = (
144 T extends any ? (arg: T) => any : never
145) extends (arg: infer T) => any
146 ? T
147 : never
148​
149/**
150 * Merges everything in a union into one object.
151 * This mapped type is homomorphic which means it preserves stuff! :)
152 */
153export type MergeAllObjects<
154 TUnion,
155 TIntersected = UnionToIntersection<ExtractObjects<TUnion>>,
156> = [keyof TIntersected] extends [never]
157 ? never
158 : {
159 [TKey in keyof TIntersected]: TUnion extends any
160 ? TUnion[TKey & keyof TUnion]
161 : never
162 }
163​
164export type MergeAll<TUnion> =
165 | MergeAllObjects<TUnion>
166 | ExtractPrimitives<TUnion>
167​
168export type ValidateJSON<T> = ((...args: Array<any>) => any) extends T
169 ? unknown extends T
170 ? never
171 : 'Function is not serializable'
172 : { [K in keyof T]: ValidateJSON<T[K]> }
173​
174export type LooseReturnType<T> = T extends (
175 ...args: Array<any>
176) => infer TReturn
177 ? TReturn
178 : never
179​
180export type LooseAsyncReturnType<T> = T extends (
181 ...args: Array<any>
182) => infer TReturn
183 ? TReturn extends Promise<infer TReturn>
184 ? TReturn
185 : TReturn
186 : never
187​
188/**
189 * Return the last element of an array.
190 * Intended for non-empty arrays used within router internals.
191 */
192export function last<T>(arr: ReadonlyArray<T>) {
193 return arr[arr.length - 1]
195​
196/**
197 * Apply a value-or-updater to a previous value.
198 * Accepts either a literal value or a function of the previous value.
199 */
200export function functionalUpdate<TPrevious, TResult = TPrevious>(
201 updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>,
202 previous: TPrevious,
203): TResult {
204 if (typeof updater === 'function') {
205 return (updater as Function)(previous)
206 }
207​
208 return updater
210​
211export const hasOwn = Object.prototype.hasOwnProperty
212const isEnumerable = Object.prototype.propertyIsEnumerable
213​
214export function hasKeys(obj: Record<string, unknown>) {
215 for (const key in obj) {
216 if (hasOwn.call(obj, key)) return true
217 }
218 return false
220​
221export const createNull = () => Object.create(null)
222export const nullReplaceEqualDeep: typeof replaceEqualDeep = (prev, next) =>
223 replaceEqualDeep(prev, next, createNull)
224​
225/**
226 * This function returns `prev` if `_next` is deeply equal.
227 * If not, it will replace any deeply equal children of `b` with those of `a`.
228 * This can be used for structural sharing between immutable JSON values for example.
229 * Do not use this with signals
230 */
231export function replaceEqualDeep<T>(
232 prev: any,
233 _next: T,
234 _makeObj = () => ({}),
235 _depth = 0,
236): T {
237 if (isServer) {
238 return _next
239 }
240 if (prev === _next) {
241 return prev
242 }
243​
244 if (_depth > 500) return _next
245​
246 const next = _next as any
247​
248 const array = isPlainArray(prev) && isPlainArray(next)
249​
250 if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next
251​
252 const prevItems = array ? prev : getEnumerableOwnKeys(prev)
253 if (!prevItems) return next
254 const nextItems = array ? next : getEnumerableOwnKeys(next)
255 if (!nextItems) return next
256 const prevSize = prevItems.length
257 const nextSize = nextItems.length
258 const copy: any = array ? new Array(nextSize) : _makeObj()
259​
260 let equalItems = 0
261​
262 for (let i = 0; i < nextSize; i++) {
263 const key = array ? i : (nextItems[i] as any)
264 const p = prev[key]
265 const n = next[key]
266​
267 if (p === n) {
268 copy[key] = p
269 if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++
270 continue
271 }
272​
273 if (
274 p === null ||
275 n === null ||
276 typeof p !== 'object' ||
277 typeof n !== 'object'
278 ) {
279 copy[key] = n
280 continue
281 }
282​
283 const v = replaceEqualDeep(p, n, _makeObj, _depth + 1)
284 copy[key] = v
285 if (v === p) equalItems++
286 }
287​
288 return prevSize === nextSize && equalItems === prevSize ? prev : copy
290​
291/**
292 * Equivalent to `Reflect.ownKeys`, but ensures that objects are "clone-friendly":
293 * will return false if object has any non-enumerable properties.
294 *
295 * Optimized for the common case where objects have no symbol properties.
296 */
297function getEnumerableOwnKeys(o: object) {
298 // `Object.keys` returns only enumerable own string keys natively (no per-key
299 // JS callback). If it has fewer entries than `getOwnPropertyNames` (all own
300 // string keys), the object has a non-enumerable own string prop and is not
301 // "clone-friendly" -> bail. This replaces an O(n) loop of
302 // `propertyIsEnumerable` calls with two native calls.
303 const keys = Object.keys(o)
304 if (keys.length !== Object.getOwnPropertyNames(o).length) {
305 return false
306 }
307​
308 // Only check symbols if the object has any (most plain objects don't)
309 const symbols = Object.getOwnPropertySymbols(o)
310​
311 // Fast path: no symbols, return enumerable string keys directly
312 if (symbols.length === 0) {
313 return keys
314 }
315​
316 // Slow path: has symbols, include only enumerable ones, bail on any
317 // non-enumerable symbol so it round-trips like the string-key check above.
318 for (const symbol of symbols) {
319 if (!isEnumerable.call(o, symbol)) {
320 return false
321 }
322 ;(keys as Array<string | symbol>).push(symbol)
323 }
324 return keys
326​
327// Copied from: https://github.com/jonschlinkert/is-plain-object
328export function isPlainObject(o: any) {
329 if (!hasObjectPrototype(o)) {
330 return false
331 }
332​
333 // If has modified constructor
334 const ctor = o.constructor
335 if (typeof ctor === 'undefined') {
336 return true
337 }
338​
339 // If has modified prototype
340 const prot = ctor.prototype
341 if (!hasObjectPrototype(prot)) {
342 return false
343 }
344​
345 // If constructor does not have an Object-specific method
346 if (!prot.hasOwnProperty('isPrototypeOf')) {
347 return false
348 }
349​
350 // Most likely a plain Object
351 return true
353​
354function hasObjectPrototype(o: any) {
355 return Object.prototype.toString.call(o) === '[object Object]'
357​
358/**
359 * Check if a value is a "plain" array (no extra enumerable keys).
360 */
361export function isPlainArray(value: unknown): value is Array<unknown> {
362 return Array.isArray(value) && value.length === Object.keys(value).length
364​
365/**
366 * Perform a deep equality check optimized for router state comparisons.
367 *
368 * - `partial`: `b` may omit keys that `a` has (arrays stay length-exact).
369 * - `explicitUndefined`: keys holding `undefined` take part in the comparison
370 * instead of being ignored.
371 *
372 * Internal: the flags are positional so hot callers pass no options object.
373 */
374export function deepEqual(
375 a: any,
376 b: any,
377 partial?: boolean,
378 explicitUndefined?: boolean,
379): boolean {
380 if (a === b) {
381 return true
382 }
383​
384 if (Array.isArray(a) && Array.isArray(b)) {
385 if (a.length !== b.length) return false
386 for (let i = 0, l = a.length; i < l; i++) {
387 const av = a[i]
388 const bv = b[i]
389 if (av !== bv && !deepEqual(av, bv, partial, explicitUndefined)) {
390 return false
391 }
392 }
393 return true
394 }
395​
396 if (isPlainObject(a) && isPlainObject(b)) {
397 if (partial) {
398 for (const k in b) {
399 if (explicitUndefined || b[k] !== undefined) {
400 if (!deepEqual(a[k], b[k], partial, explicitUndefined)) return false
401 }
402 }
403 return true
404 }
405​
406 let aCount = 0
407 if (explicitUndefined) {
408 aCount = Object.keys(a).length
409 } else {
410 for (const k in a) {
411 if (a[k] !== undefined) aCount++
412 }
413 }
414​
415 for (const k in b) {
416 if (explicitUndefined || b[k] !== undefined) {
417 if (
418 aCount-- === 0 ||
419 !deepEqual(a[k], b[k], partial, explicitUndefined)
420 ) {
421 return false
422 }
423 }
424 }
425​
426 return aCount === 0
427 }
428​
429 return false
431​
432export type StringLiteral<T> = T extends string
433 ? string extends T
434 ? string
435 : T
436 : never
437​
438export type ThrowOrOptional<T, TThrow extends boolean> = TThrow extends true
439 ? T
440 : T | undefined
441​
442export type StrictOrFrom<
443 TRouter extends AnyRouter,
444 TFrom,
445 TStrict extends boolean = true,
446> = TStrict extends false
447 ? {
448 from?: never
449 strict: TStrict
450 }
451 : {
452 from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>
453 strict?: TStrict
454 }
455​
456export type ThrowConstraint<
457 TStrict extends boolean,
458 TThrow extends boolean,
459> = TStrict extends false ? (TThrow extends true ? never : TThrow) : TThrow
460​
461export type ControlledPromise<T> = Promise<T> & {
462 resolve: (value: T) => void
463 reject: (value: any) => void
464 status: 'pending' | 'resolved' | 'rejected'
465 value?: T
467​
468/**
469 * Create a promise with exposed resolve/reject and status fields.
470 * Useful for coordinating async router lifecycle operations.
471 */
472export function createControlledPromise<T>(onResolve?: (value: T) => void) {
473 let resolveLoadPromise!: (value: T) => void
474 let rejectLoadPromise!: (value: any) => void
475​
476 const controlledPromise = new Promise<T>((resolve, reject) => {
477 resolveLoadPromise = resolve
478 rejectLoadPromise = reject
479 }) as ControlledPromise<T>
480​
481 controlledPromise.status = 'pending'
482​
483 controlledPromise.resolve = (value: T) => {
484 controlledPromise.status = 'resolved'
485 controlledPromise.value = value
486 resolveLoadPromise(value)
487 onResolve?.(value)
488 }
489​
490 controlledPromise.reject = (e) => {
491 controlledPromise.status = 'rejected'
492 rejectLoadPromise(e)
493 }
494​
495 return controlledPromise
497​
498/**
499 * Heuristically detect dynamic import "module not found" errors
500 * across major browsers for lazy route component handling.
501 */
502export function isModuleNotFoundError(error: any): boolean {
503 // chrome: "Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
504 // firefox: "error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
505 // safari: "Importing a module script failed."
506 if (typeof error?.message !== 'string') return false
507 return (
508 error.message.startsWith('Failed to fetch dynamically imported module') ||
509 error.message.startsWith('error loading dynamically imported module') ||
510 error.message.startsWith('Importing a module script failed')
511 )
513​
514export function isPromise<T>(
515 value: Promise<Awaited<T>> | T,
516): value is Promise<Awaited<T>> {
517 return Boolean(
518 value &&
519 typeof value === 'object' &&
520 typeof (value as Promise<T>).then === 'function',
521 )
523​
524export function findLast<T>(
525 array: ReadonlyArray<T>,
526 predicate: (item: T) => boolean,
527): T | undefined {
528 for (let i = array.length - 1; i >= 0; i--) {
529 const item = array[i]!
530 if (predicate(item)) return item
531 }
532 return undefined
534​
535/**
536 * Re-encode characters that are unsafe in URL paths.
537 * Includes ASCII control characters (0x00-0x1F, 0x7F) and a subset of the
538 * WHATWG URL "path percent-encode set" (", <, >, `, {, }).
539 *
540 * Space (0x20) is intentionally excluded β€” decodeURI decodes %20 to space
541 * and the router stores decoded spaces in location.pathname. The existing
542 * encodePathLikeUrl already handles re-encoding spaces for outgoing URLs.
543 *
544 * These characters are decoded by decodeURI but must remain percent-encoded
545 * in paths to match how upstream layers (CDNs, edge middleware, browsers)
546 * interpret the URL, preventing infinite redirect loops and path mismatches.
547 */
548// eslint-disable-next-line no-control-regex
549const PATH_UNSAFE_RE = /[\x00-\x1f\x7f"<>`{}]/g
550​
551function sanitizePathSegment(segment: string): string {
552 return segment.replace(
553 PATH_UNSAFE_RE,
554 (ch) => '%' + ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0'),
555 )
557​
558function decodeSegment(segment: string): string {
559 let decoded: string
560 try {
561 decoded = decodeURI(segment)
562 } catch {
563 // if the decoding fails, try to decode the various parts leaving the malformed tags in place
564 decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {
565 try {
566 return decodeURI(match)
567 } catch {
568 return match
569 }
570 })
571 }
572 return sanitizePathSegment(decoded)
574​
575/**
576 * Default list of URL protocols to allow in links, redirects, and navigation.
577 * Any absolute URL protocol not in this list is treated as dangerous by default.
578 */
579export const DEFAULT_PROTOCOL_ALLOWLIST = [
580 // Standard web navigation
581 'http:',
582 'https:',
583​
584 // Common browser-safe actions
585 'mailto:',
586 'tel:',
588​
589/**
590 * Extract the explicit URL scheme, including its colon, using WHATWG
591 * normalization rules. This does not validate the rest of the URL.
592 *
593 * Returning `undefined` means "no explicit scheme", not "safe URL";
594 * protocol-relative URLs such as "//evil.example" require a separate check.
595 */
596export function getUrlScheme(url: string): string | undefined {
597 if (url[0] === '/') {
598 return undefined
599 }
600 if (!url.includes(':')) {
601 return undefined
602 }
603 // WHATWG strips leading C0/space and TAB/LF/CR within a scheme.
604 // Match the prefix first so relative paths and URL bodies need no copying.
605 // eslint-disable-next-line no-control-regex
606 return /^[\x00-\x20]*([a-z][a-z\d+.\t\n\r-]*:)/i
607 .exec(url)?.[1]
608 ?.replace(/[\t\n\r]/g, '')
609 .toLowerCase()
611​
612// Match protocol-relative URLs such as "//evil.example", including backslash
613// and control-character variants. Stop at the second separator so validation
614// does not scan or normalize the URL body.
615// eslint-disable-next-line no-control-regex
616export const protocolRelativePrefixRegex = /^[\x00-\x20]*[\\/][\t\n\r]*[\\/]/
617​
618/**
619 * Check if a URL string uses a protocol that is not in the allowlist or is
620 * protocol-relative (e.g. "//evil.example"), which can navigate to another host.
621 * Returns true for blocked protocols like javascript:, blob:, and data:, as
622 * well as slash/backslash variants of protocol-relative URLs.
623 *
624 * Scheme parsing normalizes:
625 * - Mixed case (JavaScript: β†’ javascript:)
626 * - Whitespace/control characters (java\nscript: β†’ javascript:)
627 * - Leading whitespace
628 *
629 * For relative URLs without a protocol-relative prefix, returns false.
630 *
631 * @param url - The URL string to check
632 * @param allowlist - Set of protocols to allow
633 * @returns true if the URL uses a protocol that is not allowed or can escape
634 * the current origin through a protocol-relative URL
635 */
636export function isDangerousProtocol(
637 url: string,
638 allowlist: Set<string>,
639): boolean {
640 if (!url) return false
641​
642 // Inputs like "/\evil.example" can navigate to another host just like
643 // "//evil.example", even with leading whitespace or ignored control characters.
644 if (protocolRelativePrefixRegex.test(url)) {
645 return true
646 }
647​
648 const scheme = getUrlScheme(url)
649 return scheme ? !allowlist.has(scheme) : false
651​
652// This utility is based on https://github.com/zertosh/htmlescape
653// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
654const HTML_ESCAPE_LOOKUP: { [match: string]: string } = {
655 '&': '\\u0026',
656 '>': '\\u003e',
657 '<': '\\u003c',
658 '\u2028': '\\u2028',
659 '\u2029': '\\u2029',
661​
662const HTML_ESCAPE_REGEX = /[&><\u2028\u2029]/g
663​
664/**
665 * Escape HTML special characters in a string to prevent XSS attacks
666 * when embedding strings in script tags during SSR.
667 *
668 * This is essential for preventing XSS vulnerabilities when user-controlled
669 * content is embedded in inline scripts.
670 */
671export function escapeHtml(str: string): string {
672 return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]!)
674​
675// Decode component data only. Leave protocol-relative URL handling to callers;
676// this decoder also receives fragments, where slashes and backslashes are data.
677export function decodePath(path: string) {
678 if (!path) {
679 return path
680 }
681 let result = path
682 // eslint-disable-next-line no-control-regex
683 if (/[%\\\x00-\x1f\x7f]/.test(path)) {
684 const re = /%25|%5C/gi
685 let cursor = 0
686 let match
687 result = ''
688 while (null !== (match = re.exec(path))) {
689 result += decodeSegment(path.slice(cursor, match.index)) + match[0]
690 cursor = re.lastIndex
691 }
692 result += decodeSegment(cursor ? path.slice(cursor) : path)
693 }
694​
695 return result
697​
698/**
699 * Encodes a path the same way `new URL()` would, but without the overhead of full URL parsing.
700 *
701 * This function encodes:
702 * - Whitespace characters (spaces β†’ %20, tabs β†’ %09, etc.)
703 * - Non-ASCII/Unicode characters (emojis, accented characters, etc.)
704 *
705 * It preserves:
706 * - Already percent-encoded sequences (won't double-encode %2F, %25, etc.)
707 * - ASCII special characters valid in URL paths (@, $, &, +, etc.)
708 * - Forward slashes as path separators
709 *
710 * Used to generate proper href values for SSR without constructing URL objects.
711 *
712 * @example
713 * encodePathLikeUrl('/path/file name.pdf') // '/path/file%20name.pdf'
714 * encodePathLikeUrl('/path/ζ—₯本θͺž') // '/path/%E6%97%A5%E6%9C%AC%E8%AA%9E'
715 * encodePathLikeUrl('/path/already%20encoded') // '/path/already%20encoded' (preserved)
716 */
717export function encodePathLikeUrl(path: string): string {
718 // Encode whitespace and non-ASCII characters that browsers encode in URLs.
719 // The test uses one character class: it matches the same code units as the
720 // replacement pattern below and is cheaper than the alternation.
721 if (!/[\s\u0080-\uFFFF]/.test(path)) {
722 return path
723 }
724 // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check
725 // eslint-disable-next-line no-control-regex
726 return path.replace(/\s|[^\u0000-\u007F]/gu, encodeURIComponent)
728​
729/**
730 * Builds the dev-mode CSS styles URL for route-scoped CSS collection.
731 * Used by HeadContent components in all framework implementations to construct
732 * the URL for the `/@tanstack-start/styles.css` endpoint.
733 *
734 * @param basepath - The router's basepath (may or may not have leading slash)
735 * @param routeIds - Array of matched route IDs to include in the CSS collection
736 * @returns The full URL path for the dev styles CSS endpoint
737 */
738export function buildDevStylesUrl(
739 basepath: string,
740 routeIds: Array<string>,
741): string {
742 // Trim all leading and trailing slashes from basepath
743 const trimmedBasepath = basepath.replace(/^\/+|\/+$/g, '')
744 // Build normalized basepath: empty string for root, or '/path' for non-root
745 const normalizedBasepath = trimmedBasepath === '' ? '' : `/${trimmedBasepath}`
746 return `${normalizedBasepath}/@tanstack-start/styles.css?routes=${encodeURIComponent(routeIds.join(','))}`
748​
749export function arraysEqual<T>(a: Array<T>, b: Array<T>) {
750 if (a === b) return true
751 if (a.length !== b.length) return false
752 for (let i = 0; i < a.length; i++) {
753 if (a[i] !== b[i]) return false
754 }
755 return true