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

provenance.ts

66 lines2.1 KB

1/** Recorded sources only: never construct upstream links from provider names. */
2export function sourceHref(value: unknown): string | null {
3 if (typeof value !== 'string') return null
4 try {
5 const url = new URL(value)
6 return (url.protocol === 'https:' || url.protocol === 'http:') &&
7 !url.username &&
8 !url.password
9 ? value
10 : null
11 } catch {
12 return null
13 }
15export interface RecordedSource {
16 field: string
17 sourceUrl: string | null
18 sourceHash: string | null
19 derivation: string | null
20 path: string | null
21 checkedAt: string | null
22 trace: Record<string, unknown>
24const record = (value: unknown): value is Record<string, unknown> =>
25 !!value && typeof value === 'object' && !Array.isArray(value)
26export function recordedSources(value: unknown, prefix = ''): RecordedSource[] {
27 if (!record(value)) return []
28 if ('derivation' in value || 'sourceUrl' in value || 'sourceHash' in value)
29 return [
30 {
31 field: prefix,
32 trace: Object.fromEntries(
33 Object.entries(value).filter(
34 ([key]) =>
35 ![
36 'sourceUrl',
37 'sourceHash',
38 'derivation',
39 'path',
40 'checkedAt',
41 ].includes(key),
42 ),
43 ),
44 sourceUrl: sourceHref(value.sourceUrl),
45 sourceHash:
46 typeof value.sourceHash === 'string' ? value.sourceHash : null,
47 derivation:
48 typeof value.derivation === 'string' ? value.derivation : null,
49 path: typeof value.path === 'string' ? value.path : null,
50 checkedAt: typeof value.checkedAt === 'string' ? value.checkedAt : null,
51 },
52 ]
53 return Object.entries(value).flatMap(([field, source]) =>
54 recordedSources(source, prefix ? `${prefix}.${field}` : field),
55 )
57​
58/** A visible link represents a fact only when its recorded URL is identical. */
59export function sourceLinkAlreadyShown(
60 source: unknown,
61 shownUrl: unknown,
62): boolean {
63 if (!record(source)) return false
64 const recordedUrl = sourceHref(source.sourceUrl)
65 return recordedUrl !== null && recordedUrl === sourceHref(shownUrl)