@decocms/blocks 8.0.0 → 8.1.0-next.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.
Files changed (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -0,0 +1,497 @@
1
+ /**
2
+ * A thin, read-only view over the TypeScript compiler API: the handful of
3
+ * type, symbol and node queries the schema generator makes.
4
+ *
5
+ * `deco schema` reads types with the app's own `typescript`, a peer
6
+ * dependency loaded with `import()` only when the command runs (spec:
7
+ * internals › How the CLI ships), so the schema is built with the compiler
8
+ * version the app type-checks with and nothing compiler-sized is installed
9
+ * on the package's behalf.
10
+ *
11
+ * The method names follow the subset of ts-morph's API the v7 generator was
12
+ * written against (the engine in ./typeToSchema.ts is a port of it), with the
13
+ * same semantics, so the port reads the same as the code it came from. Every
14
+ * wrapper is cached per compiler object, so `===` on two views means the same
15
+ * type, symbol or node.
16
+ */
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import type * as TS from "typescript";
20
+ import { CliError } from "../root";
21
+
22
+ type TypeScript = typeof TS;
23
+
24
+ /** Load the app's `typescript`. Throws a `CliError` with the fix when it isn't installed. */
25
+ export async function loadTypeScript(): Promise<TypeScript> {
26
+ try {
27
+ const mod = (await import("typescript")) as TypeScript & { default?: TypeScript };
28
+ return mod.default ?? mod;
29
+ } catch {
30
+ throw new CliError(
31
+ "deco schema reads your types with TypeScript, which isn't installed: add typescript to your devDependencies",
32
+ );
33
+ }
34
+ }
35
+
36
+ class Context {
37
+ readonly types = new WeakMap<TS.Type, TsType>();
38
+ readonly symbols = new WeakMap<TS.Symbol, TsSymbol>();
39
+ readonly nodes = new WeakMap<TS.Node, TsNode>();
40
+ readonly signatures = new WeakMap<TS.Signature, TsSignature>();
41
+
42
+ constructor(
43
+ readonly ts: TypeScript,
44
+ readonly checker: TS.TypeChecker,
45
+ ) {}
46
+
47
+ type(t: TS.Type): TsType {
48
+ return cached(this.types, t, () => new TsType(this, t));
49
+ }
50
+
51
+ symbol(s: TS.Symbol): TsSymbol {
52
+ return cached(this.symbols, s, () => new TsSymbol(this, s));
53
+ }
54
+
55
+ node(n: TS.Node): TsNode {
56
+ return cached(this.nodes, n, () =>
57
+ this.ts.isSourceFile(n) ? new TsSourceFile(this, n) : new TsNode(this, n),
58
+ );
59
+ }
60
+
61
+ signature(s: TS.Signature): TsSignature {
62
+ return cached(this.signatures, s, () => new TsSignature(this, s));
63
+ }
64
+ }
65
+
66
+ function cached<K extends object, V>(map: WeakMap<K, V>, key: K, create: () => V): V {
67
+ const hit = map.get(key);
68
+ if (hit !== undefined) return hit;
69
+ const value = create();
70
+ map.set(key, value);
71
+ return value;
72
+ }
73
+
74
+ export class TsType {
75
+ constructor(
76
+ private readonly ctx: Context,
77
+ readonly compilerType: TS.Type,
78
+ ) {}
79
+
80
+ private hasFlag(flag: TS.TypeFlags): boolean {
81
+ return (this.compilerType.flags & flag) === flag;
82
+ }
83
+
84
+ private objectFlags(): number {
85
+ return this.isObject() ? ((this.compilerType as TS.ObjectType).objectFlags ?? 0) : 0;
86
+ }
87
+
88
+ /** The type as the checker prints it (ts-morph's default format flags). */
89
+ getText(): string {
90
+ const F = this.ctx.ts.TypeFormatFlags;
91
+ return this.ctx.checker.typeToString(
92
+ this.compilerType,
93
+ undefined,
94
+ F.UseTypeOfFunction |
95
+ F.NoTruncation |
96
+ F.UseFullyQualifiedType |
97
+ F.WriteTypeArgumentsOfSignature,
98
+ );
99
+ }
100
+
101
+ getSymbol(): TsSymbol | undefined {
102
+ const s = this.compilerType.getSymbol();
103
+ return s ? this.ctx.symbol(s) : undefined;
104
+ }
105
+
106
+ getAliasSymbol(): TsSymbol | undefined {
107
+ const s = this.compilerType.aliasSymbol;
108
+ return s ? this.ctx.symbol(s) : undefined;
109
+ }
110
+
111
+ getAliasTypeArguments(): TsType[] {
112
+ return (this.compilerType.aliasTypeArguments ?? []).map((t) => this.ctx.type(t));
113
+ }
114
+
115
+ getTypeArguments(): TsType[] {
116
+ return this.ctx.checker
117
+ .getTypeArguments(this.compilerType as TS.TypeReference)
118
+ .map((t) => this.ctx.type(t));
119
+ }
120
+
121
+ getCallSignatures(): TsSignature[] {
122
+ return this.compilerType.getCallSignatures().map((s) => this.ctx.signature(s));
123
+ }
124
+
125
+ getProperties(): TsSymbol[] {
126
+ return this.compilerType.getProperties().map((s) => this.ctx.symbol(s));
127
+ }
128
+
129
+ getProperty(name: string): TsSymbol | undefined {
130
+ return this.getProperties().find((p) => p.getName() === name);
131
+ }
132
+
133
+ getStringIndexType(): TsType | undefined {
134
+ const t = this.compilerType.getStringIndexType();
135
+ return t ? this.ctx.type(t) : undefined;
136
+ }
137
+
138
+ getNumberIndexType(): TsType | undefined {
139
+ const t = this.compilerType.getNumberIndexType();
140
+ return t ? this.ctx.type(t) : undefined;
141
+ }
142
+
143
+ getNonNullableType(): TsType {
144
+ return this.ctx.type(this.compilerType.getNonNullableType());
145
+ }
146
+
147
+ getUnionTypes(): TsType[] {
148
+ return this.isUnion()
149
+ ? (this.compilerType as TS.UnionType).types.map((t) => this.ctx.type(t))
150
+ : [];
151
+ }
152
+
153
+ getIntersectionTypes(): TsType[] {
154
+ return this.isIntersection()
155
+ ? (this.compilerType as TS.IntersectionType).types.map((t) => this.ctx.type(t))
156
+ : [];
157
+ }
158
+
159
+ getArrayElementType(): TsType | undefined {
160
+ return this.isArray() ? this.getTypeArguments()[0] : undefined;
161
+ }
162
+
163
+ getLiteralValue(): unknown {
164
+ return (this.compilerType as TS.LiteralType).value;
165
+ }
166
+
167
+ isAssignableTo(target: TsType): boolean {
168
+ return this.ctx.checker.isTypeAssignableTo(this.compilerType, target.compilerType);
169
+ }
170
+
171
+ isArray(): boolean {
172
+ const name = this.getSymbol()?.getName();
173
+ return (name === "Array" || name === "ReadonlyArray") && this.getTypeArguments().length === 1;
174
+ }
175
+
176
+ isAny(): boolean {
177
+ return this.hasFlag(this.ctx.ts.TypeFlags.Any);
178
+ }
179
+ isUnknown(): boolean {
180
+ return this.hasFlag(this.ctx.ts.TypeFlags.Unknown);
181
+ }
182
+ isNever(): boolean {
183
+ return this.hasFlag(this.ctx.ts.TypeFlags.Never);
184
+ }
185
+ isVoid(): boolean {
186
+ return this.hasFlag(this.ctx.ts.TypeFlags.Void);
187
+ }
188
+ isString(): boolean {
189
+ return this.hasFlag(this.ctx.ts.TypeFlags.String);
190
+ }
191
+ isNumber(): boolean {
192
+ return this.hasFlag(this.ctx.ts.TypeFlags.Number);
193
+ }
194
+ isBoolean(): boolean {
195
+ return this.hasFlag(this.ctx.ts.TypeFlags.Boolean);
196
+ }
197
+ isBooleanLiteral(): boolean {
198
+ return this.hasFlag(this.ctx.ts.TypeFlags.BooleanLiteral);
199
+ }
200
+ isNumberLiteral(): boolean {
201
+ return this.hasFlag(this.ctx.ts.TypeFlags.NumberLiteral);
202
+ }
203
+ isStringLiteral(): boolean {
204
+ return this.compilerType.isStringLiteral();
205
+ }
206
+ isLiteral(): boolean {
207
+ return this.compilerType.isLiteral() || this.isBooleanLiteral();
208
+ }
209
+ isNull(): boolean {
210
+ return this.hasFlag(this.ctx.ts.TypeFlags.Null);
211
+ }
212
+ isUndefined(): boolean {
213
+ return this.hasFlag(this.ctx.ts.TypeFlags.Undefined);
214
+ }
215
+ isUnion(): boolean {
216
+ return this.compilerType.isUnion();
217
+ }
218
+ isIntersection(): boolean {
219
+ return this.compilerType.isIntersection();
220
+ }
221
+ isObject(): boolean {
222
+ return this.hasFlag(this.ctx.ts.TypeFlags.Object);
223
+ }
224
+ isInterface(): boolean {
225
+ const flag = this.ctx.ts.ObjectFlags.Interface;
226
+ return (this.objectFlags() & flag) === flag;
227
+ }
228
+ }
229
+
230
+ export class TsSymbol {
231
+ constructor(
232
+ private readonly ctx: Context,
233
+ readonly compilerSymbol: TS.Symbol,
234
+ ) {}
235
+
236
+ getName(): string {
237
+ return this.compilerSymbol.getName();
238
+ }
239
+
240
+ getDeclarations(): TsNode[] {
241
+ return (this.compilerSymbol.declarations ?? []).map((d) => this.ctx.node(d));
242
+ }
243
+
244
+ getValueDeclaration(): TsNode | undefined {
245
+ const d = this.compilerSymbol.valueDeclaration;
246
+ return d ? this.ctx.node(d) : undefined;
247
+ }
248
+
249
+ getTypeAtLocation(node: TsNode): TsType {
250
+ return this.ctx.type(
251
+ this.ctx.checker.getTypeOfSymbolAtLocation(this.compilerSymbol, node.compilerNode),
252
+ );
253
+ }
254
+
255
+ private hasFlag(flag: TS.SymbolFlags): boolean {
256
+ return (this.compilerSymbol.getFlags() & flag) === flag;
257
+ }
258
+
259
+ isOptional(): boolean {
260
+ return this.hasFlag(this.ctx.ts.SymbolFlags.Optional);
261
+ }
262
+
263
+ isAlias(): boolean {
264
+ return this.hasFlag(this.ctx.ts.SymbolFlags.Alias);
265
+ }
266
+
267
+ getAliasedSymbol(): TsSymbol | undefined {
268
+ const s = this.ctx.checker.getAliasedSymbol(this.compilerSymbol);
269
+ return s ? this.ctx.symbol(s) : undefined;
270
+ }
271
+ }
272
+
273
+ export class TsSignature {
274
+ constructor(
275
+ private readonly ctx: Context,
276
+ readonly compilerSignature: TS.Signature,
277
+ ) {}
278
+
279
+ getParameters(): TsSymbol[] {
280
+ return this.compilerSignature.parameters.map((p) => this.ctx.symbol(p));
281
+ }
282
+
283
+ getReturnType(): TsType {
284
+ return this.ctx.type(this.compilerSignature.getReturnType());
285
+ }
286
+
287
+ getDeclaration(): TsNode | undefined {
288
+ const d = this.compilerSignature.getDeclaration();
289
+ return d ? this.ctx.node(d) : undefined;
290
+ }
291
+ }
292
+
293
+ /** One JSDoc comment: its description and its tags. */
294
+ export interface JsDocView {
295
+ getDescription(): string;
296
+ getTags(): { getTagName(): string; getCommentText(): string | undefined }[];
297
+ }
298
+
299
+ export class TsNode {
300
+ constructor(
301
+ protected readonly ctx: Context,
302
+ readonly compilerNode: TS.Node,
303
+ ) {}
304
+
305
+ getSourceFile(): TsSourceFile {
306
+ return this.ctx.node(this.compilerNode.getSourceFile()) as TsSourceFile;
307
+ }
308
+
309
+ getParent(): TsNode | undefined {
310
+ const p = this.compilerNode.parent;
311
+ return p ? this.ctx.node(p) : undefined;
312
+ }
313
+
314
+ getText(): string {
315
+ return this.compilerNode.getText(this.compilerNode.getSourceFile());
316
+ }
317
+
318
+ /** The type annotation as written, on a property or variable declaration. */
319
+ getTypeNode(): TsNode | undefined {
320
+ const t = (this.compilerNode as { type?: TS.Node }).type;
321
+ return t && typeof t === "object" && "kind" in t ? this.ctx.node(t) : undefined;
322
+ }
323
+
324
+ /** Whether `other` is this node or inside it. */
325
+ contains(other: TsNode): boolean {
326
+ const a = this.compilerNode;
327
+ const b = other.compilerNode;
328
+ return a.getSourceFile() === b.getSourceFile() && a.pos <= b.pos && b.end <= a.end;
329
+ }
330
+
331
+ getJsDocs(): JsDocView[] {
332
+ const docs = (this.compilerNode as { jsDoc?: TS.JSDoc[] }).jsDoc ?? [];
333
+ return docs.map((doc) => jsDocView(this.ctx.ts, doc));
334
+ }
335
+ }
336
+
337
+ export class TsSourceFile extends TsNode {
338
+ getFilePath(): string {
339
+ return (this.compilerNode as TS.SourceFile).fileName;
340
+ }
341
+
342
+ getDefaultExportSymbol(): TsSymbol | undefined {
343
+ const symbol = this.ctx.checker.getSymbolAtLocation(this.compilerNode);
344
+ const exported = symbol?.exports?.get(this.ctx.ts.escapeLeadingUnderscores("default"));
345
+ return exported ? this.ctx.symbol(exported) : undefined;
346
+ }
347
+
348
+ /** The declared type of a top-level interface. */
349
+ getInterfaceType(name: string): TsType {
350
+ const decl = (this.compilerNode as TS.SourceFile).statements.find(
351
+ (s): s is TS.InterfaceDeclaration =>
352
+ this.ctx.ts.isInterfaceDeclaration(s) && s.name.text === name,
353
+ );
354
+ if (!decl) throw new Error(`no interface ${name} in ${this.getFilePath()}`);
355
+ return this.ctx.type(this.ctx.checker.getTypeAtLocation(decl));
356
+ }
357
+ }
358
+
359
+ function isWhitespace(code: number): boolean {
360
+ return code === 32 || code === 9 || code === 10 || code === 13 || code === 11 || code === 12;
361
+ }
362
+
363
+ function previousMatchingPos(text: string, start: number, match: (code: number) => boolean) {
364
+ let pos = start;
365
+ while (pos > 0 && !match(text.charCodeAt(pos - 1))) pos--;
366
+ return pos;
367
+ }
368
+
369
+ function textWithoutStars(input: string): string {
370
+ const inner = input.replace(/^\/\*\*[^\S\n]*\n?/, "").replace(/(\r?\n)?[^\S\n]*\*\/$/, "");
371
+ return inner
372
+ .split(/\n/)
373
+ .map((line) => {
374
+ let star = -1;
375
+ for (let i = 0; i < line.length; i++) {
376
+ const code = line.charCodeAt(i);
377
+ if (code === 42) {
378
+ star = i;
379
+ break;
380
+ }
381
+ if (!isWhitespace(code)) break;
382
+ }
383
+ if (star === -1) return line;
384
+ return line.substring(line[star + 1] === " " ? star + 2 : star + 1);
385
+ })
386
+ .join("\n");
387
+ }
388
+
389
+ /**
390
+ * A JSDoc comment's description: the raw text before the first tag, without
391
+ * the comment's stars (ts-morph's `JSDoc.getDescription`, so a description
392
+ * keeps the line breaks and inline markup it was written with).
393
+ */
394
+ function jsDocView(ts: TypeScript, doc: TS.JSDoc): JsDocView {
395
+ const sourceFile = doc.getSourceFile();
396
+ const commentText = (comment: TS.JSDoc["comment"]) =>
397
+ typeof comment === "string" ? comment : ts.getTextOfJSDocComment(comment);
398
+ return {
399
+ getDescription() {
400
+ const text = sourceFile.getFullText();
401
+ const firstTag = doc.tags?.[0];
402
+ const endSearchStart = firstTag ? firstTag.getStart(sourceFile) : doc.end - 2;
403
+ let start = doc.getStart(sourceFile) + 3;
404
+ if (text.charCodeAt(start) === 32) start++;
405
+ const endOrNewLine = previousMatchingPos(
406
+ text,
407
+ endSearchStart,
408
+ (c) => c === 10 || (!isWhitespace(c) && c !== 42),
409
+ );
410
+ const end = previousMatchingPos(text, endOrNewLine, (c) => c !== 10 && c !== 13);
411
+ return textWithoutStars(text.substring(start, Math.max(start, end)));
412
+ },
413
+ getTags() {
414
+ return (doc.tags ?? []).map((tag) => ({
415
+ getTagName: () => tag.tagName.getText(sourceFile),
416
+ getCommentText: () => commentText(tag.comment),
417
+ }));
418
+ },
419
+ };
420
+ }
421
+
422
+ export interface TsProject {
423
+ ts: TypeScript;
424
+ sourceFile(file: string): TsSourceFile;
425
+ /** Every file the program read from disk (lib files and dependencies included). */
426
+ fileNames(): string[];
427
+ }
428
+
429
+ /** Compiler options when the app has no tsconfig.json. */
430
+ function defaultOptions(ts: TypeScript): TS.CompilerOptions {
431
+ return {
432
+ target: ts.ScriptTarget.ES2022,
433
+ module: ts.ModuleKind.ESNext,
434
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
435
+ jsx: ts.JsxEmit.ReactJSX,
436
+ strict: true,
437
+ skipLibCheck: true,
438
+ resolveJsonModule: true,
439
+ };
440
+ }
441
+
442
+ function readCompilerOptions(ts: TypeScript, root: string): TS.CompilerOptions {
443
+ const tsconfig = path.join(root, "tsconfig.json");
444
+ if (!fs.existsSync(tsconfig)) return defaultOptions(ts);
445
+ const read = ts.readConfigFile(tsconfig, ts.sys.readFile);
446
+ if (read.error) {
447
+ throw new CliError(
448
+ `${tsconfig}: ${ts.flattenDiagnosticMessageText(read.error.messageText, "\n")}`,
449
+ );
450
+ }
451
+ // Only the options: the program's files are the block map and what it imports.
452
+ return ts.parseJsonConfigFileContent(read.config, ts.sys, root, undefined, tsconfig).options;
453
+ }
454
+
455
+ /**
456
+ * A program over the block map (and everything it imports) plus in-memory
457
+ * files, with the app's tsconfig options when it has one.
458
+ */
459
+ export async function createTsProject(
460
+ root: string,
461
+ rootFiles: string[],
462
+ virtualFiles: Record<string, string> = {},
463
+ ): Promise<TsProject> {
464
+ const ts = await loadTypeScript();
465
+ const options = readCompilerOptions(ts, root);
466
+ const host = ts.createCompilerHost(options, true);
467
+ const virtual = new Map(Object.entries(virtualFiles).map(([f, text]) => [path.resolve(f), text]));
468
+ const { getSourceFile, fileExists, readFile } = host;
469
+ host.fileExists = (file) => virtual.has(path.resolve(file)) || fileExists.call(host, file);
470
+ host.readFile = (file) => virtual.get(path.resolve(file)) ?? readFile.call(host, file);
471
+ host.getSourceFile = (file, languageVersion, onError, shouldCreate) => {
472
+ const text = virtual.get(path.resolve(file));
473
+ return text !== undefined
474
+ ? ts.createSourceFile(file, text, languageVersion, true)
475
+ : getSourceFile.call(host, file, languageVersion, onError, shouldCreate);
476
+ };
477
+ const program = ts.createProgram({
478
+ rootNames: [...Object.keys(virtualFiles), ...rootFiles],
479
+ options,
480
+ host,
481
+ });
482
+ const ctx = new Context(ts, program.getTypeChecker());
483
+ return {
484
+ ts,
485
+ sourceFile(file) {
486
+ const sf = program.getSourceFile(file);
487
+ if (!sf) throw new CliError(`couldn't read ${file}`);
488
+ return ctx.node(sf) as TsSourceFile;
489
+ },
490
+ fileNames() {
491
+ return program
492
+ .getSourceFiles()
493
+ .map((sf) => sf.fileName)
494
+ .filter((f) => !virtual.has(path.resolve(f)));
495
+ },
496
+ };
497
+ }