forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
175 lines (153 loc) · 4.71 KB
/
client.ts
File metadata and controls
175 lines (153 loc) · 4.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/**
* Deno Integration (WASM)
*
* Uses @deno/doc (WASM build of deno_doc) for documentation generation.
* This runs entirely in Node.js without requiring a Deno subprocess.
*
* @module server/utils/docs/client
*/
import { doc, type DocNode } from '@deno/doc'
import type { DenoDocNode, DenoDocResult } from '#shared/types/deno-doc'
// =============================================================================
// Configuration
// =============================================================================
/** Timeout for fetching modules in milliseconds */
const FETCH_TIMEOUT_MS = 30 * 1000
// =============================================================================
// Main Export
// =============================================================================
/**
* Get documentation nodes for a package using @deno/doc WASM.
*/
export async function getDocNodes(packageName: string, version: string): Promise<DenoDocResult> {
// Get types URL from esm.sh header
const typesUrl = await getTypesUrl(packageName, version)
if (!typesUrl) {
return { version: 1, nodes: [] }
}
// Generate docs using @deno/doc WASM
let result: Record<string, DocNode[]>
try {
result = await doc([typesUrl], {
load: createLoader(),
resolve: createResolver(),
})
} catch {
return { version: 1, nodes: [] }
}
// Collect all nodes from all specifiers
const allNodes: DenoDocNode[] = []
for (const nodes of Object.values(result)) {
allNodes.push(...(nodes as DenoDocNode[]))
}
return { version: 1, nodes: allNodes }
}
// =============================================================================
// Module Loading
// =============================================================================
/** Load response for the doc() function */
interface LoadResponse {
kind: 'module'
specifier: string
headers?: Record<string, string>
content: string
}
/**
* Create a custom module loader for @deno/doc.
*
* Fetches modules from URLs using fetch(), with proper timeout handling.
*/
function createLoader(): (
specifier: string,
isDynamic?: boolean,
cacheSetting?: string,
checksum?: string,
) => Promise<LoadResponse | undefined> {
return async (
specifier: string,
_isDynamic?: boolean,
_cacheSetting?: string,
_checksum?: string,
) => {
let url: URL
try {
url = new URL(specifier)
} catch (e) {
// eslint-disable-next-line no-console
console.error(e)
return undefined
}
// Only handle http/https URLs
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return undefined
}
try {
const response = await $fetch.raw<Blob>(url.toString(), {
method: 'GET',
timeout: FETCH_TIMEOUT_MS,
redirect: 'follow',
})
if (response.status !== 200) {
return undefined
}
const content = (await response._data?.text()) ?? ''
const headers: Record<string, string> = {}
for (const [key, value] of response.headers) {
headers[key.toLowerCase()] = value
}
return {
kind: 'module',
specifier: response.url,
headers,
content,
}
} catch (e) {
// eslint-disable-next-line no-console
console.error(e)
return undefined
}
}
}
/**
* Create a module resolver for @deno/doc.
*
* Handles resolving relative imports and esm.sh redirects.
*/
function createResolver(): (specifier: string, referrer: string) => string {
return (specifier: string, referrer: string) => {
// Handle relative imports
if (specifier.startsWith('.') || specifier.startsWith('/')) {
return new URL(specifier, referrer).toString()
}
// Handle bare specifiers - resolve through esm.sh
if (!specifier.startsWith('http://') && !specifier.startsWith('https://')) {
// Try to resolve bare specifier relative to esm.sh base
const baseUrl = new URL(referrer)
if (baseUrl.hostname === 'esm.sh') {
return `https://esm.sh/${specifier}`
}
}
return specifier
}
}
/**
* Get the TypeScript types URL from esm.sh's x-typescript-types header.
*
* esm.sh serves types URL in the `x-typescript-types` header, not at the main URL.
* Example: curl -sI 'https://esm.sh/ufo@1.5.0' returns header:
* x-typescript-types: https://esm.sh/ufo@1.5.0/dist/index.d.ts
*/
async function getTypesUrl(packageName: string, version: string): Promise<string | null> {
const url = `https://esm.sh/${packageName}@${version}`
try {
const response = await $fetch.raw(url, {
method: 'HEAD',
timeout: FETCH_TIMEOUT_MS,
})
return response.headers.get('x-typescript-types')
} catch (e) {
// eslint-disable-next-line no-console
console.error(e)
return null
}
}