Repository navigation
refactor(account): cut the private utility dependencies and prep ingest-types for publish #17839
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
f690c5a
a5bf629
c958099
f82d1da
60fe6c2
bc35cea
ff14898
e2f294f
4a4a7ed
d964c9e
75db0b3
efbbf75
5b20731
141617f
f19758a
aed8ecd
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| // Copy of packages/shared-frontend-utils/src/loadExternalScript.ts (three app callers keep that one); keep both in sync | ||
| const POLL_INTERVAL_MS = 50 | ||
|
|
||
| /** | ||
| * Returns a singleton loader for an external script. `getReady` should return | ||
| * the resolved value when the script's global is available, or `null` when not. | ||
| * The returned function caches the in-flight Promise so concurrent callers share | ||
| * one load, and resets on failure so a later caller can retry. | ||
| */ | ||
| export function createScriptLoader<T>( | ||
| src: string, | ||
| getReady: () => T | null, | ||
| timeoutMs = 10_000 | ||
| ): () => Promise<T> { | ||
| let scriptPromise: Promise<T> | null = null | ||
|
|
||
| return function loadScript(): Promise<T> { | ||
| if (scriptPromise) return scriptPromise | ||
|
|
||
| scriptPromise = new Promise<T>((resolve, reject) => { | ||
| let settled = false | ||
| let cancelPoll: (() => void) | undefined | ||
|
|
||
| function trySettle(fn: () => void) { | ||
| if (settled) return | ||
| settled = true | ||
| fn() | ||
| } | ||
|
|
||
| const ready = getReady() | ||
| if (ready !== null) { | ||
| resolve(ready) | ||
| return | ||
| } | ||
|
|
||
| const existing = document.querySelector<HTMLScriptElement>( | ||
| `script[src="${src}"]` | ||
| ) | ||
|
|
||
| function startPoll(onSuccess: () => void): () => void { | ||
| const pollId = window.setInterval(() => { | ||
| const value = getReady() | ||
| if (value !== null) { | ||
| window.clearInterval(pollId) | ||
| onSuccess() | ||
| trySettle(() => resolve(value)) | ||
| } | ||
| }, POLL_INTERVAL_MS) | ||
| return () => window.clearInterval(pollId) | ||
| } | ||
|
|
||
| if (existing) { | ||
| // load/error may have already fired on the pre-existing tag; poll for readiness | ||
| const timeoutId = window.setTimeout(() => { | ||
| cancelPoll?.() | ||
| trySettle(() => { | ||
| scriptPromise = null | ||
| reject(new Error(`Script load timed out: ${src}`)) | ||
| }) | ||
| }, timeoutMs) | ||
| cancelPoll = startPoll(() => window.clearTimeout(timeoutId)) | ||
| return | ||
| } | ||
|
|
||
| const scriptEl = document.createElement('script') | ||
|
|
||
| const timeoutId = window.setTimeout(() => { | ||
| cancelPoll?.() | ||
| scriptEl.remove() | ||
| trySettle(() => { | ||
| scriptPromise = null | ||
| reject(new Error(`Script load timed out: ${src}`)) | ||
| }) | ||
| }, timeoutMs) | ||
|
|
||
| scriptEl.addEventListener( | ||
| 'load', | ||
| () => { | ||
| if (settled) return | ||
| const value = getReady() | ||
| if (value !== null) { | ||
| window.clearTimeout(timeoutId) | ||
| trySettle(() => resolve(value)) | ||
| } else { | ||
| // global may arrive asynchronously after load; poll under the shared timeout | ||
| cancelPoll = startPoll(() => window.clearTimeout(timeoutId)) | ||
| } | ||
| }, | ||
| { once: true } | ||
| ) | ||
| scriptEl.addEventListener( | ||
| 'error', | ||
| () => { | ||
| window.clearTimeout(timeoutId) | ||
| scriptEl.remove() | ||
| trySettle(() => { | ||
| scriptPromise = null | ||
| reject(new Error(`Script failed to load: ${src}`)) | ||
| }) | ||
| }, | ||
| { once: true } | ||
| ) | ||
|
|
||
| scriptEl.src = src | ||
| scriptEl.async = true | ||
| document.head.appendChild(scriptEl) | ||
| }) | ||
|
|
||
| return scriptPromise | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| /** | ||
| * A CDN implementation detail, not a contract we own. The durable form is a | ||
| * first-party endpoint echoing `CF-IPCountry`. | ||
| */ | ||
| const CLIENT_COUNTRY_URL = 'https://cloud.comfy.org/cdn-cgi/trace' | ||
|
|
||
| /** Bounds every probe leg; two previously had none. */ | ||
| const PROBE_TIMEOUT_MS = 2000 | ||
|
|
||
| /** Baidu answering this fast implies a China route. */ | ||
| const CHINA_LATENCY_MS = 150 | ||
|
|
||
| /** `XX` is an unknown country and `T1` is Tor: neither names where the client is. */ | ||
| const UNRESOLVED_COUNTRIES = new Set(['XX', 'T1']) | ||
|
|
||
| const parseTraceCountry = (body: string): string | undefined => { | ||
| const country = | ||
| body | ||
| .split('\n') | ||
| .find((line) => line.startsWith('loc=')) | ||
| ?.slice('loc='.length) | ||
| .trim() | ||
| .toUpperCase() || undefined | ||
|
|
||
| return country && UNRESOLVED_COUNTRIES.has(country) ? undefined : country | ||
| } | ||
|
|
||
| /** | ||
| * The abort signal alone is not enough: a request the browser never resolves | ||
| * nor rejects would hang forever, so the deadline rejects independently. | ||
| * | ||
| * `read` runs inside the deadline so a response that sends headers and then | ||
| * stalls its body is bounded too. | ||
| */ | ||
| async function fetchWithin<T>( | ||
| url: string, | ||
| init: RequestInit, | ||
| read: (response: Response) => Promise<T> | ||
| ): Promise<T> { | ||
| const controller = new AbortController() | ||
| let expire: ReturnType<typeof setTimeout> | undefined | ||
|
|
||
| const deadline = new Promise<never>((_, reject) => { | ||
| expire = setTimeout(() => { | ||
| controller.abort() | ||
| reject(new Error(`Timed out after ${PROBE_TIMEOUT_MS}ms: ${url}`)) | ||
| }, PROBE_TIMEOUT_MS) | ||
| }) | ||
|
|
||
| try { | ||
| return await Promise.race([ | ||
| fetch(url, { ...init, signal: controller.signal }).then(read), | ||
| deadline | ||
| ]) | ||
| } finally { | ||
| clearTimeout(expire) | ||
| } | ||
| } | ||
|
|
||
| /** ISO country from the CDN edge, or `undefined` when it cannot answer. */ | ||
| export async function getClientCountry(): Promise<string | undefined> { | ||
| try { | ||
| const body = await fetchWithin( | ||
| CLIENT_COUNTRY_URL, | ||
| { cache: 'no-store' }, | ||
| async (response) => (response.ok ? response.text() : undefined) | ||
| ) | ||
| return body === undefined ? undefined : parseTraceCountry(body) | ||
| } catch { | ||
| return undefined | ||
| } | ||
| } | ||
|
|
||
| const probe = (url: string) => | ||
| fetchWithin(url, { mode: 'no-cors', cache: 'no-cache' }, async () => {}) | ||
|
|
||
| /** | ||
| * Fallback for when the edge cannot answer. Unsound both ways: a VPN user in | ||
| * China reaches Google, and a `zh-CN` user anywhere is blocked whenever Google | ||
| * is briefly unreachable. | ||
| */ | ||
| async function isInChinaByProbe(): Promise<boolean> { | ||
| const isChineseLocale = navigator.language.toLowerCase().startsWith('zh-cn') | ||
|
|
||
| try { | ||
| await probe('https://www.google.com') | ||
| return false | ||
| } catch { | ||
| if (isChineseLocale) return true | ||
|
|
||
| try { | ||
| const start = performance.now() | ||
| await probe('https://www.baidu.com') | ||
| return performance.now() - start < CHINA_LATENCY_MS | ||
| } catch { | ||
| return isChineseLocale | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Prefers the edge's geo-IP, falling back to the heuristic. Always settles, so | ||
| * callers must not add a timeout that could pre-empt a slow but real answer. | ||
| */ | ||
| export async function isInChina(): Promise<boolean> { | ||
| const country = await getClientCountry() | ||
| if (country !== undefined) return country === 'CN' | ||
|
|
||
| return isInChinaByProbe() | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { describe, expect, it } from 'vitest' | ||
|
|
||
| import { cn } from './cn' | ||
|
|
||
| describe('cn', () => { | ||
| it.for([ | ||
| [ | ||
| 'a custom font size overrides a stock one', | ||
| 'text-sm text-xxs', | ||
| 'text-xxs' | ||
| ], | ||
| [ | ||
| 'a stock font size overrides a custom one', | ||
| 'text-xxxs text-lg', | ||
| 'text-lg' | ||
| ], | ||
| [ | ||
| 'max-h-none overrides an arbitrary max height', | ||
| 'max-h-[80vh] max-h-none', | ||
| 'max-h-none' | ||
| ], | ||
| ['a falsy entry is dropped', ['p-2', false, 'm-1'], 'p-2 m-1'] | ||
| ] as const)('%s', ([, input, expected]) => { | ||
| expect(cn(input)).toBe(expected) | ||
| }) | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import { clsx } from 'clsx' | ||
| import type { ClassArray } from 'clsx' | ||
| import { extendTailwindMerge } from 'tailwind-merge' | ||
|
|
||
| // Mirrors packages/tailwind-utils/src/index.ts; keep both configs in sync | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion (non-blocking): same point as Your four-row merge test covers the current config. Extending it to assert the full |
||
| const twMerge = extendTailwindMerge({ | ||
| extend: { | ||
| classGroups: { | ||
| 'font-size': ['text-xxs', 'text-xxxs'], | ||
| // tailwind-merge does not know `max-h-none`, so `max-h-[80vh] max-h-none` would keep both | ||
| 'max-h': [{ 'max-h': ['none'] }] | ||
| } | ||
| } | ||
| }) | ||
|
|
||
| export function cn(...inputs: ClassArray): string { | ||
| return twMerge(clsx(inputs)) | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion (non-blocking): the copy is justified, but a comment is the weakest possible sync mechanism for 111 lines that three app callers still use from the shared package. These will drift, and the drift will be silent.
Since this one is byte-identical by construction, a tiny test that reads both files and asserts equality would turn drift into a CI failure instead of a production surprise:
That does depend on the package still being reachable from the workspace at test time, which it is today. If you would rather not couple the test to the sibling's path, the alternative is a note on FE-2196 to delete the shared copy once its three callers move — but then the comment should say "delete after the callers move" rather than "keep both in sync".