@digitalcanopy/links 0.0.0-stage → 1.0.1

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/README.md CHANGED
@@ -1,3 +1,109 @@
1
- # Temporary Holding Version
1
+ # @digitalcanopy/links
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Universal TypeScript linking client and React hooks for the SunShade Systems ecosystem (`cozy`, `patchwork-web`, `valerie`, `sunshade-hub`).
4
+
5
+ Provides lightweight URL shortening, privacy surveillance parameter stripping, real-time 4-pillar Link Trust Score auditing, and telemetry hooks with minimal bundle footprint.
6
+
7
+ ## Features
8
+
9
+ - **2-Line URL Shortening**: Easily generate tracked shortlinks with channel-based routing (`bsky`, `linkedin`, `x`, `direct`, `qr`).
10
+ - **Privacy Parameter Sanitization**: Purges invasive surveillance parameters (`fbclid`, `gclid`, `msclkid`, `ttclid`, etc.) and dangerous schemes while retaining clean UTM and attribution parameters.
11
+ - **4-Pillar Trust Score Engine**: Evaluates Provenance (DID verification), Target Hygiene (SSL, redirect chains), Privacy Footprint, and Network Corroboration.
12
+ - **React Hooks & SafeAnchor**: `useTrackedLink` hook and `<SafeAnchor>` component that automatically renders a miniature Trust Badge next to external links.
13
+ - **Zero External Dependencies**: Beyond browser/Node `fetch` and optional `react` peer dependency.
14
+ - **Ultra-Lightweight**: Under 15KB bundle footprint.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @digitalcanopy/links
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ### 1. Shorten a URL (Core SDK)
25
+
26
+ ```typescript
27
+ import { shortenUrl } from '@digitalcanopy/links';
28
+
29
+ const link = await shortenUrl({
30
+ destination: 'https://example.com/article?fbclid=xyz&utm_source=twitter',
31
+ channel: 'bsky',
32
+ campaign: 'fall-launch',
33
+ });
34
+
35
+ console.log(link.shortUrl);
36
+ // => "https://links.sunshade.icu/xyz/bsky"
37
+ ```
38
+
39
+ ### 2. Resolve Link Trust Score
40
+
41
+ ```typescript
42
+ import { resolveTrustScore } from '@digitalcanopy/links';
43
+
44
+ const report = await resolveTrustScore('https://example.com/target');
45
+
46
+ console.log(`Trust Score: ${report.score}/100 (${report.status})`);
47
+ console.log(report.pillars);
48
+ // => { provenance: 35, hygiene: 25, privacy: 20, networkDecay: 20 }
49
+ ```
50
+
51
+ ### 3. Sanitize URL directly
52
+
53
+ ```typescript
54
+ import { sanitizeUrl } from '@digitalcanopy/links';
55
+
56
+ const cleanUrl = sanitizeUrl('https://site.com/?fbclid=123&utm_source=newsletter');
57
+ // => "https://site.com/?utm_source=newsletter"
58
+ ```
59
+
60
+ ### 4. React Integration
61
+
62
+ ```tsx
63
+ import { SafeAnchor, useTrackedLink } from '@digitalcanopy/links/react';
64
+
65
+ // Component that automatically shortens and renders a miniature Trust Badge
66
+ export function CommunityLink() {
67
+ return (
68
+ <SafeAnchor
69
+ href="https://sunshade.icu/manifesto"
70
+ telemetry={true}
71
+ channel="bsky"
72
+ trustScore={98}
73
+ >
74
+ Read the SunShade Manifesto
75
+ </SafeAnchor>
76
+ );
77
+ }
78
+
79
+ // Low-level hook for custom link rendering
80
+ export function CustomTrackedLink({ url }: { url: string }) {
81
+ const { href, isLoading, isShortened } = useTrackedLink(url, {
82
+ channel: 'direct',
83
+ enabled: true,
84
+ });
85
+
86
+ return (
87
+ <a href={href}>
88
+ {isLoading ? 'Preparing link...' : 'Open Link'}
89
+ </a>
90
+ );
91
+ }
92
+ ```
93
+
94
+ ## Client Configuration
95
+
96
+ ```typescript
97
+ import { LinksClient } from '@digitalcanopy/links';
98
+
99
+ const client = new LinksClient({
100
+ baseUrl: 'https://links.sunshade.icu',
101
+ apiKey: process.env.SUNSHADE_API_KEY,
102
+ tenantId: 'pym-energy',
103
+ enableFallback: true, // Gracefully falls back to raw sanitized URL if network is unreachable
104
+ });
105
+ ```
106
+
107
+ ## License
108
+
109
+ MIT © SunShade Systems
@@ -0,0 +1 @@
1
+ var T=new Set(["fbclid","gclid","msclkid","ttclid","twclid","_hsenc","mc_eid","sc_campaign","igshid","dclid","gad_source","gbraid","wbraid","yclid","_openstat","s_kwcid"]),m=/^(javascript|vbscript|data):/i,_=/[\u0000-\u0020\u007f]+/g,S=/[\u0000-\u001f\u007f]+/g;function y(n){let t=n.replace(_,"");if(m.test(t))return!0;try{let i=new URL(n,"https://sanitizer.invalid");return m.test(i.protocol)}catch{return!1}}function f(n){if(!n||typeof n!="string")return!1;let t=n.indexOf("?");if(t===-1)return!1;let i=n.indexOf("#",t),a=i!==-1?n.slice(t+1,i):n.slice(t+1),r=new URLSearchParams(a);for(let l of r.keys())if(T.has(l.toLowerCase()))return!0;return!1}function b(n){if(!n||typeof n!="string")return"";let t=n.replace(S,"").trim();if(!t)return"";if(y(n)||y(t))return"about:blank";let i=t.indexOf("#"),a=i!==-1?t.slice(i):"",r=i!==-1?t.slice(0,i):t,l=r.indexOf("?"),u=l!==-1?r.slice(0,l):r,o=l!==-1?r.slice(l+1):"";if(!o)return`${u}${a}`;try{let s=new URLSearchParams(o),c=[];for(let h of s.keys())T.has(h.toLowerCase())&&c.push(h);for(let h of c)s.delete(h);if(c.length===0)return`${u}?${o}${a}`;let e=s.toString(),p=e?`?${e}`:"";return`${u}${p}${a}`}catch{return t}}var w="https://links.sunshade.icu",C=5e3,d=class{constructor(t={}){let i=(t.baseUrl||w).replace(/\/+$/,"");if(this.apiKey=t.apiKey,this.apiKey){let a=null;try{a=new URL(i)}catch{a=null}if(a&&a.protocol==="http:"){let r=a.hostname.toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"))throw new Error("Insecure transport: apiKey cannot be transmitted over plaintext HTTP (use HTTPS or localhost).")}}this.baseUrl=i,this.tenantId=t.tenantId,this.customFetch=t.fetch||globalThis.fetch.bind(globalThis),this.enableFallback=t.enableFallback??!0,this.timeoutMs=t.timeoutMs??C}async shortenUrl(t){if(!t?.destination)throw new Error("Destination URL is required");let i=this.sanitizeUrl(t.destination),a=t.channel||"direct",r=t.tenantId||this.tenantId,l={destination:i,channel:a,campaign:t.campaign,tenant_id:r,slug:t.slug,metadata:t.metadata},u={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(u.Authorization=`Bearer ${this.apiKey}`),r&&(u["x-tenant-id"]=r);let o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs);try{let c=await this.customFetch(`${this.baseUrl}/api/v1/links`,{method:"POST",headers:u,body:JSON.stringify(l),signal:o.signal});if(!c.ok)throw new Error(`Links API error: ${c.status} ${c.statusText}`);let e=await c.json();return{id:e.id||`lnk_${Math.random().toString(36).substring(2,9)}`,slug:e.slug||t.slug||"",shortUrl:e.short_url||e.shortUrl||`${this.baseUrl}/${e.slug||t.slug||""}/${a}`,destinationUrl:e.destination_url||e.destinationUrl||i,channel:e.channel||a,campaign:e.campaign||t.campaign,tenantId:e.tenant_id||e.tenantId||r,trustScore:e.trust_score??e.trustScore,createdAt:e.created_at||e.createdAt||new Date().toISOString()}}catch(c){if(!this.enableFallback)throw c;return{id:`fallback-${Date.now()}-${Math.random().toString(36).substring(2,7)}`,slug:t.slug||"",shortUrl:i,destinationUrl:i,channel:a,campaign:t.campaign,tenantId:r,trustScore:void 0,createdAt:new Date().toISOString()}}finally{clearTimeout(s)}}async resolveTrustScore(t){if(!t)throw new Error("URL or slug is required");let a=t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")?`${this.baseUrl}/api/v1/trust?url=${encodeURIComponent(t)}`:`${this.baseUrl}/api/v1/trust/${encodeURIComponent(t)}`,r={Accept:"application/json"};this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`),this.tenantId&&(r["x-tenant-id"]=this.tenantId);let l=new AbortController,u=setTimeout(()=>l.abort(),this.timeoutMs);try{let o=await this.customFetch(a,{method:"GET",headers:r,signal:l.signal});if(!o.ok)throw new Error(`Trust API error: ${o.status} ${o.statusText}`);let s=await o.json(),c=s.score??s.trust_score;if(typeof c!="number"||isNaN(c))throw new Error("Invalid audit response: missing or unparseable trust score");let e=Math.max(0,Math.min(100,c)),p=e>=85?"trusted":e>=60?"warning":"danger",h=s.tier||(e>=85?"trusted":e>=60?"neutral":"danger");return{url:s.url||t,slug:s.slug,score:e,tier:h,status:p,flags:s.flags||{verified_did:!!s.verified_did,sanitized_trackers:!f(t),redirect_count:s.redirect_count??0,reputation_tier:h,is_flagged:e<60,ssl_valid:t.startsWith("https://")||t.startsWith("//")},pillars:s.pillars||{provenance:Math.round(e*.35),hygiene:Math.round(e*.25),privacy:Math.round(e*.2),networkDecay:Math.round(e*.2)},lastHygieneCheck:s.last_hygiene_check||s.lastHygieneCheck||new Date().toISOString(),did:s.did,recommendation:s.recommendation}}catch(o){if(!this.enableFallback)throw o;return this.computeLocalTrustScore(t)}finally{clearTimeout(u)}}sanitizeUrl(t){return b(t)}computeLocalTrustScore(t){let i=t.startsWith("https://")||t.startsWith("//"),a=f(t),r=10,l=i?25:10,u=a?5:20,o=20,s=r+l+u+o,c=s>=85?"trusted":s>=60?"warning":"danger",e=s>=85?"trusted":s>=60?"neutral":"danger",p={verified_did:!1,sanitized_trackers:!a,redirect_count:0,reputation_tier:e,is_flagged:s<60,ssl_valid:i};return{url:t,score:s,tier:e,status:c,flags:p,pillars:{provenance:r,hygiene:l,privacy:u,networkDecay:o},lastHygieneCheck:new Date().toISOString(),recommendation:s<60?"Destination has potential security or tracking concerns.":"Destination is reachable and verified against standard security baselines."}}},g=Symbol.for("@digitalcanopy/links/defaultClient");function k(){let n=globalThis;return n[g]||(n[g]=new d),n[g]}function v(n){let t=globalThis;t[g]=n}async function I(n,t){return(t?new d(t):k()).shortenUrl(n)}async function R(n,t){return(t?new d(t):k()).resolveTrustScore(n)}var $=d;export{T as a,f as b,b as c,d,k as e,v as f,I as g,R as h,$ as i};
@@ -0,0 +1,156 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * @digitalcanopy/links Types & Interfaces
5
+ */
6
+ type ReputationTier = 'canonical' | 'trusted' | 'neutral' | 'warning' | 'danger' | 'unverified';
7
+ type TrustTier = 'trusted' | 'warning' | 'danger';
8
+ interface TrustFlags {
9
+ verified_did: boolean;
10
+ sanitized_trackers: boolean;
11
+ redirect_count: number;
12
+ reputation_tier: ReputationTier;
13
+ is_flagged?: boolean;
14
+ ssl_valid?: boolean;
15
+ }
16
+ interface TrustPillars {
17
+ /** Cryptographic provenance and DID verification score (0–35) */
18
+ provenance: number;
19
+ /** Destination hygiene, SSL validity, and redirect hop score (0–25) */
20
+ hygiene: number;
21
+ /** Privacy footprint and surveillance tracker stripping score (0–20) */
22
+ privacy: number;
23
+ /** Network corroboration and temporal decay score (0–20) */
24
+ networkDecay: number;
25
+ }
26
+ interface TrustScoreReport {
27
+ url: string;
28
+ slug?: string;
29
+ score: number;
30
+ tier: ReputationTier;
31
+ status: TrustTier;
32
+ flags: TrustFlags;
33
+ pillars: TrustPillars;
34
+ lastHygieneCheck?: string;
35
+ did?: string;
36
+ recommendation?: string;
37
+ }
38
+ interface ShortenUrlOptions {
39
+ destination: string;
40
+ channel?: string;
41
+ campaign?: string;
42
+ tenantId?: string;
43
+ slug?: string;
44
+ metadata?: Record<string, unknown>;
45
+ }
46
+ interface ShortLinkResult {
47
+ id: string;
48
+ slug: string;
49
+ shortUrl: string;
50
+ destinationUrl: string;
51
+ channel: string;
52
+ campaign?: string;
53
+ tenantId?: string;
54
+ trustScore?: number;
55
+ createdAt: string;
56
+ }
57
+ interface ClientConfig {
58
+ baseUrl?: string;
59
+ apiKey?: string;
60
+ tenantId?: string;
61
+ fetch?: typeof fetch;
62
+ enableFallback?: boolean;
63
+ timeoutMs?: number;
64
+ }
65
+
66
+ /**
67
+ * SunShade Universal Links Client SDK
68
+ */
69
+
70
+ declare class LinksClient {
71
+ private baseUrl;
72
+ private apiKey?;
73
+ private tenantId?;
74
+ private customFetch;
75
+ private enableFallback;
76
+ private timeoutMs;
77
+ constructor(config?: ClientConfig);
78
+ /**
79
+ * Shorten a destination URL with channel routing and privacy sanitization.
80
+ */
81
+ shortenUrl(options: ShortenUrlOptions): Promise<ShortLinkResult>;
82
+ /**
83
+ * Resolve the Link Trust Score and 4-pillar audit report.
84
+ */
85
+ resolveTrustScore(urlOrSlug: string): Promise<TrustScoreReport>;
86
+ /**
87
+ * Sanitizes a URL by stripping surveillance and ad-tech tracking parameters.
88
+ */
89
+ sanitizeUrl(rawUrl: string): string;
90
+ /**
91
+ * Deterministic client-side evaluation fallback when the remote trust auditor is unreachable.
92
+ */
93
+ private computeLocalTrustScore;
94
+ }
95
+ declare function getDefaultClient(): LinksClient;
96
+ declare function setDefaultClient(client: LinksClient): void;
97
+ /**
98
+ * Universal functional export to shorten a URL.
99
+ */
100
+ declare function shortenUrl(options: ShortenUrlOptions, config?: ClientConfig): Promise<ShortLinkResult>;
101
+ /**
102
+ * Universal functional export to resolve a Link Trust Score.
103
+ */
104
+ declare function resolveTrustScore(urlOrSlug: string, config?: ClientConfig): Promise<TrustScoreReport>;
105
+ /**
106
+ * Alias for ecosystem naming consistency.
107
+ */
108
+ declare const SunshadeLinksClient: typeof LinksClient;
109
+
110
+ interface TrustBadgeProps {
111
+ score?: number;
112
+ tier?: ReputationTier;
113
+ status?: TrustTier;
114
+ showLabel?: boolean;
115
+ size?: 'sm' | 'md' | 'lg';
116
+ className?: string;
117
+ onClick?: (e: React.MouseEvent) => void;
118
+ 'data-testid'?: string;
119
+ }
120
+ declare const TrustBadge: React.FC<TrustBadgeProps>;
121
+
122
+ interface SafeAnchorProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
123
+ href: string;
124
+ children?: React.ReactNode;
125
+ showBadge?: boolean;
126
+ telemetry?: boolean;
127
+ trustScore?: number;
128
+ resolveTrust?: boolean;
129
+ badgeSize?: 'sm' | 'md' | 'lg';
130
+ channel?: string;
131
+ campaign?: string;
132
+ tenantId?: string;
133
+ client?: LinksClient;
134
+ }
135
+ declare const SafeAnchor: React.FC<SafeAnchorProps>;
136
+
137
+ interface UseTrackedLinkOptions {
138
+ channel?: string;
139
+ campaign?: string;
140
+ tenantId?: string;
141
+ enabled?: boolean;
142
+ client?: LinksClient;
143
+ autoResolveTrust?: boolean;
144
+ }
145
+ interface UseTrackedLinkResult {
146
+ href: string;
147
+ isLoading: boolean;
148
+ isShortened: boolean;
149
+ trustScore?: number;
150
+ trustReport?: TrustScoreReport;
151
+ error: Error | null;
152
+ refetch: () => Promise<void>;
153
+ }
154
+ declare function useTrackedLink(destinationUrl: string, options?: UseTrackedLinkOptions): UseTrackedLinkResult;
155
+
156
+ export { type ClientConfig as C, LinksClient as L, type ReputationTier as R, type SafeAnchorProps as S, type TrustBadgeProps as T, type UseTrackedLinkOptions as U, type ShortLinkResult as a, type ShortenUrlOptions as b, SunshadeLinksClient as c, type TrustFlags as d, type TrustPillars as e, type TrustScoreReport as f, type TrustTier as g, type UseTrackedLinkResult as h, getDefaultClient as i, shortenUrl as j, SafeAnchor as k, TrustBadge as l, resolveTrustScore as r, setDefaultClient as s, useTrackedLink as u };
@@ -0,0 +1,156 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * @digitalcanopy/links Types & Interfaces
5
+ */
6
+ type ReputationTier = 'canonical' | 'trusted' | 'neutral' | 'warning' | 'danger' | 'unverified';
7
+ type TrustTier = 'trusted' | 'warning' | 'danger';
8
+ interface TrustFlags {
9
+ verified_did: boolean;
10
+ sanitized_trackers: boolean;
11
+ redirect_count: number;
12
+ reputation_tier: ReputationTier;
13
+ is_flagged?: boolean;
14
+ ssl_valid?: boolean;
15
+ }
16
+ interface TrustPillars {
17
+ /** Cryptographic provenance and DID verification score (0–35) */
18
+ provenance: number;
19
+ /** Destination hygiene, SSL validity, and redirect hop score (0–25) */
20
+ hygiene: number;
21
+ /** Privacy footprint and surveillance tracker stripping score (0–20) */
22
+ privacy: number;
23
+ /** Network corroboration and temporal decay score (0–20) */
24
+ networkDecay: number;
25
+ }
26
+ interface TrustScoreReport {
27
+ url: string;
28
+ slug?: string;
29
+ score: number;
30
+ tier: ReputationTier;
31
+ status: TrustTier;
32
+ flags: TrustFlags;
33
+ pillars: TrustPillars;
34
+ lastHygieneCheck?: string;
35
+ did?: string;
36
+ recommendation?: string;
37
+ }
38
+ interface ShortenUrlOptions {
39
+ destination: string;
40
+ channel?: string;
41
+ campaign?: string;
42
+ tenantId?: string;
43
+ slug?: string;
44
+ metadata?: Record<string, unknown>;
45
+ }
46
+ interface ShortLinkResult {
47
+ id: string;
48
+ slug: string;
49
+ shortUrl: string;
50
+ destinationUrl: string;
51
+ channel: string;
52
+ campaign?: string;
53
+ tenantId?: string;
54
+ trustScore?: number;
55
+ createdAt: string;
56
+ }
57
+ interface ClientConfig {
58
+ baseUrl?: string;
59
+ apiKey?: string;
60
+ tenantId?: string;
61
+ fetch?: typeof fetch;
62
+ enableFallback?: boolean;
63
+ timeoutMs?: number;
64
+ }
65
+
66
+ /**
67
+ * SunShade Universal Links Client SDK
68
+ */
69
+
70
+ declare class LinksClient {
71
+ private baseUrl;
72
+ private apiKey?;
73
+ private tenantId?;
74
+ private customFetch;
75
+ private enableFallback;
76
+ private timeoutMs;
77
+ constructor(config?: ClientConfig);
78
+ /**
79
+ * Shorten a destination URL with channel routing and privacy sanitization.
80
+ */
81
+ shortenUrl(options: ShortenUrlOptions): Promise<ShortLinkResult>;
82
+ /**
83
+ * Resolve the Link Trust Score and 4-pillar audit report.
84
+ */
85
+ resolveTrustScore(urlOrSlug: string): Promise<TrustScoreReport>;
86
+ /**
87
+ * Sanitizes a URL by stripping surveillance and ad-tech tracking parameters.
88
+ */
89
+ sanitizeUrl(rawUrl: string): string;
90
+ /**
91
+ * Deterministic client-side evaluation fallback when the remote trust auditor is unreachable.
92
+ */
93
+ private computeLocalTrustScore;
94
+ }
95
+ declare function getDefaultClient(): LinksClient;
96
+ declare function setDefaultClient(client: LinksClient): void;
97
+ /**
98
+ * Universal functional export to shorten a URL.
99
+ */
100
+ declare function shortenUrl(options: ShortenUrlOptions, config?: ClientConfig): Promise<ShortLinkResult>;
101
+ /**
102
+ * Universal functional export to resolve a Link Trust Score.
103
+ */
104
+ declare function resolveTrustScore(urlOrSlug: string, config?: ClientConfig): Promise<TrustScoreReport>;
105
+ /**
106
+ * Alias for ecosystem naming consistency.
107
+ */
108
+ declare const SunshadeLinksClient: typeof LinksClient;
109
+
110
+ interface TrustBadgeProps {
111
+ score?: number;
112
+ tier?: ReputationTier;
113
+ status?: TrustTier;
114
+ showLabel?: boolean;
115
+ size?: 'sm' | 'md' | 'lg';
116
+ className?: string;
117
+ onClick?: (e: React.MouseEvent) => void;
118
+ 'data-testid'?: string;
119
+ }
120
+ declare const TrustBadge: React.FC<TrustBadgeProps>;
121
+
122
+ interface SafeAnchorProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
123
+ href: string;
124
+ children?: React.ReactNode;
125
+ showBadge?: boolean;
126
+ telemetry?: boolean;
127
+ trustScore?: number;
128
+ resolveTrust?: boolean;
129
+ badgeSize?: 'sm' | 'md' | 'lg';
130
+ channel?: string;
131
+ campaign?: string;
132
+ tenantId?: string;
133
+ client?: LinksClient;
134
+ }
135
+ declare const SafeAnchor: React.FC<SafeAnchorProps>;
136
+
137
+ interface UseTrackedLinkOptions {
138
+ channel?: string;
139
+ campaign?: string;
140
+ tenantId?: string;
141
+ enabled?: boolean;
142
+ client?: LinksClient;
143
+ autoResolveTrust?: boolean;
144
+ }
145
+ interface UseTrackedLinkResult {
146
+ href: string;
147
+ isLoading: boolean;
148
+ isShortened: boolean;
149
+ trustScore?: number;
150
+ trustReport?: TrustScoreReport;
151
+ error: Error | null;
152
+ refetch: () => Promise<void>;
153
+ }
154
+ declare function useTrackedLink(destinationUrl: string, options?: UseTrackedLinkOptions): UseTrackedLinkResult;
155
+
156
+ export { type ClientConfig as C, LinksClient as L, type ReputationTier as R, type SafeAnchorProps as S, type TrustBadgeProps as T, type UseTrackedLinkOptions as U, type ShortLinkResult as a, type ShortenUrlOptions as b, SunshadeLinksClient as c, type TrustFlags as d, type TrustPillars as e, type TrustScoreReport as f, type TrustTier as g, type UseTrackedLinkResult as h, getDefaultClient as i, shortenUrl as j, SafeAnchor as k, TrustBadge as l, resolveTrustScore as r, setDefaultClient as s, useTrackedLink as u };
@@ -0,0 +1,20 @@
1
+ export { C as ClientConfig, L as LinksClient, R as ReputationTier, S as SafeAnchorProps, a as ShortLinkResult, b as ShortenUrlOptions, c as SunshadeLinksClient, T as TrustBadgeProps, d as TrustFlags, e as TrustPillars, f as TrustScoreReport, g as TrustTier, U as UseTrackedLinkOptions, h as UseTrackedLinkResult, i as getDefaultClient, r as resolveTrustScore, s as setDefaultClient, j as shortenUrl } from './index-CsMt9a_s.mjs';
2
+ import 'react';
3
+
4
+ /**
5
+ * Privacy Sanitizer for SunShade Links
6
+ * Strips invasive surveillance and ad-tech tracking parameters while
7
+ * preserving clean attribution parameters (UTM, ch, ref) and query payload.
8
+ */
9
+ declare const INVASIVE_TRACKING_PARAMS: Set<string>;
10
+ /**
11
+ * Checks whether a URL contains invasive surveillance tokens.
12
+ */
13
+ declare function hasSurveillanceTokens(rawUrl: string): boolean;
14
+ /**
15
+ * Strips known surveillance tokens and returns a sanitized clean URL.
16
+ * Neutralizes dangerous executable URL schemes (e.g. javascript:).
17
+ */
18
+ declare function sanitizeUrl(rawUrl: string): string;
19
+
20
+ export { INVASIVE_TRACKING_PARAMS, hasSurveillanceTokens, sanitizeUrl };
@@ -0,0 +1,20 @@
1
+ export { C as ClientConfig, L as LinksClient, R as ReputationTier, S as SafeAnchorProps, a as ShortLinkResult, b as ShortenUrlOptions, c as SunshadeLinksClient, T as TrustBadgeProps, d as TrustFlags, e as TrustPillars, f as TrustScoreReport, g as TrustTier, U as UseTrackedLinkOptions, h as UseTrackedLinkResult, i as getDefaultClient, r as resolveTrustScore, s as setDefaultClient, j as shortenUrl } from './index-CsMt9a_s.js';
2
+ import 'react';
3
+
4
+ /**
5
+ * Privacy Sanitizer for SunShade Links
6
+ * Strips invasive surveillance and ad-tech tracking parameters while
7
+ * preserving clean attribution parameters (UTM, ch, ref) and query payload.
8
+ */
9
+ declare const INVASIVE_TRACKING_PARAMS: Set<string>;
10
+ /**
11
+ * Checks whether a URL contains invasive surveillance tokens.
12
+ */
13
+ declare function hasSurveillanceTokens(rawUrl: string): boolean;
14
+ /**
15
+ * Strips known surveillance tokens and returns a sanitized clean URL.
16
+ * Neutralizes dangerous executable URL schemes (e.g. javascript:).
17
+ */
18
+ declare function sanitizeUrl(rawUrl: string): string;
19
+
20
+ export { INVASIVE_TRACKING_PARAMS, hasSurveillanceTokens, sanitizeUrl };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var b=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var r in t)b(e,r,{get:t[r],enumerable:!0})},A=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of R(t))!v.call(e,n)&&n!==r&&b(e,n,{get:()=>t[n],enumerable:!(a=U(t,n))||a.enumerable});return e};var x=e=>A(b({},"__esModule",{value:!0}),e);var M={};I(M,{INVASIVE_TRACKING_PARAMS:()=>g,LinksClient:()=>d,SunshadeLinksClient:()=>w,getDefaultClient:()=>y,hasSurveillanceTokens:()=>f,resolveTrustScore:()=>L,sanitizeUrl:()=>m,setDefaultClient:()=>_,shortenUrl:()=>C});module.exports=x(M);var g=new Set(["fbclid","gclid","msclkid","ttclid","twclid","_hsenc","mc_eid","sc_campaign","igshid","dclid","gad_source","gbraid","wbraid","yclid","_openstat","s_kwcid"]),k=/^(javascript|vbscript|data):/i,$=/[\u0000-\u0020\u007f]+/g,P=/[\u0000-\u001f\u007f]+/g;function S(e){let t=e.replace($,"");if(k.test(t))return!0;try{let r=new URL(e,"https://sanitizer.invalid");return k.test(r.protocol)}catch{return!1}}function f(e){if(!e||typeof e!="string")return!1;let t=e.indexOf("?");if(t===-1)return!1;let r=e.indexOf("#",t),a=r!==-1?e.slice(t+1,r):e.slice(t+1),n=new URLSearchParams(a);for(let l of n.keys())if(g.has(l.toLowerCase()))return!0;return!1}function m(e){if(!e||typeof e!="string")return"";let t=e.replace(P,"").trim();if(!t)return"";if(S(e)||S(t))return"about:blank";let r=t.indexOf("#"),a=r!==-1?t.slice(r):"",n=r!==-1?t.slice(0,r):t,l=n.indexOf("?"),u=l!==-1?n.slice(0,l):n,o=l!==-1?n.slice(l+1):"";if(!o)return`${u}${a}`;try{let i=new URLSearchParams(o),c=[];for(let h of i.keys())g.has(h.toLowerCase())&&c.push(h);for(let h of c)i.delete(h);if(c.length===0)return`${u}?${o}${a}`;let s=i.toString(),p=s?`?${s}`:"";return`${u}${p}${a}`}catch{return t}}var D="https://links.sunshade.icu",E=5e3,d=class{constructor(t={}){let r=(t.baseUrl||D).replace(/\/+$/,"");if(this.apiKey=t.apiKey,this.apiKey){let a=null;try{a=new URL(r)}catch{a=null}if(a&&a.protocol==="http:"){let n=a.hostname.toLowerCase();if(!(n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"))throw new Error("Insecure transport: apiKey cannot be transmitted over plaintext HTTP (use HTTPS or localhost).")}}this.baseUrl=r,this.tenantId=t.tenantId,this.customFetch=t.fetch||globalThis.fetch.bind(globalThis),this.enableFallback=t.enableFallback??!0,this.timeoutMs=t.timeoutMs??E}async shortenUrl(t){if(!t?.destination)throw new Error("Destination URL is required");let r=this.sanitizeUrl(t.destination),a=t.channel||"direct",n=t.tenantId||this.tenantId,l={destination:r,channel:a,campaign:t.campaign,tenant_id:n,slug:t.slug,metadata:t.metadata},u={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(u.Authorization=`Bearer ${this.apiKey}`),n&&(u["x-tenant-id"]=n);let o=new AbortController,i=setTimeout(()=>o.abort(),this.timeoutMs);try{let c=await this.customFetch(`${this.baseUrl}/api/v1/links`,{method:"POST",headers:u,body:JSON.stringify(l),signal:o.signal});if(!c.ok)throw new Error(`Links API error: ${c.status} ${c.statusText}`);let s=await c.json();return{id:s.id||`lnk_${Math.random().toString(36).substring(2,9)}`,slug:s.slug||t.slug||"",shortUrl:s.short_url||s.shortUrl||`${this.baseUrl}/${s.slug||t.slug||""}/${a}`,destinationUrl:s.destination_url||s.destinationUrl||r,channel:s.channel||a,campaign:s.campaign||t.campaign,tenantId:s.tenant_id||s.tenantId||n,trustScore:s.trust_score??s.trustScore,createdAt:s.created_at||s.createdAt||new Date().toISOString()}}catch(c){if(!this.enableFallback)throw c;return{id:`fallback-${Date.now()}-${Math.random().toString(36).substring(2,7)}`,slug:t.slug||"",shortUrl:r,destinationUrl:r,channel:a,campaign:t.campaign,tenantId:n,trustScore:void 0,createdAt:new Date().toISOString()}}finally{clearTimeout(i)}}async resolveTrustScore(t){if(!t)throw new Error("URL or slug is required");let a=t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")?`${this.baseUrl}/api/v1/trust?url=${encodeURIComponent(t)}`:`${this.baseUrl}/api/v1/trust/${encodeURIComponent(t)}`,n={Accept:"application/json"};this.apiKey&&(n.Authorization=`Bearer ${this.apiKey}`),this.tenantId&&(n["x-tenant-id"]=this.tenantId);let l=new AbortController,u=setTimeout(()=>l.abort(),this.timeoutMs);try{let o=await this.customFetch(a,{method:"GET",headers:n,signal:l.signal});if(!o.ok)throw new Error(`Trust API error: ${o.status} ${o.statusText}`);let i=await o.json(),c=i.score??i.trust_score;if(typeof c!="number"||isNaN(c))throw new Error("Invalid audit response: missing or unparseable trust score");let s=Math.max(0,Math.min(100,c)),p=s>=85?"trusted":s>=60?"warning":"danger",h=i.tier||(s>=85?"trusted":s>=60?"neutral":"danger");return{url:i.url||t,slug:i.slug,score:s,tier:h,status:p,flags:i.flags||{verified_did:!!i.verified_did,sanitized_trackers:!f(t),redirect_count:i.redirect_count??0,reputation_tier:h,is_flagged:s<60,ssl_valid:t.startsWith("https://")||t.startsWith("//")},pillars:i.pillars||{provenance:Math.round(s*.35),hygiene:Math.round(s*.25),privacy:Math.round(s*.2),networkDecay:Math.round(s*.2)},lastHygieneCheck:i.last_hygiene_check||i.lastHygieneCheck||new Date().toISOString(),did:i.did,recommendation:i.recommendation}}catch(o){if(!this.enableFallback)throw o;return this.computeLocalTrustScore(t)}finally{clearTimeout(u)}}sanitizeUrl(t){return m(t)}computeLocalTrustScore(t){let r=t.startsWith("https://")||t.startsWith("//"),a=f(t),n=10,l=r?25:10,u=a?5:20,o=20,i=n+l+u+o,c=i>=85?"trusted":i>=60?"warning":"danger",s=i>=85?"trusted":i>=60?"neutral":"danger",p={verified_did:!1,sanitized_trackers:!a,redirect_count:0,reputation_tier:s,is_flagged:i<60,ssl_valid:r};return{url:t,score:i,tier:s,status:c,flags:p,pillars:{provenance:n,hygiene:l,privacy:u,networkDecay:o},lastHygieneCheck:new Date().toISOString(),recommendation:i<60?"Destination has potential security or tracking concerns.":"Destination is reachable and verified against standard security baselines."}}},T=Symbol.for("@digitalcanopy/links/defaultClient");function y(){let e=globalThis;return e[T]||(e[T]=new d),e[T]}function _(e){let t=globalThis;t[T]=e}async function C(e,t){return(t?new d(t):y()).shortenUrl(e)}async function L(e,t){return(t?new d(t):y()).resolveTrustScore(e)}var w=d;0&&(module.exports={INVASIVE_TRACKING_PARAMS,LinksClient,SunshadeLinksClient,getDefaultClient,hasSurveillanceTokens,resolveTrustScore,sanitizeUrl,setDefaultClient,shortenUrl});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{a as e,b as r,c as t,d as s,e as o,f as n,g as i,h as l,i as a}from"./chunk-LFYYBCTE.mjs";export{e as INVASIVE_TRACKING_PARAMS,s as LinksClient,a as SunshadeLinksClient,o as getDefaultClient,r as hasSurveillanceTokens,l as resolveTrustScore,t as sanitizeUrl,n as setDefaultClient,i as shortenUrl};
@@ -0,0 +1,2 @@
1
+ export { k as SafeAnchor, S as SafeAnchorProps, l as TrustBadge, T as TrustBadgeProps, U as UseTrackedLinkOptions, h as UseTrackedLinkResult, u as useTrackedLink } from '../index-CsMt9a_s.mjs';
2
+ import 'react';
@@ -0,0 +1,2 @@
1
+ export { k as SafeAnchor, S as SafeAnchorProps, l as TrustBadge, T as TrustBadgeProps, U as UseTrackedLinkOptions, h as UseTrackedLinkResult, u as useTrackedLink } from '../index-CsMt9a_s.js';
2
+ import 'react';
@@ -0,0 +1 @@
1
+ "use strict";var B=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(e,t)=>{for(var o in t)B(e,o,{get:t[o],enumerable:!0})},tt=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Q(t))!X.call(e,r)&&r!==o&&B(e,r,{get:()=>t[r],enumerable:!(i=J(t,r))||i.enumerable});return e};var et=e=>tt(B({},"__esModule",{value:!0}),e);var it={};Z(it,{SafeAnchor:()=>j,TrustBadge:()=>_,useTrackedLink:()=>I});module.exports=et(it);var m=require("react/jsx-runtime"),_=({score:e,tier:t,status:o,showLabel:i=!1,size:r="sm",className:l="",onClick:u,"data-testid":c="trust-badge"})=>{let n=typeof e=="number"&&!isNaN(e),a=o||(n?e>=85?"trusted":e>=60?"warning":"danger":"unknown"),d={trusted:{bg:"rgba(16, 185, 129, 0.1)",border:"rgba(16, 185, 129, 0.3)",text:"#10B981"},warning:{bg:"rgba(245, 158, 11, 0.1)",border:"rgba(245, 158, 11, 0.3)",text:"#F59E0B"},danger:{bg:"rgba(239, 68, 68, 0.1)",border:"rgba(239, 68, 68, 0.3)",text:"#EF4444"},unknown:{bg:"rgba(100, 116, 139, 0.1)",border:"rgba(100, 116, 139, 0.3)",text:"#64748B"}}[a],h={sm:{icon:12,fontSize:"0.7rem",padding:"1px 5px",gap:"3px"},md:{icon:14,fontSize:"0.8rem",padding:"2px 8px",gap:"4px"},lg:{icon:18,fontSize:"0.9rem",padding:"4px 10px",gap:"6px"}}[r],S=n?`${e}/100`:t||"Unverified";return(0,m.jsxs)("span",{"data-testid":c,"data-status":a,role:"img","aria-label":`Trust Score: ${n?`${e} out of 100`:"Unverified"}`,onClick:u,style:{display:"inline-flex",alignItems:"center",gap:h.gap,padding:h.padding,fontSize:h.fontSize,lineHeight:1,borderRadius:"9999px",backgroundColor:d.bg,border:`1px solid ${d.border}`,color:d.text,fontWeight:600,verticalAlign:"middle",cursor:u?"pointer":"default",userSelect:"none"},className:l,children:[(0,m.jsxs)("svg",{width:h.icon,height:h.icon,viewBox:"0 0 24 24",fill:"none",stroke:d.text,strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,m.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"}),a==="trusted"&&(0,m.jsx)("path",{d:"m9 12 2 2 4-4"}),a==="warning"&&(0,m.jsx)("path",{d:"M12 8v4M12 16h.01"}),a==="danger"&&(0,m.jsx)("path",{d:"m15 9-6 6M9 9l6 6"})]}),i&&(0,m.jsx)("span",{children:S}),!i&&n&&(0,m.jsx)("span",{children:e})]})};var K=new Set(["fbclid","gclid","msclkid","ttclid","twclid","_hsenc","mc_eid","sc_campaign","igshid","dclid","gad_source","gbraid","wbraid","yclid","_openstat","s_kwcid"]),W=/^(javascript|vbscript|data):/i,rt=/[\u0000-\u0020\u007f]+/g,nt=/[\u0000-\u001f\u007f]+/g;function O(e){let t=e.replace(rt,"");if(W.test(t))return!0;try{let o=new URL(e,"https://sanitizer.invalid");return W.test(o.protocol)}catch{return!1}}function F(e){if(!e||typeof e!="string")return!1;let t=e.indexOf("?");if(t===-1)return!1;let o=e.indexOf("#",t),i=o!==-1?e.slice(t+1,o):e.slice(t+1),r=new URLSearchParams(i);for(let l of r.keys())if(K.has(l.toLowerCase()))return!0;return!1}function k(e){if(!e||typeof e!="string")return"";let t=e.replace(nt,"").trim();if(!t)return"";if(O(e)||O(t))return"about:blank";let o=t.indexOf("#"),i=o!==-1?t.slice(o):"",r=o!==-1?t.slice(0,o):t,l=r.indexOf("?"),u=l!==-1?r.slice(0,l):r,c=l!==-1?r.slice(l+1):"";if(!c)return`${u}${i}`;try{let n=new URLSearchParams(c),a=[];for(let f of n.keys())K.has(f.toLowerCase())&&a.push(f);for(let f of a)n.delete(f);if(a.length===0)return`${u}?${c}${i}`;let s=n.toString(),d=s?`?${s}`:"";return`${u}${d}${i}`}catch{return t}}var p=require("react");var st="https://links.sunshade.icu",ot=5e3,H=class{constructor(t={}){let o=(t.baseUrl||st).replace(/\/+$/,"");if(this.apiKey=t.apiKey,this.apiKey){let i=null;try{i=new URL(o)}catch{i=null}if(i&&i.protocol==="http:"){let r=i.hostname.toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"))throw new Error("Insecure transport: apiKey cannot be transmitted over plaintext HTTP (use HTTPS or localhost).")}}this.baseUrl=o,this.tenantId=t.tenantId,this.customFetch=t.fetch||globalThis.fetch.bind(globalThis),this.enableFallback=t.enableFallback??!0,this.timeoutMs=t.timeoutMs??ot}async shortenUrl(t){if(!t?.destination)throw new Error("Destination URL is required");let o=this.sanitizeUrl(t.destination),i=t.channel||"direct",r=t.tenantId||this.tenantId,l={destination:o,channel:i,campaign:t.campaign,tenant_id:r,slug:t.slug,metadata:t.metadata},u={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(u.Authorization=`Bearer ${this.apiKey}`),r&&(u["x-tenant-id"]=r);let c=new AbortController,n=setTimeout(()=>c.abort(),this.timeoutMs);try{let a=await this.customFetch(`${this.baseUrl}/api/v1/links`,{method:"POST",headers:u,body:JSON.stringify(l),signal:c.signal});if(!a.ok)throw new Error(`Links API error: ${a.status} ${a.statusText}`);let s=await a.json();return{id:s.id||`lnk_${Math.random().toString(36).substring(2,9)}`,slug:s.slug||t.slug||"",shortUrl:s.short_url||s.shortUrl||`${this.baseUrl}/${s.slug||t.slug||""}/${i}`,destinationUrl:s.destination_url||s.destinationUrl||o,channel:s.channel||i,campaign:s.campaign||t.campaign,tenantId:s.tenant_id||s.tenantId||r,trustScore:s.trust_score??s.trustScore,createdAt:s.created_at||s.createdAt||new Date().toISOString()}}catch(a){if(!this.enableFallback)throw a;return{id:`fallback-${Date.now()}-${Math.random().toString(36).substring(2,7)}`,slug:t.slug||"",shortUrl:o,destinationUrl:o,channel:i,campaign:t.campaign,tenantId:r,trustScore:void 0,createdAt:new Date().toISOString()}}finally{clearTimeout(n)}}async resolveTrustScore(t){if(!t)throw new Error("URL or slug is required");let i=t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")?`${this.baseUrl}/api/v1/trust?url=${encodeURIComponent(t)}`:`${this.baseUrl}/api/v1/trust/${encodeURIComponent(t)}`,r={Accept:"application/json"};this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`),this.tenantId&&(r["x-tenant-id"]=this.tenantId);let l=new AbortController,u=setTimeout(()=>l.abort(),this.timeoutMs);try{let c=await this.customFetch(i,{method:"GET",headers:r,signal:l.signal});if(!c.ok)throw new Error(`Trust API error: ${c.status} ${c.statusText}`);let n=await c.json(),a=n.score??n.trust_score;if(typeof a!="number"||isNaN(a))throw new Error("Invalid audit response: missing or unparseable trust score");let s=Math.max(0,Math.min(100,a)),d=s>=85?"trusted":s>=60?"warning":"danger",f=n.tier||(s>=85?"trusted":s>=60?"neutral":"danger");return{url:n.url||t,slug:n.slug,score:s,tier:f,status:d,flags:n.flags||{verified_did:!!n.verified_did,sanitized_trackers:!F(t),redirect_count:n.redirect_count??0,reputation_tier:f,is_flagged:s<60,ssl_valid:t.startsWith("https://")||t.startsWith("//")},pillars:n.pillars||{provenance:Math.round(s*.35),hygiene:Math.round(s*.25),privacy:Math.round(s*.2),networkDecay:Math.round(s*.2)},lastHygieneCheck:n.last_hygiene_check||n.lastHygieneCheck||new Date().toISOString(),did:n.did,recommendation:n.recommendation}}catch(c){if(!this.enableFallback)throw c;return this.computeLocalTrustScore(t)}finally{clearTimeout(u)}}sanitizeUrl(t){return k(t)}computeLocalTrustScore(t){let o=t.startsWith("https://")||t.startsWith("//"),i=F(t),r=10,l=o?25:10,u=i?5:20,c=20,n=r+l+u+c,a=n>=85?"trusted":n>=60?"warning":"danger",s=n>=85?"trusted":n>=60?"neutral":"danger",d={verified_did:!1,sanitized_trackers:!i,redirect_count:0,reputation_tier:s,is_flagged:n<60,ssl_valid:o};return{url:t,score:n,tier:s,status:a,flags:d,pillars:{provenance:r,hygiene:l,privacy:u,networkDecay:c},lastHygieneCheck:new Date().toISOString(),recommendation:n<60?"Destination has potential security or tracking concerns.":"Destination is reachable and verified against standard security baselines."}}},N=Symbol.for("@digitalcanopy/links/defaultClient");function q(){let e=globalThis;return e[N]||(e[N]=new H),e[N]}function I(e,t={}){let{channel:o,campaign:i,tenantId:r,enabled:l=!0,client:u,autoResolveTrust:c=!1}=t,n=u||q(),a=k(e),[s,d]=(0,p.useState)(a),[f,h]=(0,p.useState)(!!((l||c)&&e)),[S,y]=(0,p.useState)(!1),[T,x]=(0,p.useState)(void 0),[U,A]=(0,p.useState)(void 0),[L,R]=(0,p.useState)(null),E=(0,p.useRef)(!0),P=(0,p.useRef)(0),$=(0,p.useCallback)(async()=>{if(!e){d(""),h(!1),y(!1),R(null);return}if(!l&&!c){d(k(e)),h(!1),y(!1),R(null);return}let G=++P.current;h(!0),R(null);let V=l?n.shortenUrl({destination:e,channel:o,campaign:i,tenantId:r}):Promise.resolve(null),Y=c?n.resolveTrustScore(e):Promise.resolve(null),[g,b]=await Promise.allSettled([V,Y]);if(!E.current||G!==P.current)return;let M=a,D=!1,w,z,C=null;g.status==="fulfilled"&&g.value?(M=g.value.shortUrl,D=g.value.shortUrl!==a,typeof g.value.trustScore=="number"&&(w=g.value.trustScore)):g.status==="rejected"&&(M=a,D=!1,C=g.reason instanceof Error?g.reason:new Error(String(g.reason))),b.status==="fulfilled"&&b.value?(z=b.value,w===void 0&&(w=b.value.score)):b.status==="rejected"&&!C&&(C=b.reason instanceof Error?b.reason:new Error(String(b.reason))),d(M),y(D),x(w),z&&A(z),R(C),h(!1)},[e,l,o,i,r,c,n,a]);return(0,p.useEffect)(()=>(E.current=!0,$(),()=>{E.current=!1,P.current++}),[$]),{href:s,isLoading:f,isShortened:S,trustScore:T,trustReport:U,error:L,refetch:$}}var v=require("react/jsx-runtime"),j=({href:e,children:t,showBadge:o=!0,telemetry:i=!1,trustScore:r,resolveTrust:l=!1,badgeSize:u="sm",channel:c,campaign:n,tenantId:a,client:s,target:d,rel:f,className:h="",style:S,...y})=>{let T=typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//")),x=I(e,{enabled:i&&T,autoResolveTrust:l&&T&&r===void 0,channel:c,campaign:n,tenantId:a,client:s}),U=i?x.href:k(e),A=r??x.trustScore,L=d??(T?"_blank":void 0);return(0,v.jsxs)("a",{href:U,target:L,rel:f??(T&&L==="_blank"?"noopener noreferrer":void 0),className:h,style:{display:"inline-flex",alignItems:"center",gap:"6px",textDecoration:"none",...S},...y,children:[(0,v.jsx)("span",{children:t}),o&&T&&(0,v.jsx)(_,{score:A,size:u,showLabel:!1})]})};0&&(module.exports={SafeAnchor,TrustBadge,useTrackedLink});
@@ -0,0 +1 @@
1
+ import{c as k,e as N}from"../chunk-LFYYBCTE.mjs";import{jsx as g,jsxs as D}from"react/jsx-runtime";var U=({score:e,tier:b,status:c,showLabel:a=!1,size:d="sm",className:i="",onClick:p,"data-testid":l="trust-badge"})=>{let n=typeof e=="number"&&!isNaN(e),t=c||(n?e>=85?"trusted":e>=60?"warning":"danger":"unknown"),o={trusted:{bg:"rgba(16, 185, 129, 0.1)",border:"rgba(16, 185, 129, 0.3)",text:"#10B981"},warning:{bg:"rgba(245, 158, 11, 0.1)",border:"rgba(245, 158, 11, 0.3)",text:"#F59E0B"},danger:{bg:"rgba(239, 68, 68, 0.1)",border:"rgba(239, 68, 68, 0.3)",text:"#EF4444"},unknown:{bg:"rgba(100, 116, 139, 0.1)",border:"rgba(100, 116, 139, 0.3)",text:"#64748B"}}[t],r={sm:{icon:12,fontSize:"0.7rem",padding:"1px 5px",gap:"3px"},md:{icon:14,fontSize:"0.8rem",padding:"2px 8px",gap:"4px"},lg:{icon:18,fontSize:"0.9rem",padding:"4px 10px",gap:"6px"}}[d],h=n?`${e}/100`:b||"Unverified";return D("span",{"data-testid":l,"data-status":t,role:"img","aria-label":`Trust Score: ${n?`${e} out of 100`:"Unverified"}`,onClick:p,style:{display:"inline-flex",alignItems:"center",gap:r.gap,padding:r.padding,fontSize:r.fontSize,lineHeight:1,borderRadius:"9999px",backgroundColor:o.bg,border:`1px solid ${o.border}`,color:o.text,fontWeight:600,verticalAlign:"middle",cursor:p?"pointer":"default",userSelect:"none"},className:i,children:[D("svg",{width:r.icon,height:r.icon,viewBox:"0 0 24 24",fill:"none",stroke:o.text,strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[g("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"}),t==="trusted"&&g("path",{d:"m9 12 2 2 4-4"}),t==="warning"&&g("path",{d:"M12 8v4M12 16h.01"}),t==="danger"&&g("path",{d:"m15 9-6 6M9 9l6 6"})]}),a&&g("span",{children:h}),!a&&n&&g("span",{children:e})]})};import{useCallback as _,useEffect as j,useRef as W,useState as m}from"react";function H(e,b={}){let{channel:c,campaign:a,tenantId:d,enabled:i=!0,client:p,autoResolveTrust:l=!1}=b,n=p||N(),t=k(e),[x,o]=m(t),[R,r]=m(!!((i||l)&&e)),[h,T]=m(!1),[f,v]=m(void 0),[z,w]=m(void 0),[L,S]=m(null),B=W(!0),P=W(0),C=_(async()=>{if(!e){o(""),r(!1),T(!1),S(null);return}if(!i&&!l){o(k(e)),r(!1),T(!1),S(null);return}let $=++P.current;r(!0),S(null);let O=i?n.shortenUrl({destination:e,channel:c,campaign:a,tenantId:d}):Promise.resolve(null),q=l?n.resolveTrustScore(e):Promise.resolve(null),[s,u]=await Promise.allSettled([O,q]);if(!B.current||$!==P.current)return;let A=t,I=!1,y,M,E=null;s.status==="fulfilled"&&s.value?(A=s.value.shortUrl,I=s.value.shortUrl!==t,typeof s.value.trustScore=="number"&&(y=s.value.trustScore)):s.status==="rejected"&&(A=t,I=!1,E=s.reason instanceof Error?s.reason:new Error(String(s.reason))),u.status==="fulfilled"&&u.value?(M=u.value,y===void 0&&(y=u.value.score)):u.status==="rejected"&&!E&&(E=u.reason instanceof Error?u.reason:new Error(String(u.reason))),o(A),T(I),v(y),M&&w(M),S(E),r(!1)},[e,i,c,a,d,l,n,t]);return j(()=>(B.current=!0,C(),()=>{B.current=!1,P.current++}),[C]),{href:x,isLoading:R,isShortened:h,trustScore:f,trustReport:z,error:L,refetch:C}}import{jsx as F,jsxs as G}from"react/jsx-runtime";var V=({href:e,children:b,showBadge:c=!0,telemetry:a=!1,trustScore:d,resolveTrust:i=!1,badgeSize:p="sm",channel:l,campaign:n,tenantId:t,client:x,target:o,rel:R,className:r="",style:h,...T})=>{let f=typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//")),v=H(e,{enabled:a&&f,autoResolveTrust:i&&f&&d===void 0,channel:l,campaign:n,tenantId:t,client:x}),z=a?v.href:k(e),w=d??v.trustScore,L=o??(f?"_blank":void 0);return G("a",{href:z,target:L,rel:R??(f&&L==="_blank"?"noopener noreferrer":void 0),className:r,style:{display:"inline-flex",alignItems:"center",gap:"6px",textDecoration:"none",...h},...T,children:[F("span",{children:b}),c&&f&&F(U,{score:w,size:p,showLabel:!1})]})};export{V as SafeAnchor,U as TrustBadge,H as useTrackedLink};
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@digitalcanopy/links",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Universal SunShade linking client library and React hooks for URL shortening, trust scoring, and privacy-preserving telemetry",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md"
11
+ ],
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.mjs",
19
+ "require": "./dist/index.js"
20
+ },
21
+ "./react": {
22
+ "types": "./dist/react/index.d.ts",
23
+ "import": "./dist/react/index.mjs",
24
+ "require": "./dist/react/index.js"
25
+ }
26
+ },
27
+ "scripts": {
28
+ "build": "tsup src/index.ts src/react/index.ts --dts --format cjs,esm --minify",
29
+ "typecheck": "tsc --noEmit",
30
+ "test": "vitest run",
31
+ "test:boundaries": "vitest run"
32
+ },
33
+ "peerDependencies": {
34
+ "react": ">=18.0.0 || >=19.0.0"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "react": {
38
+ "optional": true
39
+ }
40
+ },
41
+ "devDependencies": {
42
+ "@types/react": "^19.1.0",
43
+ "react": "^19.1.0",
44
+ "tsup": "^8.5.1",
45
+ "typescript": "^5.7.3",
46
+ "vitest": "^3.0.5"
47
+ },
48
+ "keywords": [
49
+ "sunshade",
50
+ "links",
51
+ "shortener",
52
+ "trust-score",
53
+ "telemetry",
54
+ "react"
55
+ ],
56
+ "author": "SunShade Systems",
57
+ "license": "MIT"
58
+ }