@stackframe/stack-shared 2.8.43 → 2.8.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/apps/apps-config.d.mts +52 -31
- package/dist/apps/apps-config.d.ts +52 -31
- package/dist/apps/apps-config.js +54 -32
- package/dist/apps/apps-config.js.map +1 -1
- package/dist/config/schema.d.mts +248 -248
- package/dist/config/schema.d.ts +248 -248
- package/dist/config/schema.js +1 -1
- package/dist/config/schema.js.map +1 -1
- package/dist/esm/apps/apps-config.js +52 -31
- package/dist/esm/apps/apps-config.js.map +1 -1
- package/dist/esm/config/schema.js +1 -1
- package/dist/esm/config/schema.js.map +1 -1
- package/dist/esm/interface/client-interface.js +18 -16
- package/dist/esm/interface/client-interface.js.map +1 -1
- package/dist/esm/utils/caches.js +6 -2
- package/dist/esm/utils/caches.js.map +1 -1
- package/dist/esm/utils/globals.js +9 -1
- package/dist/esm/utils/globals.js.map +1 -1
- package/dist/esm/utils/react.js +12 -6
- package/dist/esm/utils/react.js.map +1 -1
- package/dist/esm/utils/regex.js +13 -0
- package/dist/esm/utils/regex.js.map +1 -0
- package/dist/esm/utils/urls.js +10 -0
- package/dist/esm/utils/urls.js.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/interface/admin-interface.d.mts +1 -1
- package/dist/interface/admin-interface.d.ts +1 -1
- package/dist/interface/client-interface.d.mts +1 -1
- package/dist/interface/client-interface.d.ts +1 -1
- package/dist/interface/client-interface.js +18 -16
- package/dist/interface/client-interface.js.map +1 -1
- package/dist/interface/server-interface.d.mts +1 -1
- package/dist/interface/server-interface.d.ts +1 -1
- package/dist/utils/caches.d.mts +4 -2
- package/dist/utils/caches.d.ts +4 -2
- package/dist/utils/caches.js +6 -2
- package/dist/utils/caches.js.map +1 -1
- package/dist/utils/globals.d.mts +3 -1
- package/dist/utils/globals.d.ts +3 -1
- package/dist/utils/globals.js +12 -2
- package/dist/utils/globals.js.map +1 -1
- package/dist/utils/react.d.mts +2 -1
- package/dist/utils/react.d.ts +2 -1
- package/dist/utils/react.js +13 -6
- package/dist/utils/react.js.map +1 -1
- package/dist/utils/regex.d.mts +3 -0
- package/dist/utils/regex.d.ts +3 -0
- package/dist/utils/regex.js +38 -0
- package/dist/utils/regex.js.map +1 -0
- package/dist/utils/urls.d.mts +3 -1
- package/dist/utils/urls.d.ts +3 -1
- package/dist/utils/urls.js +12 -0
- package/dist/utils/urls.js.map +1 -1
- package/package.json +1 -1
package/dist/utils/caches.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/caches.tsx"],"sourcesContent":["import { DependenciesMap } from \"./maps\";\nimport { filterUndefined } from \"./objects\";\nimport { RateLimitOptions, ReactPromise, pending, rateLimited, resolved, runAsynchronously, wait } from \"./promises\";\nimport { AsyncStore } from \"./stores\";\n\n/**\n * Can be used to cache the result of a function call, for example for the `use` hook in React.\n */\nexport function cacheFunction<F extends Function>(f: F): F {\n const dependenciesMap = new DependenciesMap<any, any>();\n\n return ((...args: any) => {\n if (dependenciesMap.has(args)) {\n return dependenciesMap.get(args);\n }\n\n const value = f(...args);\n dependenciesMap.set(args, value);\n return value;\n }) as any as F;\n}\nundefined?.test(\"cacheFunction\", ({ expect }) => {\n // Test with a simple function\n let callCount = 0;\n const add = (a: number, b: number) => {\n callCount++;\n return a + b;\n };\n\n const cachedAdd = cacheFunction(add);\n\n // First call should execute the function\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Second call with same args should use cached result\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Call with different args should execute the function again\n expect(cachedAdd(2, 3)).toBe(5);\n expect(callCount).toBe(2);\n\n // Test with a function that returns objects\n let objectCallCount = 0;\n const createObject = (id: number) => {\n objectCallCount++;\n return { id };\n };\n\n const cachedCreateObject = cacheFunction(createObject);\n\n // First call should execute the function\n const obj1 = cachedCreateObject(1);\n expect(obj1).toEqual({ id: 1 });\n expect(objectCallCount).toBe(1);\n\n // Second call with same args should use cached result\n const obj2 = cachedCreateObject(1);\n expect(obj2).toBe(obj1); // Same reference\n expect(objectCallCount).toBe(1);\n});\n\n\ntype CacheStrategy = \"write-only\" | \"read-write\" | \"never\";\n\nexport class AsyncCache<D extends any[], T> {\n private readonly _map = new DependenciesMap<D, AsyncValueCache<T>>();\n\n constructor(\n private readonly _fetcher: (dependencies: D) => Promise<T>,\n private readonly _options: {\n onSubscribe?: (key: D, refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n // nothing here yet\n }\n\n private _createKeyed<FunctionName extends keyof AsyncValueCache<T>>(\n functionName: FunctionName,\n ): (key: D, ...args: Parameters<AsyncValueCache<T>[FunctionName]>) => ReturnType<AsyncValueCache<T>[FunctionName]> {\n return (key: D, ...args) => {\n const valueCache = this.getValueCache(key);\n return (valueCache[functionName] as any).apply(valueCache, args);\n };\n }\n\n getValueCache(dependencies: D): AsyncValueCache<T> {\n let cache = this._map.get(dependencies);\n if (!cache) {\n cache = new AsyncValueCache(\n async () => await this._fetcher(dependencies),\n {\n ...this._options,\n onSubscribe: this._options.onSubscribe ? (cb) => this._options.onSubscribe!(dependencies, cb) : undefined,\n },\n );\n this._map.set(dependencies, cache);\n }\n return cache;\n }\n\n async refreshWhere(predicate: (dependencies: D) => boolean) {\n const promises: Promise<T>[] = [];\n for (const [dependencies, cache] of this._map) {\n if (predicate(dependencies)) {\n promises.push(cache.refresh());\n }\n }\n await Promise.all(promises);\n }\n\n readonly isCacheAvailable = this._createKeyed(\"isCacheAvailable\");\n readonly getIfCached = this._createKeyed(\"getIfCached\");\n readonly getOrWait = this._createKeyed(\"getOrWait\");\n readonly forceSetCachedValue = this._createKeyed(\"forceSetCachedValue\");\n readonly forceSetCachedValueAsync = this._createKeyed(\"forceSetCachedValueAsync\");\n readonly refresh = this._createKeyed(\"refresh\");\n readonly invalidate = this._createKeyed(\"invalidate\");\n readonly onStateChange = this._createKeyed(\"onStateChange\");\n}\n\nclass AsyncValueCache<T> {\n private _store: AsyncStore<T>;\n private _pendingPromise: ReactPromise<T> | undefined;\n private _fetcher: () => Promise<T>;\n private readonly _rateLimitOptions: Omit<RateLimitOptions, \"batchCalls\">;\n private _subscriptionsCount = 0;\n private _unsubscribers: (() => void)[] = [];\n private _mostRecentRefreshPromiseIndex = 0;\n\n constructor(\n fetcher: () => Promise<T>,\n private readonly _options: {\n onSubscribe?: (refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n this._store = new AsyncStore();\n this._rateLimitOptions = {\n concurrency: 1,\n throttleMs: 300,\n ...filterUndefined(_options.rateLimiter ?? {}),\n };\n\n\n this._fetcher = rateLimited(fetcher, {\n ...this._rateLimitOptions,\n batchCalls: true,\n });\n }\n\n isCacheAvailable(): boolean {\n return this._store.isAvailable();\n }\n\n getIfCached() {\n return this._store.get();\n }\n\n getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T> {\n const cached = this.getIfCached();\n if (cacheStrategy === \"read-write\" && cached.status === \"ok\") {\n return resolved(cached.data);\n }\n\n return this._refetch(cacheStrategy);\n }\n\n private _set(value: T): void {\n this._store.set(value);\n }\n\n private _setAsync(value: Promise<T>): ReactPromise<boolean> {\n const promise = pending(value);\n this._pendingPromise = promise;\n return pending(this._store.setAsync(promise));\n }\n\n private _refetch(cacheStrategy: CacheStrategy): ReactPromise<T> {\n if (cacheStrategy === \"read-write\" && this._pendingPromise) {\n return this._pendingPromise;\n }\n const promise = pending(this._fetcher());\n if (cacheStrategy === \"never\") {\n return promise;\n }\n return pending(this._setAsync(promise).then(() => promise));\n }\n\n forceSetCachedValue(value: T): void {\n this._set(value);\n }\n\n forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean> {\n return this._setAsync(value);\n }\n\n /**\n * Refetches the value from the fetcher, and updates the cache with it.\n */\n async refresh(): Promise<T> {\n return await this.getOrWait(\"write-only\");\n }\n\n /**\n * Invalidates the cache, marking it to refresh on the next read. If anyone was listening to it, it will refresh\n * immediately.\n */\n invalidate(): void {\n this._store.setUnavailable();\n this._pendingPromise = undefined;\n if (this._subscriptionsCount > 0) {\n runAsynchronously(this.refresh());\n }\n }\n\n onStateChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const storeObj = this._store.onChange(callback);\n\n runAsynchronously(this.getOrWait(\"read-write\"));\n\n if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) {\n const unsubscribe = this._options.onSubscribe(() => {\n runAsynchronously(this.refresh());\n });\n this._unsubscribers.push(unsubscribe);\n }\n\n let hasUnsubscribed = false;\n return {\n unsubscribe: () => {\n if (hasUnsubscribed) return;\n hasUnsubscribed = true;\n storeObj.unsubscribe();\n if (--this._subscriptionsCount === 0) {\n const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex;\n runAsynchronously(async () => {\n // wait a few seconds; if anything changes during that time, we don't want to refresh\n // else we do unnecessary requests if we unsubscribe and then subscribe again immediately\n await wait(5000);\n if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {\n this.invalidate();\n }\n });\n\n for (const unsubscribe of this._unsubscribers) {\n unsubscribe();\n }\n }\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAgC;AAChC,qBAAgC;AAChC,sBAAwG;AACxG,oBAA2B;AAKpB,SAAS,cAAkC,GAAS;AACzD,QAAM,kBAAkB,IAAI,4BAA0B;AAEtD,SAAQ,IAAI,SAAc;AACxB,QAAI,gBAAgB,IAAI,IAAI,GAAG;AAC7B,aAAO,gBAAgB,IAAI,IAAI;AAAA,IACjC;AAEA,UAAM,QAAQ,EAAE,GAAG,IAAI;AACvB,oBAAgB,IAAI,MAAM,KAAK;AAC/B,WAAO;AA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,SAAK,KAAK,KAAK;AAAA,EACjB;AAAA,EAEA,yBAAyB,OAA0C;AACjE,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAsB;AAC1B,WAAO,MAAM,KAAK,UAAU,YAAY;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAmB;AACjB,SAAK,OAAO,eAAe;AAC3B,SAAK,kBAAkB;AACvB,QAAI,KAAK,sBAAsB,GAAG;AAChC,6CAAkB,KAAK,QAAQ,CAAC;AAAA,IAClC;AAAA,EACF;AAAA,EAEA,cAAc,UAAoF;AAChG,UAAM,WAAW,KAAK,OAAO,SAAS,QAAQ;AAE9C,2CAAkB,KAAK,UAAU,YAAY,CAAC;AAE9C,QAAI,KAAK,0BAA0B,KAAK,KAAK,SAAS,aAAa;AACjE,YAAM,cAAc,KAAK,SAAS,YAAY,MAAM;AAClD,+CAAkB,KAAK,QAAQ,CAAC;AAAA,MAClC,CAAC;AACD,WAAK,eAAe,KAAK,WAAW;AAAA,IACtC;AAEA,QAAI,kBAAkB;AACtB,WAAO;AAAA,MACL,aAAa,MAAM;AACjB,YAAI,gBAAiB;AACrB,0BAAkB;AAClB,iBAAS,YAAY;AACrB,YAAI,EAAE,KAAK,wBAAwB,GAAG;AACpC,gBAAM,6BAA6B,EAAE,KAAK;AAC1C,iDAAkB,YAAY;AAG5B,sBAAM,sBAAK,GAAI;AACf,gBAAI,KAAK,wBAAwB,KAAK,+BAA+B,KAAK,gCAAgC;AACxG,mBAAK,WAAW;AAAA,YAClB;AAAA,UACF,CAAC;AAED,qBAAW,eAAe,KAAK,gBAAgB;AAC7C,wBAAY;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/caches.tsx"],"sourcesContent":["import { DependenciesMap } from \"./maps\";\nimport { filterUndefined } from \"./objects\";\nimport { RateLimitOptions, ReactPromise, pending, rateLimited, resolved, runAsynchronously, wait } from \"./promises\";\nimport { AsyncStore } from \"./stores\";\n\n/**\n * Can be used to cache the result of a function call, for example for the `use` hook in React.\n */\nexport function cacheFunction<F extends Function>(f: F): F {\n const dependenciesMap = new DependenciesMap<any, any>();\n\n return ((...args: any) => {\n if (dependenciesMap.has(args)) {\n return dependenciesMap.get(args);\n }\n\n const value = f(...args);\n dependenciesMap.set(args, value);\n return value;\n }) as any as F;\n}\nundefined?.test(\"cacheFunction\", ({ expect }) => {\n // Test with a simple function\n let callCount = 0;\n const add = (a: number, b: number) => {\n callCount++;\n return a + b;\n };\n\n const cachedAdd = cacheFunction(add);\n\n // First call should execute the function\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Second call with same args should use cached result\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Call with different args should execute the function again\n expect(cachedAdd(2, 3)).toBe(5);\n expect(callCount).toBe(2);\n\n // Test with a function that returns objects\n let objectCallCount = 0;\n const createObject = (id: number) => {\n objectCallCount++;\n return { id };\n };\n\n const cachedCreateObject = cacheFunction(createObject);\n\n // First call should execute the function\n const obj1 = cachedCreateObject(1);\n expect(obj1).toEqual({ id: 1 });\n expect(objectCallCount).toBe(1);\n\n // Second call with same args should use cached result\n const obj2 = cachedCreateObject(1);\n expect(obj2).toBe(obj1); // Same reference\n expect(objectCallCount).toBe(1);\n});\n\n\ntype CacheStrategy = \"write-only\" | \"read-write\" | \"never\";\n\nexport class AsyncCache<D extends any[], T> {\n private readonly _map = new DependenciesMap<D, AsyncValueCache<T>>();\n\n constructor(\n private readonly _fetcher: (dependencies: D) => Promise<T>,\n private readonly _options: {\n onSubscribe?: (key: D, refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n // nothing here yet\n }\n\n private _createKeyed<FunctionName extends keyof AsyncValueCache<T>>(\n functionName: FunctionName,\n ): (key: D, ...args: Parameters<AsyncValueCache<T>[FunctionName]>) => ReturnType<AsyncValueCache<T>[FunctionName]> {\n return (key: D, ...args) => {\n const valueCache = this.getValueCache(key);\n return (valueCache[functionName] as any).apply(valueCache, args);\n };\n }\n\n getValueCache(dependencies: D): AsyncValueCache<T> {\n let cache = this._map.get(dependencies);\n if (!cache) {\n cache = new AsyncValueCache(\n async () => await this._fetcher(dependencies),\n {\n ...this._options,\n onSubscribe: this._options.onSubscribe ? (cb) => this._options.onSubscribe!(dependencies, cb) : undefined,\n },\n );\n this._map.set(dependencies, cache);\n }\n return cache;\n }\n\n async refreshWhere(predicate: (dependencies: D) => boolean) {\n const promises: Promise<T>[] = [];\n for (const [dependencies, cache] of this._map) {\n if (predicate(dependencies)) {\n promises.push(cache.refresh());\n }\n }\n await Promise.all(promises);\n }\n\n readonly isCacheAvailable = this._createKeyed(\"isCacheAvailable\");\n readonly getIfCached = this._createKeyed(\"getIfCached\");\n readonly getOrWait = this._createKeyed(\"getOrWait\");\n readonly forceSetCachedValue = this._createKeyed(\"forceSetCachedValue\");\n readonly forceSetCachedValueAsync = this._createKeyed(\"forceSetCachedValueAsync\");\n readonly refresh = this._createKeyed(\"refresh\");\n readonly invalidate = this._createKeyed(\"invalidate\");\n readonly onStateChange = this._createKeyed(\"onStateChange\");\n readonly isDirty = this._createKeyed(\"isDirty\");\n}\n\nclass AsyncValueCache<T> {\n private _store: AsyncStore<T>;\n private _pendingPromise: ReactPromise<T> | undefined;\n private _fetcher: () => Promise<T>;\n private readonly _rateLimitOptions: Omit<RateLimitOptions, \"batchCalls\">;\n private _subscriptionsCount = 0;\n private _unsubscribers: (() => void)[] = [];\n private _mostRecentRefreshPromiseIndex = 0;\n\n constructor(\n fetcher: () => Promise<T>,\n private readonly _options: {\n onSubscribe?: (refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n this._store = new AsyncStore();\n this._rateLimitOptions = {\n concurrency: 1,\n throttleMs: 300,\n ...filterUndefined(_options.rateLimiter ?? {}),\n };\n\n\n this._fetcher = rateLimited(fetcher, {\n ...this._rateLimitOptions,\n batchCalls: true,\n });\n }\n\n isCacheAvailable(): boolean {\n return this._store.isAvailable();\n }\n\n getIfCached() {\n return this._store.get();\n }\n\n getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T> {\n const cached = this.getIfCached();\n if (cacheStrategy === \"read-write\" && cached.status === \"ok\") {\n return resolved(cached.data);\n }\n\n return this._refetch(cacheStrategy);\n }\n\n private _set(value: T): void {\n this._store.set(value);\n }\n\n private _setAsync(value: Promise<T>): ReactPromise<boolean> {\n const promise = pending(value);\n this._pendingPromise = promise;\n return pending(this._store.setAsync(promise));\n }\n\n private _refetch(cacheStrategy: CacheStrategy): ReactPromise<T> {\n if (cacheStrategy === \"read-write\" && this._pendingPromise) {\n return this._pendingPromise;\n }\n const promise = pending(this._fetcher());\n if (cacheStrategy === \"never\") {\n return promise;\n }\n return pending(this._setAsync(promise).then(() => promise));\n }\n\n forceSetCachedValue(value: T): void {\n this._set(value);\n }\n\n forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean> {\n return this._setAsync(value);\n }\n\n /**\n * Refetches the value from the fetcher, and updates the cache with it.\n */\n async refresh(): Promise<T> {\n return await this.getOrWait(\"write-only\");\n }\n\n /**\n * Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). If anyone was listening to it,\n * it will refresh immediately.\n */\n invalidate(): void {\n this._store.setUnavailable();\n this._pendingPromise = undefined;\n if (this._subscriptionsCount > 0) {\n runAsynchronously(this.refresh());\n }\n }\n\n isDirty(): boolean {\n return this._pendingPromise === undefined;\n }\n\n onStateChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const storeObj = this._store.onChange(callback);\n\n runAsynchronously(this.getOrWait(\"read-write\"));\n\n if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) {\n const unsubscribe = this._options.onSubscribe(() => {\n runAsynchronously(this.refresh());\n });\n this._unsubscribers.push(unsubscribe);\n }\n\n let hasUnsubscribed = false;\n return {\n unsubscribe: () => {\n if (hasUnsubscribed) return;\n hasUnsubscribed = true;\n storeObj.unsubscribe();\n if (--this._subscriptionsCount === 0) {\n const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex;\n runAsynchronously(async () => {\n // wait a few seconds; if anything changes during that time, we don't want to refresh\n // else we do unnecessary requests if we unsubscribe and then subscribe again immediately\n await wait(5000);\n if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {\n this.invalidate();\n }\n });\n\n for (const unsubscribe of this._unsubscribers) {\n unsubscribe();\n }\n }\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAgC;AAChC,qBAAgC;AAChC,sBAAwG;AACxG,oBAA2B;AAKpB,SAAS,cAAkC,GAAS;AACzD,QAAM,kBAAkB,IAAI,4BAA0B;AAEtD,SAAQ,IAAI,SAAc;AACxB,QAAI,gBAAgB,IAAI,IAAI,GAAG;AAC7B,aAAO,gBAAgB,IAAI,IAAI;AAAA,IACjC;AAEA,UAAM,QAAQ,EAAE,GAAG,IAAI;AACvB,oBAAgB,IAAI,MAAM,KAAK;AAC/B,WAAO;AAAA,EACT;AACF;AA8CO,IAAM,aAAN,MAAqC;AAAA,EAG1C,YACmB,UACA,WAGb,CAAC,GACL;AALiB;AACA;AAJnB,SAAiB,OAAO,IAAI,4BAAuC;AA8CnE,SAAS,mBAAmB,KAAK,aAAa,kBAAkB;AAChE,SAAS,cAAc,KAAK,aAAa,aAAa;AACtD,SAAS,YAAY,KAAK,aAAa,WAAW;AAClD,SAAS,sBAAsB,KAAK,aAAa,qBAAqB;AACtE,SAAS,2BAA2B,KAAK,aAAa,0BAA0B;AAChF,SAAS,UAAU,KAAK,aAAa,SAAS;AAC9C,SAAS,aAAa,KAAK,aAAa,YAAY;AACpD,SAAS,gBAAgB,KAA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A,UAAmB;AACjB,WAAO,KAAK,oBAAoB;AAAA,EAClC;AAAA,EAEA,cAAc,UAAoF;AAChG,UAAM,WAAW,KAAK,OAAO,SAAS,QAAQ;AAE9C,2CAAkB,KAAK,UAAU,YAAY,CAAC;AAE9C,QAAI,KAAK,0BAA0B,KAAK,KAAK,SAAS,aAAa;AACjE,YAAM,cAAc,KAAK,SAAS,YAAY,MAAM;AAClD,+CAAkB,KAAK,QAAQ,CAAC;AAAA,MAClC,CAAC;AACD,WAAK,eAAe,KAAK,WAAW;AAAA,IACtC;AAEA,QAAI,kBAAkB;AACtB,WAAO;AAAA,MACL,aAAa,MAAM;AACjB,YAAI,gBAAiB;AACrB,0BAAkB;AAClB,iBAAS,YAAY;AACrB,YAAI,EAAE,KAAK,wBAAwB,GAAG;AACpC,gBAAM,6BAA6B,EAAE,KAAK;AAC1C,iDAAkB,YAAY;AAG5B,sBAAM,sBAAK,GAAI;AACf,gBAAI,KAAK,wBAAwB,KAAK,+BAA+B,KAAK,gCAAgC;AACxG,mBAAK,WAAW;AAAA,YAClB;AAAA,UACF,CAAC;AAED,qBAAW,eAAe,KAAK,gBAAgB;AAC7C,wBAAY;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/utils/globals.d.mts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
declare const globalVar: any;
|
|
2
2
|
|
|
3
3
|
declare function createGlobal<T>(key: string, init: () => T): T;
|
|
4
|
+
declare function getGlobal(key: string): any;
|
|
5
|
+
declare function setGlobal(key: string, value: any): void;
|
|
4
6
|
|
|
5
|
-
export { createGlobal, globalVar };
|
|
7
|
+
export { createGlobal, getGlobal, globalVar, setGlobal };
|
package/dist/utils/globals.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
declare const globalVar: any;
|
|
2
2
|
|
|
3
3
|
declare function createGlobal<T>(key: string, init: () => T): T;
|
|
4
|
+
declare function getGlobal(key: string): any;
|
|
5
|
+
declare function setGlobal(key: string, value: any): void;
|
|
4
6
|
|
|
5
|
-
export { createGlobal, globalVar };
|
|
7
|
+
export { createGlobal, getGlobal, globalVar, setGlobal };
|
package/dist/utils/globals.js
CHANGED
|
@@ -21,7 +21,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var globals_exports = {};
|
|
22
22
|
__export(globals_exports, {
|
|
23
23
|
createGlobal: () => createGlobal,
|
|
24
|
-
|
|
24
|
+
getGlobal: () => getGlobal,
|
|
25
|
+
globalVar: () => globalVar,
|
|
26
|
+
setGlobal: () => setGlobal
|
|
25
27
|
});
|
|
26
28
|
module.exports = __toCommonJS(globals_exports);
|
|
27
29
|
var globalVar = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {};
|
|
@@ -36,9 +38,17 @@ function createGlobal(key, init) {
|
|
|
36
38
|
}
|
|
37
39
|
return globalVar[stackGlobalsSymbol][key];
|
|
38
40
|
}
|
|
41
|
+
function getGlobal(key) {
|
|
42
|
+
return globalVar[stackGlobalsSymbol][key];
|
|
43
|
+
}
|
|
44
|
+
function setGlobal(key, value) {
|
|
45
|
+
globalVar[stackGlobalsSymbol][key] = value;
|
|
46
|
+
}
|
|
39
47
|
// Annotate the CommonJS export names for ESM import in node:
|
|
40
48
|
0 && (module.exports = {
|
|
41
49
|
createGlobal,
|
|
42
|
-
|
|
50
|
+
getGlobal,
|
|
51
|
+
globalVar,
|
|
52
|
+
setGlobal
|
|
43
53
|
});
|
|
44
54
|
//# sourceMappingURL=globals.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/globals.tsx"],"sourcesContent":["const globalVar: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof global !== 'undefined' ? global :\n typeof window !== 'undefined' ? window :\n typeof self !== 'undefined' ? self :\n {};\nexport {\n globalVar\n};\n\nif (typeof globalThis === 'undefined') {\n (globalVar as any).globalThis = globalVar;\n}\n\nconst stackGlobalsSymbol = Symbol.for('__stack-globals');\nglobalVar[stackGlobalsSymbol] ??= {};\n\nexport function createGlobal<T>(key: string, init: () => T) {\n if (!globalVar[stackGlobalsSymbol][key]) {\n globalVar[stackGlobalsSymbol][key] = init();\n }\n return globalVar[stackGlobalsSymbol][key] as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,YACJ,OAAO,eAAe,cAAc,aAClC,OAAO,WAAW,cAAc,SAC9B,OAAO,WAAW,cAAc,SAC9B,OAAO,SAAS,cAAc,OAC5B,CAAC;AAKX,IAAI,OAAO,eAAe,aAAa;AACrC,EAAC,UAAkB,aAAa;AAClC;AAEA,IAAM,qBAAqB,OAAO,IAAI,iBAAiB;AACvD,UAAU,kBAAkB,MAAM,CAAC;AAE5B,SAAS,aAAgB,KAAa,MAAe;AAC1D,MAAI,CAAC,UAAU,kBAAkB,EAAE,GAAG,GAAG;AACvC,cAAU,kBAAkB,EAAE,GAAG,IAAI,KAAK;AAAA,EAC5C;AACA,SAAO,UAAU,kBAAkB,EAAE,GAAG;AAC1C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/globals.tsx"],"sourcesContent":["const globalVar: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof global !== 'undefined' ? global :\n typeof window !== 'undefined' ? window :\n typeof self !== 'undefined' ? self :\n {};\nexport {\n globalVar\n};\n\nif (typeof globalThis === 'undefined') {\n (globalVar as any).globalThis = globalVar;\n}\n\nconst stackGlobalsSymbol = Symbol.for('__stack-globals');\nglobalVar[stackGlobalsSymbol] ??= {};\n\nexport function createGlobal<T>(key: string, init: () => T) {\n if (!globalVar[stackGlobalsSymbol][key]) {\n globalVar[stackGlobalsSymbol][key] = init();\n }\n return globalVar[stackGlobalsSymbol][key] as T;\n}\n\nexport function getGlobal(key: string): any {\n return globalVar[stackGlobalsSymbol][key];\n}\n\nexport function setGlobal(key: string, value: any) {\n globalVar[stackGlobalsSymbol][key] = value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,YACJ,OAAO,eAAe,cAAc,aAClC,OAAO,WAAW,cAAc,SAC9B,OAAO,WAAW,cAAc,SAC9B,OAAO,SAAS,cAAc,OAC5B,CAAC;AAKX,IAAI,OAAO,eAAe,aAAa;AACrC,EAAC,UAAkB,aAAa;AAClC;AAEA,IAAM,qBAAqB,OAAO,IAAI,iBAAiB;AACvD,UAAU,kBAAkB,MAAM,CAAC;AAE5B,SAAS,aAAgB,KAAa,MAAe;AAC1D,MAAI,CAAC,UAAU,kBAAkB,EAAE,GAAG,GAAG;AACvC,cAAU,kBAAkB,EAAE,GAAG,IAAI,KAAK;AAAA,EAC5C;AACA,SAAO,UAAU,kBAAkB,EAAE,GAAG;AAC1C;AAEO,SAAS,UAAU,KAAkB;AAC1C,SAAO,UAAU,kBAAkB,EAAE,GAAG;AAC1C;AAEO,SAAS,UAAU,KAAa,OAAY;AACjD,YAAU,kBAAkB,EAAE,GAAG,IAAI;AACvC;","names":[]}
|
package/dist/utils/react.d.mts
CHANGED
|
@@ -40,6 +40,7 @@ type RefState<T> = ReadonlyRef<T> & {
|
|
|
40
40
|
*/
|
|
41
41
|
declare function useRefState<T>(initialValue: T): RefState<T>;
|
|
42
42
|
declare function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R>;
|
|
43
|
+
declare function shouldRethrowRenderingError(error: unknown): boolean;
|
|
43
44
|
declare class NoSuspenseBoundaryError extends Error {
|
|
44
45
|
digest: string;
|
|
45
46
|
reason: string;
|
|
@@ -52,4 +53,4 @@ declare class NoSuspenseBoundaryError extends Error {
|
|
|
52
53
|
*/
|
|
53
54
|
declare function suspendIfSsr(caller?: string): void;
|
|
54
55
|
|
|
55
|
-
export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, suspend, suspendIfSsr, useRefState };
|
|
56
|
+
export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, shouldRethrowRenderingError, suspend, suspendIfSsr, useRefState };
|
package/dist/utils/react.d.ts
CHANGED
|
@@ -40,6 +40,7 @@ type RefState<T> = ReadonlyRef<T> & {
|
|
|
40
40
|
*/
|
|
41
41
|
declare function useRefState<T>(initialValue: T): RefState<T>;
|
|
42
42
|
declare function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R>;
|
|
43
|
+
declare function shouldRethrowRenderingError(error: unknown): boolean;
|
|
43
44
|
declare class NoSuspenseBoundaryError extends Error {
|
|
44
45
|
digest: string;
|
|
45
46
|
reason: string;
|
|
@@ -52,4 +53,4 @@ declare class NoSuspenseBoundaryError extends Error {
|
|
|
52
53
|
*/
|
|
53
54
|
declare function suspendIfSsr(caller?: string): void;
|
|
54
55
|
|
|
55
|
-
export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, suspend, suspendIfSsr, useRefState };
|
|
56
|
+
export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, shouldRethrowRenderingError, suspend, suspendIfSsr, useRefState };
|
package/dist/utils/react.js
CHANGED
|
@@ -36,6 +36,7 @@ __export(react_exports, {
|
|
|
36
36
|
getNodeText: () => getNodeText,
|
|
37
37
|
mapRef: () => mapRef,
|
|
38
38
|
mapRefState: () => mapRefState,
|
|
39
|
+
shouldRethrowRenderingError: () => shouldRethrowRenderingError,
|
|
39
40
|
suspend: () => suspend,
|
|
40
41
|
suspendIfSsr: () => suspendIfSsr,
|
|
41
42
|
useRefState: () => useRefState
|
|
@@ -95,9 +96,7 @@ function useRefState(initialValue) {
|
|
|
95
96
|
const ref = import_react.default.useRef(initialValue);
|
|
96
97
|
const setValue = import_react.default.useCallback((updater) => {
|
|
97
98
|
const value = typeof updater === "function" ? updater(ref.current) : updater;
|
|
98
|
-
console.log("setValue", ref.current);
|
|
99
99
|
ref.current = value;
|
|
100
|
-
console.log("setValue", ref.current);
|
|
101
100
|
setState(value);
|
|
102
101
|
}, []);
|
|
103
102
|
const res = import_react.default.useMemo(() => ({
|
|
@@ -124,16 +123,23 @@ function mapRefState(refState, mapper, reverseMapper) {
|
|
|
124
123
|
}
|
|
125
124
|
};
|
|
126
125
|
}
|
|
126
|
+
function shouldRethrowRenderingError(error) {
|
|
127
|
+
return !!error && typeof error === "object" && "digest" in error && error.digest === "BAILOUT_TO_CLIENT_SIDE_RENDERING";
|
|
128
|
+
}
|
|
127
129
|
var NoSuspenseBoundaryError = class extends Error {
|
|
128
130
|
constructor(options) {
|
|
129
131
|
super(import_strings.deindent`
|
|
132
|
+
Suspense boundary not found! Read the error message below carefully on how to fix it.
|
|
133
|
+
|
|
130
134
|
${options.caller ?? "This code path"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.
|
|
131
135
|
|
|
132
|
-
The fix depends on which of the
|
|
136
|
+
The fix depends on which of the 4 scenarios caused it:
|
|
133
137
|
|
|
134
|
-
1. You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.
|
|
138
|
+
1. [Next.js] You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.
|
|
139
|
+
|
|
140
|
+
2. [React] You are missing a <Suspense> boundary in your component. Fix it by wrapping your component (or the entire app) in a <Suspense> component.
|
|
135
141
|
|
|
136
|
-
|
|
142
|
+
3. [Next.js] The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:
|
|
137
143
|
|
|
138
144
|
- app
|
|
139
145
|
- - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? "this code path"}
|
|
@@ -145,7 +151,7 @@ var NoSuspenseBoundaryError = class extends Error {
|
|
|
145
151
|
|
|
146
152
|
For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups
|
|
147
153
|
|
|
148
|
-
|
|
154
|
+
4. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.
|
|
149
155
|
|
|
150
156
|
See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout
|
|
151
157
|
|
|
@@ -169,6 +175,7 @@ function suspendIfSsr(caller) {
|
|
|
169
175
|
getNodeText,
|
|
170
176
|
mapRef,
|
|
171
177
|
mapRefState,
|
|
178
|
+
shouldRethrowRenderingError,
|
|
172
179
|
suspend,
|
|
173
180
|
suspendIfSsr,
|
|
174
181
|
useRefState
|
package/dist/utils/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React, { SetStateAction } from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve } from \"./promises\";\nimport { deindent } from \"./strings\";\n\nexport function componentWrapper<\n C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements,\n ExtraProps extends {} = {}\n>(displayName: string, render: React.ForwardRefRenderFunction<RefFromComponent<C>, React.ComponentPropsWithRef<C> & ExtraProps>) {\n const Component = forwardRefIfNeeded(render);\n Component.displayName = displayName;\n return Component;\n}\ntype RefFromComponent<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements> = NonNullable<RefFromComponentDistCond<React.ComponentPropsWithRef<C>[\"ref\"]>>;\ntype RefFromComponentDistCond<A> = A extends React.RefObject<infer T> ? T : never; // distributive conditional type; see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n\nexport function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & { ref?: React.Ref<T> }> {\n // TODO: when we drop support for react 18, remove this\n\n const version = React.version;\n const major = parseInt(version.split(\".\")[0]);\n if (major < 19) {\n return React.forwardRef<T, P>(render as any) as any;\n } else {\n return ((props: P) => render(props, (props as any).ref)) as any;\n }\n}\n\nexport function getNodeText(node: React.ReactNode): string {\n if ([\"number\", \"string\"].includes(typeof node)) {\n return `${node}`;\n }\n if (!node) {\n return \"\";\n }\n if (Array.isArray(node)) {\n return node.map(getNodeText).join(\"\");\n }\n if (typeof node === \"object\" && \"props\" in node) {\n return getNodeText(node.props.children);\n }\n throw new Error(`Unknown node type: ${typeof node}`);\n}\nundefined?.test(\"getNodeText\", ({ expect }) => {\n // Test with string\n expect(getNodeText(\"hello\")).toBe(\"hello\");\n\n // Test with number\n expect(getNodeText(42)).toBe(\"42\");\n\n // Test with null/undefined\n expect(getNodeText(null)).toBe(\"\");\n expect(getNodeText(undefined)).toBe(\"\");\n\n // Test with array\n expect(getNodeText([\"hello\", \" \", \"world\"])).toBe(\"hello world\");\n expect(getNodeText([1, 2, 3])).toBe(\"123\");\n\n // Test with mixed array\n expect(getNodeText([\"hello\", 42, null])).toBe(\"hello42\");\n\n // Test with React element (mocked)\n const mockElement = {\n props: {\n children: \"child text\"\n }\n } as React.ReactElement;\n expect(getNodeText(mockElement)).toBe(\"child text\");\n\n // Test with nested React elements\n const nestedElement = {\n props: {\n children: {\n props: {\n children: \"nested text\"\n }\n } as React.ReactElement\n }\n } as React.ReactElement;\n expect(getNodeText(nestedElement)).toBe(\"nested text\");\n\n // Test with array of React elements\n const arrayOfElements = [\n { props: { children: \"first\" } } as React.ReactElement,\n { props: { children: \"second\" } } as React.ReactElement\n ];\n expect(getNodeText(arrayOfElements)).toBe(\"firstsecond\");\n});\n\n/**\n * Suspends the currently rendered component indefinitely. Will not unsuspend unless the component rerenders.\n *\n * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`\n */\nexport function suspend(): never {\n React.use(neverResolve());\n throw new Error(\"Somehow a Promise that never resolves was resolved?\");\n}\n\nexport function mapRef<T, R>(ref: ReadonlyRef<T>, mapper: (value: T) => R): ReadonlyRef<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = ref.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n };\n}\n\nexport type ReadonlyRef<T> = {\n readonly current: T,\n};\n\nexport type RefState<T> = ReadonlyRef<T> & {\n set: (updater: SetStateAction<T>) => void,\n};\n\n/**\n * Like useState, but its value is immediately available on refState.current after being set.\n *\n * Like useRef, but setting the value will cause a rerender.\n *\n * Note that useRefState returns a new object every time a rerender happens due to a value change, which is intentional\n * as it allows you to specify it in a dependency array like this:\n *\n * ```tsx\n * useEffect(() => {\n * // do something with refState.current\n * }, [refState]); // instead of refState.current\n * ```\n *\n * If you don't want this, you can wrap the result in a useMemo call.\n */\nexport function useRefState<T>(initialValue: T): RefState<T> {\n const [, setState] = React.useState(initialValue);\n const ref = React.useRef(initialValue);\n const setValue = React.useCallback((updater: SetStateAction<T>) => {\n const value: T = typeof updater === \"function\" ? (updater as any)(ref.current) : updater;\n console.log(\"setValue\", ref.current);\n ref.current = value;\n console.log(\"setValue\", ref.current);\n setState(value);\n }, []);\n const res = React.useMemo(() => ({\n get current() {\n return ref.current;\n },\n set: setValue,\n }), [setValue]);\n return res;\n}\n\nexport function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = refState.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n set(updater: SetStateAction<R>) {\n const value: R = typeof updater === \"function\" ? (updater as any)(this.current) : updater;\n refState.set(reverseMapper(refState.current, value));\n },\n };\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n\n constructor(options: { caller?: string }) {\n super(deindent`\n ${options.caller ?? \"This code path\"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.\n \n The fix depends on which of the 3 scenarios caused it:\n \n 1. You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.\n\n 2. The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:\n\n - app\n - - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? \"this code path\"}\n - - loading.tsx // required for suspense\n - - (main)\n - - - layout.tsx // contains the main layout of your app, like a sidebar or a header, and can use ${options.caller ?? \"this code path\"}\n - - - route.tsx // your actual main page\n - - - the rest of your app\n\n For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups\n \n 3. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.\n\n See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n\n More information on SSR and Suspense boundaries: https://react.dev/reference/react/Suspense#providing-a-fallback-for-server-errors-and-client-only-content\n `);\n\n this.name = \"NoSuspenseBoundaryError\";\n this.reason = options.caller ?? \"suspendIfSsr()\";\n\n // set the digest so nextjs doesn't log the error\n // https://github.com/vercel/next.js/blob/d01d6d9c35a8c2725b3d74c1402ab76d4779a6cf/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts#L14\n this.digest = \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n }\n}\nundefined?.test(\"NoSuspenseBoundaryError\", ({ expect }) => {\n // Test with default options\n const defaultError = new NoSuspenseBoundaryError({});\n expect(defaultError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(defaultError.reason).toBe(\"suspendIfSsr()\");\n expect(defaultError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(defaultError.message).toContain(\"This code path attempted to display a loading indicator\");\n\n // Test with custom caller\n const customError = new NoSuspenseBoundaryError({ caller: \"CustomComponent\" });\n expect(customError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(customError.reason).toBe(\"CustomComponent\");\n expect(customError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(customError.message).toContain(\"CustomComponent attempted to display a loading indicator\");\n\n // Verify error message contains all the necessary information\n expect(customError.message).toContain(\"loading.tsx\");\n expect(customError.message).toContain(\"route groups\");\n expect(customError.message).toContain(\"https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\");\n});\n\n\n/**\n * Use this in a component or a hook to disable SSR. Should be wrapped in a Suspense boundary, or it will throw an error.\n */\nexport function suspendIfSsr(caller?: string) {\n if (!isBrowserLike()) {\n throw new NoSuspenseBoundaryError({ caller });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAsC;AACtC,iBAA8B;AAC9B,sBAA6B;AAC7B,qBAAyB;AAElB,SAAS,iBAGd,aAAqB,QAA0G;AAC/H,QAAM,YAAY,mBAAmB,MAAM;AAC3C,YAAU,cAAc;AACxB,SAAO;AACT;AAIO,SAAS,mBAA8B,QAAoF;AAGhI,QAAM,UAAU,aAAAA,QAAM;AACtB,QAAM,QAAQ,SAAS,QAAQ,MAAM,GAAG,EAAE,CAAC,CAAC;AAC5C,MAAI,QAAQ,IAAI;AACd,WAAO,aAAAA,QAAM,WAAiB,MAAa;AAAA,EAC7C,OAAO;AACL,WAAQ,CAAC,UAAa,OAAO,OAAQ,MAAc,GAAG;AAAA,EACxD;AACF;AAEO,SAAS,YAAY,MAA+B;AACzD,MAAI,CAAC,UAAU,QAAQ,EAAE,SAAS,OAAO,IAAI,GAAG;AAC9C,WAAO,GAAG,IAAI;AAAA,EAChB;AACA,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,EACT;AACA,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,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,SAAS;AACvB,UAAI,SAAS,QAAQ,UAAU,KAAK,CAAC,GAAG;AACtC,eAAO,CAAC,OAAO,OAAO,KAAK,CAAC;AAAA,MAC9B;AACA,aAAO,KAAK,CAAC;AAAA,IACf;AAAA,IACA,IAAI,SAA4B;AAC9B,YAAM,QAAW,OAAO,YAAY,aAAc,QAAgB,KAAK,OAAO,IAAI;AAClF,eAAS,IAAI,cAAc,SAAS,SAAS,KAAK,CAAC;AAAA,IACrD;AAAA,EACF;AACF;AAEO,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAIjD,YAAY,SAA8B;AACxC,UAAM;AAAA,QACF,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kHASwE,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA,6GAGvC,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAW1I;AAED,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ,UAAU;AAIhC,SAAK,SAAS;AAAA,EAChB;AACF;AA0BO,SAAS,aAAa,QAAiB;AAC5C,MAAI,KAAC,0BAAc,GAAG;AACpB,UAAM,IAAI,wBAAwB,EAAE,OAAO,CAAC;AAAA,EAC9C;AACF;","names":["React"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React, { SetStateAction } from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve } from \"./promises\";\nimport { deindent } from \"./strings\";\n\nexport function componentWrapper<\n C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements,\n ExtraProps extends {} = {}\n>(displayName: string, render: React.ForwardRefRenderFunction<RefFromComponent<C>, React.ComponentPropsWithRef<C> & ExtraProps>) {\n const Component = forwardRefIfNeeded(render);\n Component.displayName = displayName;\n return Component;\n}\ntype RefFromComponent<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements> = NonNullable<RefFromComponentDistCond<React.ComponentPropsWithRef<C>[\"ref\"]>>;\ntype RefFromComponentDistCond<A> = A extends React.RefObject<infer T> ? T : never; // distributive conditional type; see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n\nexport function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & { ref?: React.Ref<T> }> {\n // TODO: when we drop support for react 18, remove this\n\n const version = React.version;\n const major = parseInt(version.split(\".\")[0]);\n if (major < 19) {\n return React.forwardRef<T, P>(render as any) as any;\n } else {\n return ((props: P) => render(props, (props as any).ref)) as any;\n }\n}\n\nexport function getNodeText(node: React.ReactNode): string {\n if ([\"number\", \"string\"].includes(typeof node)) {\n return `${node}`;\n }\n if (!node) {\n return \"\";\n }\n if (Array.isArray(node)) {\n return node.map(getNodeText).join(\"\");\n }\n if (typeof node === \"object\" && \"props\" in node) {\n return getNodeText(node.props.children);\n }\n throw new Error(`Unknown node type: ${typeof node}`);\n}\nundefined?.test(\"getNodeText\", ({ expect }) => {\n // Test with string\n expect(getNodeText(\"hello\")).toBe(\"hello\");\n\n // Test with number\n expect(getNodeText(42)).toBe(\"42\");\n\n // Test with null/undefined\n expect(getNodeText(null)).toBe(\"\");\n expect(getNodeText(undefined)).toBe(\"\");\n\n // Test with array\n expect(getNodeText([\"hello\", \" \", \"world\"])).toBe(\"hello world\");\n expect(getNodeText([1, 2, 3])).toBe(\"123\");\n\n // Test with mixed array\n expect(getNodeText([\"hello\", 42, null])).toBe(\"hello42\");\n\n // Test with React element (mocked)\n const mockElement = {\n props: {\n children: \"child text\"\n }\n } as React.ReactElement;\n expect(getNodeText(mockElement)).toBe(\"child text\");\n\n // Test with nested React elements\n const nestedElement = {\n props: {\n children: {\n props: {\n children: \"nested text\"\n }\n } as React.ReactElement\n }\n } as React.ReactElement;\n expect(getNodeText(nestedElement)).toBe(\"nested text\");\n\n // Test with array of React elements\n const arrayOfElements = [\n { props: { children: \"first\" } } as React.ReactElement,\n { props: { children: \"second\" } } as React.ReactElement\n ];\n expect(getNodeText(arrayOfElements)).toBe(\"firstsecond\");\n});\n\n/**\n * Suspends the currently rendered component indefinitely. Will not unsuspend unless the component rerenders.\n *\n * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`\n */\nexport function suspend(): never {\n React.use(neverResolve());\n throw new Error(\"Somehow a Promise that never resolves was resolved?\");\n}\n\nexport function mapRef<T, R>(ref: ReadonlyRef<T>, mapper: (value: T) => R): ReadonlyRef<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = ref.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n };\n}\n\nexport type ReadonlyRef<T> = {\n readonly current: T,\n};\n\nexport type RefState<T> = ReadonlyRef<T> & {\n set: (updater: SetStateAction<T>) => void,\n};\n\n/**\n * Like useState, but its value is immediately available on refState.current after being set.\n *\n * Like useRef, but setting the value will cause a rerender.\n *\n * Note that useRefState returns a new object every time a rerender happens due to a value change, which is intentional\n * as it allows you to specify it in a dependency array like this:\n *\n * ```tsx\n * useEffect(() => {\n * // do something with refState.current\n * }, [refState]); // instead of refState.current\n * ```\n *\n * If you don't want this, you can wrap the result in a useMemo call.\n */\nexport function useRefState<T>(initialValue: T): RefState<T> {\n const [, setState] = React.useState(initialValue);\n const ref = React.useRef(initialValue);\n const setValue = React.useCallback((updater: SetStateAction<T>) => {\n const value: T = typeof updater === \"function\" ? (updater as any)(ref.current) : updater;\n ref.current = value;\n setState(value);\n }, []);\n const res = React.useMemo(() => ({\n get current() {\n return ref.current;\n },\n set: setValue,\n }), [setValue]);\n return res;\n}\n\nexport function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = refState.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n set(updater: SetStateAction<R>) {\n const value: R = typeof updater === \"function\" ? (updater as any)(this.current) : updater;\n refState.set(reverseMapper(refState.current, value));\n },\n };\n}\n\nexport function shouldRethrowRenderingError(error: unknown): boolean {\n return !!error && typeof error === \"object\" && \"digest\" in error && error.digest === \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n\n constructor(options: { caller?: string }) {\n super(deindent`\n Suspense boundary not found! Read the error message below carefully on how to fix it.\n\n ${options.caller ?? \"This code path\"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.\n \n The fix depends on which of the 4 scenarios caused it:\n \n 1. [Next.js] You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.\n\n 2. [React] You are missing a <Suspense> boundary in your component. Fix it by wrapping your component (or the entire app) in a <Suspense> component.\n\n 3. [Next.js] The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:\n\n - app\n - - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? \"this code path\"}\n - - loading.tsx // required for suspense\n - - (main)\n - - - layout.tsx // contains the main layout of your app, like a sidebar or a header, and can use ${options.caller ?? \"this code path\"}\n - - - route.tsx // your actual main page\n - - - the rest of your app\n\n For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups\n \n 4. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.\n\n See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n\n More information on SSR and Suspense boundaries: https://react.dev/reference/react/Suspense#providing-a-fallback-for-server-errors-and-client-only-content\n `);\n\n this.name = \"NoSuspenseBoundaryError\";\n this.reason = options.caller ?? \"suspendIfSsr()\";\n\n // set the digest so nextjs doesn't log the error\n // https://github.com/vercel/next.js/blob/d01d6d9c35a8c2725b3d74c1402ab76d4779a6cf/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts#L14\n this.digest = \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n }\n}\nundefined?.test(\"NoSuspenseBoundaryError\", ({ expect }) => {\n // Test with default options\n const defaultError = new NoSuspenseBoundaryError({});\n expect(defaultError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(defaultError.reason).toBe(\"suspendIfSsr()\");\n expect(defaultError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(defaultError.message).toContain(\"This code path attempted to display a loading indicator\");\n\n // Test with custom caller\n const customError = new NoSuspenseBoundaryError({ caller: \"CustomComponent\" });\n expect(customError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(customError.reason).toBe(\"CustomComponent\");\n expect(customError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(customError.message).toContain(\"CustomComponent attempted to display a loading indicator\");\n\n // Verify error message contains all the necessary information\n expect(customError.message).toContain(\"loading.tsx\");\n expect(customError.message).toContain(\"route groups\");\n expect(customError.message).toContain(\"https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\");\n});\n\n\n/**\n * Use this in a component or a hook to disable SSR. Should be wrapped in a Suspense boundary, or it will throw an error.\n */\nexport function suspendIfSsr(caller?: string) {\n if (!isBrowserLike()) {\n throw new NoSuspenseBoundaryError({ caller });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAsC;AACtC,iBAA8B;AAC9B,sBAA6B;AAC7B,qBAAyB;AAElB,SAAS,iBAGd,aAAqB,QAA0G;AAC/H,QAAM,YAAY,mBAAmB,MAAM;AAC3C,YAAU,cAAc;AACxB,SAAO;AACT;AAIO,SAAS,mBAA8B,QAAoF;AAGhI,QAAM,UAAU,aAAAA,QAAM;AACtB,QAAM,QAAQ,SAA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I,wBAAwB,EAAE,OAAO,CAAC;AAAA,EAC9C;AACF;","names":["React"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/utils/regex.tsx
|
|
21
|
+
var regex_exports = {};
|
|
22
|
+
__export(regex_exports, {
|
|
23
|
+
createCachedRegex: () => createCachedRegex
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(regex_exports);
|
|
26
|
+
var cachedRegexes = /* @__PURE__ */ new Map();
|
|
27
|
+
function createCachedRegex(pattern) {
|
|
28
|
+
const cached = cachedRegexes.get(pattern);
|
|
29
|
+
if (cached) return cached;
|
|
30
|
+
const regex = new RegExp(pattern);
|
|
31
|
+
cachedRegexes.set(pattern, regex);
|
|
32
|
+
return regex;
|
|
33
|
+
}
|
|
34
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
35
|
+
0 && (module.exports = {
|
|
36
|
+
createCachedRegex
|
|
37
|
+
});
|
|
38
|
+
//# sourceMappingURL=regex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/regex.tsx"],"sourcesContent":["const cachedRegexes = new Map<string, RegExp>();\n\nexport function createCachedRegex(pattern: string) {\n const cached = cachedRegexes.get(pattern);\n if (cached) return cached;\n\n const regex = new RegExp(pattern);\n cachedRegexes.set(pattern, regex);\n return regex;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,gBAAgB,oBAAI,IAAoB;AAEvC,SAAS,kBAAkB,SAAiB;AACjD,QAAM,SAAS,cAAc,IAAI,OAAO;AACxC,MAAI,OAAQ,QAAO;AAEnB,QAAM,QAAQ,IAAI,OAAO,OAAO;AAChC,gBAAc,IAAI,SAAS,KAAK;AAChC,SAAO;AACT;","names":[]}
|
package/dist/utils/urls.d.mts
CHANGED
|
@@ -18,5 +18,7 @@ declare function url(strings: TemplateStringsArray | readonly string[], ...value
|
|
|
18
18
|
* Any values passed are encoded.
|
|
19
19
|
*/
|
|
20
20
|
declare function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): string;
|
|
21
|
+
declare function isChildUrl(parentUrl: URL, maybeChildUrl: URL): boolean;
|
|
22
|
+
declare function isChildPath(parentPath: string, maybeChildPath: string): boolean;
|
|
21
23
|
|
|
22
|
-
export { createUrlIfValid, getRelativePart, isLocalhost, isRelative, isValidHostname, isValidHostnameWithWildcards, isValidUrl, matchHostnamePattern, url, urlString };
|
|
24
|
+
export { createUrlIfValid, getRelativePart, isChildPath, isChildUrl, isLocalhost, isRelative, isValidHostname, isValidHostnameWithWildcards, isValidUrl, matchHostnamePattern, url, urlString };
|
package/dist/utils/urls.d.ts
CHANGED
|
@@ -18,5 +18,7 @@ declare function url(strings: TemplateStringsArray | readonly string[], ...value
|
|
|
18
18
|
* Any values passed are encoded.
|
|
19
19
|
*/
|
|
20
20
|
declare function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): string;
|
|
21
|
+
declare function isChildUrl(parentUrl: URL, maybeChildUrl: URL): boolean;
|
|
22
|
+
declare function isChildPath(parentPath: string, maybeChildPath: string): boolean;
|
|
21
23
|
|
|
22
|
-
export { createUrlIfValid, getRelativePart, isLocalhost, isRelative, isValidHostname, isValidHostnameWithWildcards, isValidUrl, matchHostnamePattern, url, urlString };
|
|
24
|
+
export { createUrlIfValid, getRelativePart, isChildPath, isChildUrl, isLocalhost, isRelative, isValidHostname, isValidHostnameWithWildcards, isValidUrl, matchHostnamePattern, url, urlString };
|
package/dist/utils/urls.js
CHANGED
|
@@ -22,6 +22,8 @@ var urls_exports = {};
|
|
|
22
22
|
__export(urls_exports, {
|
|
23
23
|
createUrlIfValid: () => createUrlIfValid,
|
|
24
24
|
getRelativePart: () => getRelativePart,
|
|
25
|
+
isChildPath: () => isChildPath,
|
|
26
|
+
isChildUrl: () => isChildUrl,
|
|
25
27
|
isLocalhost: () => isLocalhost,
|
|
26
28
|
isRelative: () => isRelative,
|
|
27
29
|
isValidHostname: () => isValidHostname,
|
|
@@ -125,10 +127,20 @@ function url(strings, ...values) {
|
|
|
125
127
|
function urlString(strings, ...values) {
|
|
126
128
|
return (0, import_strings.templateIdentity)(strings, ...values.map(encodeURIComponent));
|
|
127
129
|
}
|
|
130
|
+
function isChildUrl(parentUrl, maybeChildUrl) {
|
|
131
|
+
return parentUrl.origin === maybeChildUrl.origin && isChildPath(parentUrl.pathname, maybeChildUrl.pathname) && [...parentUrl.searchParams].every(([key, value]) => maybeChildUrl.searchParams.get(key) === value) && (!parentUrl.hash || parentUrl.hash === maybeChildUrl.hash);
|
|
132
|
+
}
|
|
133
|
+
function isChildPath(parentPath, maybeChildPath) {
|
|
134
|
+
parentPath = parentPath.endsWith("/") ? parentPath : parentPath + "/";
|
|
135
|
+
maybeChildPath = maybeChildPath.endsWith("/") ? maybeChildPath : maybeChildPath + "/";
|
|
136
|
+
return maybeChildPath.startsWith(parentPath);
|
|
137
|
+
}
|
|
128
138
|
// Annotate the CommonJS export names for ESM import in node:
|
|
129
139
|
0 && (module.exports = {
|
|
130
140
|
createUrlIfValid,
|
|
131
141
|
getRelativePart,
|
|
142
|
+
isChildPath,
|
|
143
|
+
isChildUrl,
|
|
132
144
|
isLocalhost,
|
|
133
145
|
isRelative,
|
|
134
146
|
isValidHostname,
|
package/dist/utils/urls.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/urls.tsx"],"sourcesContent":["import { generateSecureRandomString } from \"./crypto\";\nimport { templateIdentity } from \"./strings\";\n\nexport function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {\n try {\n return new URL(...args);\n } catch (e) {\n return null;\n }\n}\nundefined?.test(\"createUrlIfValid\", ({ expect }) => {\n // Test with valid URLs\n expect(createUrlIfValid(\"https://example.com\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"https://example.com/path?query=value#hash\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"/path\", \"https://example.com\")).toBeInstanceOf(URL);\n\n // Test with invalid URLs\n expect(createUrlIfValid(\"\")).toBeNull();\n expect(createUrlIfValid(\"not a url\")).toBeNull();\n expect(createUrlIfValid(\"http://\")).toBeNull();\n});\n\nexport function isValidUrl(url: string) {\n return !!createUrlIfValid(url);\n}\nundefined?.test(\"isValidUrl\", ({ expect }) => {\n // Test with valid URLs\n expect(isValidUrl(\"https://example.com\")).toBe(true);\n expect(isValidUrl(\"http://localhost:3000\")).toBe(true);\n expect(isValidUrl(\"ftp://example.com\")).toBe(true);\n\n // Test with invalid URLs\n expect(isValidUrl(\"\")).toBe(false);\n expect(isValidUrl(\"not a url\")).toBe(false);\n expect(isValidUrl(\"http://\")).toBe(false);\n});\n\nexport function isValidHostname(hostname: string) {\n // Basic validation\n if (!hostname || hostname.startsWith('.') || hostname.endsWith('.') || hostname.includes('..')) {\n return false;\n }\n\n const url = createUrlIfValid(`https://${hostname}`);\n if (!url) return false;\n return url.hostname === hostname;\n}\nundefined?.test(\"isValidHostname\", ({ expect }) => {\n // Test with valid hostnames\n expect(isValidHostname(\"example.com\")).toBe(true);\n expect(isValidHostname(\"localhost\")).toBe(true);\n expect(isValidHostname(\"sub.domain.example.com\")).toBe(true);\n expect(isValidHostname(\"127.0.0.1\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostname(\"\")).toBe(false);\n expect(isValidHostname(\"example.com/path\")).toBe(false);\n expect(isValidHostname(\"https://example.com\")).toBe(false);\n expect(isValidHostname(\"example com\")).toBe(false);\n});\n\nexport function isValidHostnameWithWildcards(hostname: string) {\n // Empty hostnames are invalid\n if (!hostname) return false;\n\n // Check if it contains wildcards\n const hasWildcard = hostname.includes('*');\n\n if (!hasWildcard) {\n // If no wildcards, validate as a normal hostname\n return isValidHostname(hostname);\n }\n\n // Basic validation checks that apply even with wildcards\n // - Hostname cannot start or end with a dot\n if (hostname.startsWith('.') || hostname.endsWith('.')) {\n return false;\n }\n\n // - No consecutive dots\n if (hostname.includes('..')) {\n return false;\n }\n\n // For wildcard validation, check that non-wildcard parts contain valid characters\n // Replace wildcards with a valid placeholder to check the rest\n const testHostname = hostname.replace(/\\*+/g, 'wildcard');\n\n // Check if the resulting string would be a valid hostname\n if (!/^[a-zA-Z0-9.-]+$/.test(testHostname)) {\n return false;\n }\n\n // Additional check: ensure the pattern makes sense\n // Check each segment between wildcards\n const segments = hostname.split(/\\*+/);\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (segment === '') continue; // Empty segments are OK (consecutive wildcards)\n\n // First segment can't start with dot\n if (i === 0 && segment.startsWith('.')) {\n return false;\n }\n\n // Last segment can't end with dot\n if (i === segments.length - 1 && segment.endsWith('.')) {\n return false;\n }\n\n // No segment should have consecutive dots\n if (segment.includes('..')) {\n return false;\n }\n }\n\n return true;\n}\nundefined?.test(\"isValidHostnameWithWildcards\", ({ expect }) => {\n // Test with valid regular hostnames\n expect(isValidHostnameWithWildcards(\"example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"localhost\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.domain.example.com\")).toBe(true);\n\n // Test with valid wildcard hostnames\n expect(isValidHostnameWithWildcards(\"*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"a-*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*.*.org\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"**.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.**.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*-api.*.com\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostnameWithWildcards(\"\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com/path\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"https://example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\".example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com.\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example..com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"*.example..com\")).toBe(false);\n});\n\nexport function matchHostnamePattern(pattern: string, hostname: string): boolean {\n // If no wildcards, it's an exact match\n if (!pattern.includes('*')) {\n return pattern === hostname;\n }\n\n // Convert the pattern to a regex\n // First, escape all regex special characters except *\n let regexPattern = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n // Use a placeholder for ** to handle it separately from single *\n const doubleWildcardPlaceholder = '\\x00DOUBLE_WILDCARD\\x00';\n regexPattern = regexPattern.replace(/\\*\\*/g, doubleWildcardPlaceholder);\n\n // Replace single * with a pattern that matches anything except dots\n regexPattern = regexPattern.replace(/\\*/g, '[^.]*');\n\n // Replace the double wildcard placeholder with a pattern that matches anything including dots\n regexPattern = regexPattern.replace(new RegExp(doubleWildcardPlaceholder, 'g'), '.*');\n\n // Anchor the pattern to match the entire hostname\n regexPattern = '^' + regexPattern + '$';\n\n try {\n const regex = new RegExp(regexPattern);\n return regex.test(hostname);\n } catch {\n return false;\n }\n}\nundefined?.test(\"matchHostnamePattern\", ({ expect }) => {\n // Test exact matches\n expect(matchHostnamePattern(\"example.com\", \"example.com\")).toBe(true);\n expect(matchHostnamePattern(\"example.com\", \"other.com\")).toBe(false);\n\n // Test single wildcard matches\n expect(matchHostnamePattern(\"*.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"www.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.example.com\", \"api.v2.example.com\")).toBe(false);\n\n // Test double wildcard matches\n expect(matchHostnamePattern(\"**.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"api.v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"a.b.c.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"example.com\")).toBe(false);\n\n // Test complex patterns\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v1.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api.example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.*.org\", \"mail.example.org\")).toBe(true);\n expect(matchHostnamePattern(\"*.*.org\", \"example.org\")).toBe(false);\n});\n\nexport function isLocalhost(urlOrString: string | URL) {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n if (url.hostname === \"localhost\" || url.hostname.endsWith(\".localhost\")) return true;\n if (url.hostname.match(/^127\\.\\d+\\.\\d+\\.\\d+$/)) return true;\n return false;\n}\nundefined?.test(\"isLocalhost\", ({ expect }) => {\n // Test with localhost URLs\n expect(isLocalhost(\"http://localhost\")).toBe(true);\n expect(isLocalhost(\"https://localhost:8080\")).toBe(true);\n expect(isLocalhost(\"http://sub.localhost\")).toBe(true);\n expect(isLocalhost(\"http://127.0.0.1\")).toBe(true);\n expect(isLocalhost(\"http://127.1.2.3\")).toBe(true);\n\n // Test with non-localhost URLs\n expect(isLocalhost(\"https://example.com\")).toBe(false);\n expect(isLocalhost(\"http://192.168.1.1\")).toBe(false);\n expect(isLocalhost(\"http://10.0.0.1\")).toBe(false);\n\n // Test with URL objects\n expect(isLocalhost(new URL(\"http://localhost\"))).toBe(true);\n expect(isLocalhost(new URL(\"https://example.com\"))).toBe(false);\n\n // Test with invalid URLs\n expect(isLocalhost(\"not a url\")).toBe(false);\n expect(isLocalhost(\"\")).toBe(false);\n});\n\nexport function isRelative(url: string) {\n const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;\n const u = createUrlIfValid(url, `https://${randomDomain}`);\n if (!u) return false;\n if (u.host !== randomDomain) return false;\n if (u.protocol !== \"https:\") return false;\n return true;\n}\nundefined?.test(\"isRelative\", ({ expect }) => {\n // We can't easily mock generateSecureRandomString in this context\n // but we can still test the function's behavior\n\n // Test with relative URLs\n expect(isRelative(\"/\")).toBe(true);\n expect(isRelative(\"/path\")).toBe(true);\n expect(isRelative(\"/path?query=value#hash\")).toBe(true);\n\n // Test with absolute URLs\n expect(isRelative(\"https://example.com\")).toBe(false);\n expect(isRelative(\"http://example.com\")).toBe(false);\n expect(isRelative(\"//example.com\")).toBe(false);\n\n // Note: The implementation treats empty strings and invalid URLs as relative\n // This is because they can be resolved against a base URL\n expect(isRelative(\"\")).toBe(true);\n expect(isRelative(\"not a url\")).toBe(true);\n});\n\nexport function getRelativePart(url: URL) {\n return url.pathname + url.search + url.hash;\n}\nundefined?.test(\"getRelativePart\", ({ expect }) => {\n // Test with various URLs\n expect(getRelativePart(new URL(\"https://example.com\"))).toBe(\"/\");\n expect(getRelativePart(new URL(\"https://example.com/path\"))).toBe(\"/path\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value\"))).toBe(\"/path?query=value\");\n expect(getRelativePart(new URL(\"https://example.com/path#hash\"))).toBe(\"/path#hash\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value#hash\"))).toBe(\"/path?query=value#hash\");\n\n // Test with different domains but same paths\n const url1 = new URL(\"https://example.com/path?query=value#hash\");\n const url2 = new URL(\"https://different.com/path?query=value#hash\");\n expect(getRelativePart(url1)).toBe(getRelativePart(url2));\n});\n\n/**\n * A template literal tag that returns a URL.\n *\n * Any values passed are encoded.\n */\nexport function url(strings: TemplateStringsArray | readonly string[], ...values: (string|number|boolean)[]): URL {\n return new URL(urlString(strings, ...values));\n}\nundefined?.test(\"url\", ({ expect }) => {\n // Test with no interpolation\n expect(url`https://example.com`).toBeInstanceOf(URL);\n expect(url`https://example.com`.href).toBe(\"https://example.com/\");\n\n // Test with string interpolation\n expect(url`https://example.com/${\"path\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}`.pathname).toBe(\"/path\");\n\n // Test with number interpolation\n expect(url`https://example.com/${42}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${42}`.pathname).toBe(\"/42\");\n\n // Test with boolean interpolation\n expect(url`https://example.com/${true}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${true}`.pathname).toBe(\"/true\");\n\n // Test with special characters in interpolation\n expect(url`https://example.com/${\"path with spaces\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path with spaces\"}`.pathname).toBe(\"/path%20with%20spaces\");\n\n // Test with multiple interpolations\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.pathname).toBe(\"/path\");\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.search).toBe(\"?query=value\");\n});\n\n\n/**\n * A template literal tag that returns a URL string.\n *\n * Any values passed are encoded.\n */\nexport function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string|number|boolean)[]): string {\n return templateIdentity(strings, ...values.map(encodeURIComponent));\n}\nundefined?.test(\"urlString\", ({ expect }) => {\n // Test with no interpolation\n expect(urlString`https://example.com`).toBe(\"https://example.com\");\n\n // Test with string interpolation\n expect(urlString`https://example.com/${\"path\"}`).toBe(\"https://example.com/path\");\n\n // Test with number interpolation\n expect(urlString`https://example.com/${42}`).toBe(\"https://example.com/42\");\n\n // Test with boolean interpolation\n expect(urlString`https://example.com/${true}`).toBe(\"https://example.com/true\");\n\n // Test with special characters in interpolation\n expect(urlString`https://example.com/${\"path with spaces\"}`).toBe(\"https://example.com/path%20with%20spaces\");\n expect(urlString`https://example.com/${\"?&=\"}`).toBe(\"https://example.com/%3F%26%3D\");\n\n // Test with multiple interpolations\n expect(urlString`https://example.com/${\"path\"}?query=${\"value\"}`).toBe(\"https://example.com/path?query=value\");\n expect(urlString`https://example.com/${\"path\"}?query=${\"value with spaces\"}`).toBe(\"https://example.com/path?query=value%20with%20spaces\");\n});\n\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2C;AAC3C,qBAAiC;AAE1B,SAAS,oBAAoB,MAAyC;AAC3E,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,IAAI;AAAA,EACxB,SAAS,GAAG;AACV,WAAO;AAAA,EACT;AACF;AAaO,SAAS,WAAWA,MAAa;AACtC,SAAO,CAAC,CAAC,iBAAiBA,IAAG;AAC/B;AAaO,SAAS,gBAAgB,UAAkB;AAEhD,MAAI,CAAC,YAAY,SAAS,WAAW,GAAG,KAAK,SAAS,SAAS,GAAG,KAAK,SAAS,SAAS,IAAI,GAAG;AAC9F,WAAO;AAAA,EACT;AAEA,QAAMA,OAAM,iBAAiB,WAAW,QAAQ,EAAE;AAClD,MAAI,CAACA,KAAK,QAAO;AACjB,SAAOA,KAAI,aAAa;AAC1B;AAeO,SAAS,6BAA6B,UAAkB;AAE7D,MAAI,CAAC,SAAU,QAAO;AAGtB,QAAM,cAAc,SAAS,SAAS,GAAG;AAEzC,MAAI,CAAC,a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AACxC,MAAI,CAACA,KAAK,QAAO;AACjB,MAAIA,KAAI,aAAa,eAAeA,KAAI,SAAS,SAAS,YAAY,EAAG,QAAO;AAChF,MAAIA,KAAI,SAAS,MAAM,sBAAsB,EAAG,QAAO;AACvD,SAAO;AACT;AAuBO,SAAS,WAAWA,MAAa;AACtC,QAAM,eAAe,OAAG,0CAA2B,CAAC;AACpD,QAAM,IAAI,iBAAiBA,MAAK,WAAW,YAAY,EAAE;AACzD,MAAI,CAAC,EAAG,QAAO;AACf,MAAI,EAAE,SAAS,aAAc,QAAO;AACpC,MAAI,EAAE,aAAa,SAAU,QAAO;AACpC,SAAO;AACT;AAqBO,SAAS,gBAAgBA,MAAU;AACxC,SAAOA,KAAI,WAAWA,KAAI,SAASA,KAAI;AACzC;AAoBO,SAAS,IAAI,YAAsD,QAAwC;AAChH,SAAO,IAAI,IAAI,UAAU,SAAS,GAAG,MAAM,CAAC;AAC9C;AAkCO,SAAS,UAAU,YAAsD,QAA2C;AACzH,aAAO,iCAAiB,SAAS,GAAG,OAAO,IAAI,kBAAkB,CAAC;AACpE;","names":["url"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/urls.tsx"],"sourcesContent":["import { generateSecureRandomString } from \"./crypto\";\nimport { templateIdentity } from \"./strings\";\n\nexport function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {\n try {\n return new URL(...args);\n } catch (e) {\n return null;\n }\n}\nundefined?.test(\"createUrlIfValid\", ({ expect }) => {\n // Test with valid URLs\n expect(createUrlIfValid(\"https://example.com\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"https://example.com/path?query=value#hash\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"/path\", \"https://example.com\")).toBeInstanceOf(URL);\n\n // Test with invalid URLs\n expect(createUrlIfValid(\"\")).toBeNull();\n expect(createUrlIfValid(\"not a url\")).toBeNull();\n expect(createUrlIfValid(\"http://\")).toBeNull();\n});\n\nexport function isValidUrl(url: string) {\n return !!createUrlIfValid(url);\n}\nundefined?.test(\"isValidUrl\", ({ expect }) => {\n // Test with valid URLs\n expect(isValidUrl(\"https://example.com\")).toBe(true);\n expect(isValidUrl(\"http://localhost:3000\")).toBe(true);\n expect(isValidUrl(\"ftp://example.com\")).toBe(true);\n\n // Test with invalid URLs\n expect(isValidUrl(\"\")).toBe(false);\n expect(isValidUrl(\"not a url\")).toBe(false);\n expect(isValidUrl(\"http://\")).toBe(false);\n});\n\nexport function isValidHostname(hostname: string) {\n // Basic validation\n if (!hostname || hostname.startsWith('.') || hostname.endsWith('.') || hostname.includes('..')) {\n return false;\n }\n\n const url = createUrlIfValid(`https://${hostname}`);\n if (!url) return false;\n return url.hostname === hostname;\n}\nundefined?.test(\"isValidHostname\", ({ expect }) => {\n // Test with valid hostnames\n expect(isValidHostname(\"example.com\")).toBe(true);\n expect(isValidHostname(\"localhost\")).toBe(true);\n expect(isValidHostname(\"sub.domain.example.com\")).toBe(true);\n expect(isValidHostname(\"127.0.0.1\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostname(\"\")).toBe(false);\n expect(isValidHostname(\"example.com/path\")).toBe(false);\n expect(isValidHostname(\"https://example.com\")).toBe(false);\n expect(isValidHostname(\"example com\")).toBe(false);\n});\n\nexport function isValidHostnameWithWildcards(hostname: string) {\n // Empty hostnames are invalid\n if (!hostname) return false;\n\n // Check if it contains wildcards\n const hasWildcard = hostname.includes('*');\n\n if (!hasWildcard) {\n // If no wildcards, validate as a normal hostname\n return isValidHostname(hostname);\n }\n\n // Basic validation checks that apply even with wildcards\n // - Hostname cannot start or end with a dot\n if (hostname.startsWith('.') || hostname.endsWith('.')) {\n return false;\n }\n\n // - No consecutive dots\n if (hostname.includes('..')) {\n return false;\n }\n\n // For wildcard validation, check that non-wildcard parts contain valid characters\n // Replace wildcards with a valid placeholder to check the rest\n const testHostname = hostname.replace(/\\*+/g, 'wildcard');\n\n // Check if the resulting string would be a valid hostname\n if (!/^[a-zA-Z0-9.-]+$/.test(testHostname)) {\n return false;\n }\n\n // Additional check: ensure the pattern makes sense\n // Check each segment between wildcards\n const segments = hostname.split(/\\*+/);\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (segment === '') continue; // Empty segments are OK (consecutive wildcards)\n\n // First segment can't start with dot\n if (i === 0 && segment.startsWith('.')) {\n return false;\n }\n\n // Last segment can't end with dot\n if (i === segments.length - 1 && segment.endsWith('.')) {\n return false;\n }\n\n // No segment should have consecutive dots\n if (segment.includes('..')) {\n return false;\n }\n }\n\n return true;\n}\nundefined?.test(\"isValidHostnameWithWildcards\", ({ expect }) => {\n // Test with valid regular hostnames\n expect(isValidHostnameWithWildcards(\"example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"localhost\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.domain.example.com\")).toBe(true);\n\n // Test with valid wildcard hostnames\n expect(isValidHostnameWithWildcards(\"*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"a-*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*.*.org\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"**.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.**.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*-api.*.com\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostnameWithWildcards(\"\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com/path\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"https://example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\".example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com.\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example..com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"*.example..com\")).toBe(false);\n});\n\nexport function matchHostnamePattern(pattern: string, hostname: string): boolean {\n // If no wildcards, it's an exact match\n if (!pattern.includes('*')) {\n return pattern === hostname;\n }\n\n // Convert the pattern to a regex\n // First, escape all regex special characters except *\n let regexPattern = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n // Use a placeholder for ** to handle it separately from single *\n const doubleWildcardPlaceholder = '\\x00DOUBLE_WILDCARD\\x00';\n regexPattern = regexPattern.replace(/\\*\\*/g, doubleWildcardPlaceholder);\n\n // Replace single * with a pattern that matches anything except dots\n regexPattern = regexPattern.replace(/\\*/g, '[^.]*');\n\n // Replace the double wildcard placeholder with a pattern that matches anything including dots\n regexPattern = regexPattern.replace(new RegExp(doubleWildcardPlaceholder, 'g'), '.*');\n\n // Anchor the pattern to match the entire hostname\n regexPattern = '^' + regexPattern + '$';\n\n try {\n const regex = new RegExp(regexPattern);\n return regex.test(hostname);\n } catch {\n return false;\n }\n}\nundefined?.test(\"matchHostnamePattern\", ({ expect }) => {\n // Test exact matches\n expect(matchHostnamePattern(\"example.com\", \"example.com\")).toBe(true);\n expect(matchHostnamePattern(\"example.com\", \"other.com\")).toBe(false);\n\n // Test single wildcard matches\n expect(matchHostnamePattern(\"*.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"www.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.example.com\", \"api.v2.example.com\")).toBe(false);\n\n // Test double wildcard matches\n expect(matchHostnamePattern(\"**.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"api.v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"a.b.c.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"example.com\")).toBe(false);\n\n // Test complex patterns\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v1.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api.example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.*.org\", \"mail.example.org\")).toBe(true);\n expect(matchHostnamePattern(\"*.*.org\", \"example.org\")).toBe(false);\n});\n\nexport function isLocalhost(urlOrString: string | URL) {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n if (url.hostname === \"localhost\" || url.hostname.endsWith(\".localhost\")) return true;\n if (url.hostname.match(/^127\\.\\d+\\.\\d+\\.\\d+$/)) return true;\n return false;\n}\nundefined?.test(\"isLocalhost\", ({ expect }) => {\n // Test with localhost URLs\n expect(isLocalhost(\"http://localhost\")).toBe(true);\n expect(isLocalhost(\"https://localhost:8080\")).toBe(true);\n expect(isLocalhost(\"http://sub.localhost\")).toBe(true);\n expect(isLocalhost(\"http://127.0.0.1\")).toBe(true);\n expect(isLocalhost(\"http://127.1.2.3\")).toBe(true);\n\n // Test with non-localhost URLs\n expect(isLocalhost(\"https://example.com\")).toBe(false);\n expect(isLocalhost(\"http://192.168.1.1\")).toBe(false);\n expect(isLocalhost(\"http://10.0.0.1\")).toBe(false);\n\n // Test with URL objects\n expect(isLocalhost(new URL(\"http://localhost\"))).toBe(true);\n expect(isLocalhost(new URL(\"https://example.com\"))).toBe(false);\n\n // Test with invalid URLs\n expect(isLocalhost(\"not a url\")).toBe(false);\n expect(isLocalhost(\"\")).toBe(false);\n});\n\nexport function isRelative(url: string) {\n const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;\n const u = createUrlIfValid(url, `https://${randomDomain}`);\n if (!u) return false;\n if (u.host !== randomDomain) return false;\n if (u.protocol !== \"https:\") return false;\n return true;\n}\nundefined?.test(\"isRelative\", ({ expect }) => {\n // We can't easily mock generateSecureRandomString in this context\n // but we can still test the function's behavior\n\n // Test with relative URLs\n expect(isRelative(\"/\")).toBe(true);\n expect(isRelative(\"/path\")).toBe(true);\n expect(isRelative(\"/path?query=value#hash\")).toBe(true);\n\n // Test with absolute URLs\n expect(isRelative(\"https://example.com\")).toBe(false);\n expect(isRelative(\"http://example.com\")).toBe(false);\n expect(isRelative(\"//example.com\")).toBe(false);\n\n // Note: The implementation treats empty strings and invalid URLs as relative\n // This is because they can be resolved against a base URL\n expect(isRelative(\"\")).toBe(true);\n expect(isRelative(\"not a url\")).toBe(true);\n});\n\nexport function getRelativePart(url: URL) {\n return url.pathname + url.search + url.hash;\n}\nundefined?.test(\"getRelativePart\", ({ expect }) => {\n // Test with various URLs\n expect(getRelativePart(new URL(\"https://example.com\"))).toBe(\"/\");\n expect(getRelativePart(new URL(\"https://example.com/path\"))).toBe(\"/path\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value\"))).toBe(\"/path?query=value\");\n expect(getRelativePart(new URL(\"https://example.com/path#hash\"))).toBe(\"/path#hash\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value#hash\"))).toBe(\"/path?query=value#hash\");\n\n // Test with different domains but same paths\n const url1 = new URL(\"https://example.com/path?query=value#hash\");\n const url2 = new URL(\"https://different.com/path?query=value#hash\");\n expect(getRelativePart(url1)).toBe(getRelativePart(url2));\n});\n\n/**\n * A template literal tag that returns a URL.\n *\n * Any values passed are encoded.\n */\nexport function url(strings: TemplateStringsArray | readonly string[], ...values: (string|number|boolean)[]): URL {\n return new URL(urlString(strings, ...values));\n}\nundefined?.test(\"url\", ({ expect }) => {\n // Test with no interpolation\n expect(url`https://example.com`).toBeInstanceOf(URL);\n expect(url`https://example.com`.href).toBe(\"https://example.com/\");\n\n // Test with string interpolation\n expect(url`https://example.com/${\"path\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}`.pathname).toBe(\"/path\");\n\n // Test with number interpolation\n expect(url`https://example.com/${42}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${42}`.pathname).toBe(\"/42\");\n\n // Test with boolean interpolation\n expect(url`https://example.com/${true}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${true}`.pathname).toBe(\"/true\");\n\n // Test with special characters in interpolation\n expect(url`https://example.com/${\"path with spaces\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path with spaces\"}`.pathname).toBe(\"/path%20with%20spaces\");\n\n // Test with multiple interpolations\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.pathname).toBe(\"/path\");\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.search).toBe(\"?query=value\");\n});\n\n\n/**\n * A template literal tag that returns a URL string.\n *\n * Any values passed are encoded.\n */\nexport function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string|number|boolean)[]): string {\n return templateIdentity(strings, ...values.map(encodeURIComponent));\n}\nundefined?.test(\"urlString\", ({ expect }) => {\n // Test with no interpolation\n expect(urlString`https://example.com`).toBe(\"https://example.com\");\n\n // Test with string interpolation\n expect(urlString`https://example.com/${\"path\"}`).toBe(\"https://example.com/path\");\n\n // Test with number interpolation\n expect(urlString`https://example.com/${42}`).toBe(\"https://example.com/42\");\n\n // Test with boolean interpolation\n expect(urlString`https://example.com/${true}`).toBe(\"https://example.com/true\");\n\n // Test with special characters in interpolation\n expect(urlString`https://example.com/${\"path with spaces\"}`).toBe(\"https://example.com/path%20with%20spaces\");\n expect(urlString`https://example.com/${\"?&=\"}`).toBe(\"https://example.com/%3F%26%3D\");\n\n // Test with multiple interpolations\n expect(urlString`https://example.com/${\"path\"}?query=${\"value\"}`).toBe(\"https://example.com/path?query=value\");\n expect(urlString`https://example.com/${\"path\"}?query=${\"value with spaces\"}`).toBe(\"https://example.com/path?query=value%20with%20spaces\");\n});\n\nexport function isChildUrl(parentUrl: URL, maybeChildUrl: URL) {\n return parentUrl.origin === maybeChildUrl.origin\n && isChildPath(parentUrl.pathname, maybeChildUrl.pathname)\n && [...parentUrl.searchParams].every(([key, value]) => maybeChildUrl.searchParams.get(key) === value)\n && (!parentUrl.hash || parentUrl.hash === maybeChildUrl.hash);\n}\nundefined?.test(\"isChildUrl\", ({ expect }) => {\n // true\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(true);\n\n // false\n expect(isChildUrl(new URL(\"https://abc.com\"), new URL(\"https://example.com\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com?query=value123\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n});\n\nexport function isChildPath(parentPath: string, maybeChildPath: string) {\n parentPath = parentPath.endsWith(\"/\") ? parentPath : parentPath + \"/\";\n maybeChildPath = maybeChildPath.endsWith(\"/\") ? maybeChildPath : maybeChildPath + \"/\";\n return maybeChildPath.startsWith(parentPath);\n}\nundefined?.test(\"isSubPath\", ({ expect }) => {\n expect(isChildPath(\"/\", \"/\")).toBe(true);\n expect(isChildPath(\"/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path-abc/\")).toBe(false);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