-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimporter.ts
More file actions
160 lines (137 loc) · 4.23 KB
/
importer.ts
File metadata and controls
160 lines (137 loc) · 4.23 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
import Module from 'node:module'
import { toError } from '@kidd-cli/utils/fp'
import { hasTag } from '@kidd-cli/utils/tag'
import { createJiti } from 'jiti'
import type { StoryEntry } from './types.js'
/**
* A story importer that can load `.stories.{tsx,ts,jsx,js}` files.
*/
export interface StoryImporter {
readonly importStory: (filePath: string) => Promise<[Error, null] | [null, StoryEntry]>
}
/**
* Create a story importer backed by jiti with cache disabled for hot reload.
*
* Installs a TypeScript extension resolution hook so that ESM-style `.js`
* imports (e.g. `from './alert.js'`) resolve to `.ts` / `.tsx` source files.
*
* @returns A frozen {@link StoryImporter} instance.
*/
export function createStoryImporter(): StoryImporter {
installTsExtensionResolution()
const jiti = createJiti(import.meta.url, {
fsCache: false,
moduleCache: false,
interopDefault: true,
jsx: { runtime: 'automatic' },
})
return Object.freeze({
importStory: async (filePath: string): Promise<[Error, null] | [null, StoryEntry]> => {
try {
const mod = (await jiti.import(filePath)) as Record<string, unknown>
const entry = (mod.default ?? mod) as unknown
if (!isStoryEntry(entry)) {
return [new Error(`File ${filePath} does not export a valid Story or StoryGroup`), null]
}
return [null, entry]
} catch (error) {
return [toError(error), null]
}
},
})
}
// ---------------------------------------------------------------------------
/**
* TypeScript extensions to try when a `.js` import fails to resolve.
*
* @private
*/
const TS_EXTENSIONS: readonly string[] = ['.ts', '.tsx']
/**
* TypeScript extensions to try when a `.jsx` import fails to resolve.
*
* @private
*/
const TSX_EXTENSIONS: readonly string[] = ['.tsx', '.ts', '.jsx']
/**
* Name used to tag the patched `_resolveFilename` function so the
* patch can detect itself and remain idempotent.
*
* @private
*/
const PATCHED_FN_NAME = '__kidd_ts_resolve'
/**
* Patch `Module._resolveFilename` so that ESM-style `.js` / `.jsx` specifiers
* fall back to their TypeScript equivalents (`.ts`, `.tsx`).
*
* This is the same strategy used by `tsx` and `ts-node`. The patch is
* idempotent — calling it more than once is a no-op.
*
* @private
*/
function installTsExtensionResolution(): void {
const mod = Module as unknown as Record<string, unknown>
const current = mod._resolveFilename as (...args: unknown[]) => string
if (current.name === PATCHED_FN_NAME) {
return
}
const original = current
const patched = {
[PATCHED_FN_NAME]: (
request: string,
parent: unknown,
isMain: boolean,
options: unknown
): string => {
try {
return original.call(mod, request, parent, isMain, options)
} catch (error) {
const alternates = resolveAlternateExtensions(request)
const resolved = alternates.reduce<string | null>((found, alt) => {
if (found) {
return found
}
try {
return original.call(mod, alt, parent, isMain, options)
} catch {
return null
}
}, null)
if (resolved) {
return resolved
}
throw error
}
},
}
mod._resolveFilename = patched[PATCHED_FN_NAME]
}
/**
* Build a list of alternate file paths to try when a `.js` or `.jsx`
* import fails to resolve.
*
* @private
* @param request - The original module specifier.
* @returns Alternate specifiers to try, or an empty array if not applicable.
*/
function resolveAlternateExtensions(request: string): readonly string[] {
if (request.endsWith('.js')) {
const base = request.slice(0, -3)
return [...TS_EXTENSIONS.map((ext) => base + ext), base]
}
if (request.endsWith('.jsx')) {
const base = request.slice(0, -4)
return TSX_EXTENSIONS.map((ext) => base + ext)
}
return []
}
/**
* Check whether a value is a valid {@link StoryEntry} (tagged as `Story` or `StoryGroup`).
*
* @private
* @param value - The value to check.
* @returns `true` when `value` carries a `Story` or `StoryGroup` tag.
*/
function isStoryEntry(value: unknown): value is StoryEntry {
return hasTag(value, 'Story') || hasTag(value, 'StoryGroup')
}