tempo-sdk 0.0.6 → 0.0.8

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.
@@ -0,0 +1,935 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // nextjs-loader.ts
31
+ var nextjs_loader_exports = {};
32
+ __export(nextjs_loader_exports, {
33
+ _resetLoaderState: () => _resetLoaderState,
34
+ default: () => nextjs_loader_default,
35
+ injectRootMetaIntoAnnotatedSource: () => injectRootMetaIntoAnnotatedSource,
36
+ injectRootMetaIntoSource: () => injectRootMetaIntoSource,
37
+ nextjsLoader: () => nextjsLoader
38
+ });
39
+ module.exports = __toCommonJS(nextjs_loader_exports);
40
+ var import_node_fs3 = require("fs");
41
+ var import_node_module = require("module");
42
+ var import_node_path3 = require("path");
43
+
44
+ // ../../modules/annotation/annotate-file.ts
45
+ var import_oxc_parser2 = require("oxc-parser");
46
+
47
+ // ../../modules/file-parser/utils.ts
48
+ function getTagName(name) {
49
+ switch (name.type) {
50
+ case "JSXIdentifier":
51
+ return name.name;
52
+ case "JSXNamespacedName":
53
+ return `${name.namespace.name}:${name.name.name}`;
54
+ case "JSXMemberExpression":
55
+ return getJSXMemberExpressionName(name);
56
+ }
57
+ }
58
+ function getJSXMemberExpressionName(node) {
59
+ const object = node.object.type === "JSXIdentifier" ? node.object.name : getJSXMemberExpressionName(node.object);
60
+ return `${object}.${node.property.name}`;
61
+ }
62
+
63
+ // ../../modules/file-parser/walk.ts
64
+ function walk(node, callbacks) {
65
+ if (node === null || node === void 0 || typeof node !== "object") return;
66
+ if (Array.isArray(node)) {
67
+ for (const child of node) {
68
+ walk(child, callbacks);
69
+ }
70
+ return;
71
+ }
72
+ const record = node;
73
+ const type = record.type;
74
+ if (typeof type === "string" && type in callbacks) {
75
+ callbacks[type](node);
76
+ }
77
+ for (const value of Object.values(record)) {
78
+ if (value !== null && typeof value === "object") {
79
+ walk(value, callbacks);
80
+ }
81
+ }
82
+ }
83
+
84
+ // ../../modules/file-parser/scope-analyzer/types.ts
85
+ var ScopeFlags = {
86
+ Top: 1 << 0,
87
+ Function: 1 << 1,
88
+ Block: 1 << 2,
89
+ Catch: 1 << 3,
90
+ Class: 1 << 4,
91
+ For: 1 << 5,
92
+ Switch: 1 << 6,
93
+ Module: 1 << 7,
94
+ StrictMode: 1 << 8,
95
+ ClassStaticBlock: 1 << 9,
96
+ TsModuleBlock: 1 << 10,
97
+ TsConditional: 1 << 11,
98
+ Type: 1 << 12,
99
+ Enum: 1 << 13
100
+ };
101
+
102
+ // ../../modules/file-parser/scope-analyzer/scopeAnalyzer.ts
103
+ var import_oxc_parser = require("oxc-parser");
104
+ var import_keys = __toESM(require("oxc-parser/src-js/generated/visit/keys.js"), 1);
105
+
106
+ // ../../modules/annotation/annotate-file.ts
107
+ function formatPropValue(value) {
108
+ if (value === void 0) return null;
109
+ if (typeof value === "function") return value.toString();
110
+ return JSON.stringify(value);
111
+ }
112
+ function formatProps(props) {
113
+ return Object.entries(props).map(([key, value]) => {
114
+ const formatted = formatPropValue(value);
115
+ if (formatted === null) return null;
116
+ return ` ${key}={${formatted}}`;
117
+ }).filter((s) => s !== null).join("");
118
+ }
119
+ function getExistingAttributeNames(element) {
120
+ const names = /* @__PURE__ */ new Set();
121
+ for (const attr of element.openingElement.attributes ?? []) {
122
+ if (attr.type !== "JSXAttribute") continue;
123
+ names.add(getTagName(attr.name));
124
+ }
125
+ return names;
126
+ }
127
+ function removeExistingProps(props, existingNames) {
128
+ return Object.fromEntries(
129
+ Object.entries(props).filter(([key]) => !existingNames.has(key))
130
+ );
131
+ }
132
+ var FRAGMENT_TAG_NAMES = /* @__PURE__ */ new Set(["Fragment", "React.Fragment"]);
133
+ function annotateFile(source, filename, computeAnnotatedProps) {
134
+ const parseResult = (0, import_oxc_parser2.parseSync)(filename, source);
135
+ const insertions = [];
136
+ walk(parseResult.program, {
137
+ JSXElement(node) {
138
+ const element = node;
139
+ const tagName = getTagName(element.openingElement.name);
140
+ if (FRAGMENT_TAG_NAMES.has(tagName)) return;
141
+ const props = removeExistingProps(
142
+ computeAnnotatedProps({ element, tagName }),
143
+ getExistingAttributeNames(element)
144
+ );
145
+ if (Object.keys(props).length === 0) return;
146
+ const openingElement = element.openingElement;
147
+ let insertPos = openingElement.end - 1;
148
+ if (openingElement.selfClosing) {
149
+ insertPos--;
150
+ while (insertPos > openingElement.start && /\s/.test(source[insertPos - 1])) {
151
+ insertPos--;
152
+ }
153
+ }
154
+ insertions.push({ position: insertPos, text: formatProps(props) });
155
+ }
156
+ });
157
+ insertions.sort((a, b) => a.position - b.position);
158
+ const chunks = [];
159
+ let lastPos = 0;
160
+ for (const { position, text } of insertions) {
161
+ chunks.push(source.slice(lastPos, position));
162
+ chunks.push(text);
163
+ lastPos = position;
164
+ }
165
+ chunks.push(source.slice(lastPos));
166
+ return { annotatedSource: chunks.join(""), elementsAnnotated: insertions.length, parseResult };
167
+ }
168
+
169
+ // nextjs-loader.ts
170
+ var import_oxc_parser3 = require("oxc-parser");
171
+
172
+ // type-analyzer.ts
173
+ var import_typescript2 = __toESM(require("typescript"), 1);
174
+ var import_node_path2 = __toESM(require("path"), 1);
175
+ var import_node_fs2 = require("fs");
176
+
177
+ // ../../modules/typescript/workspace-service.ts
178
+ var import_node_fs = require("fs");
179
+ var import_node_path = __toESM(require("path"), 1);
180
+ var import_typescript = __toESM(require("typescript"), 1);
181
+ function canonicalPath(input) {
182
+ const resolved = import_node_path.default.resolve(input);
183
+ try {
184
+ return import_node_fs.realpathSync.native(resolved);
185
+ } catch {
186
+ return resolved;
187
+ }
188
+ }
189
+ function compareProjectPriority(left, right) {
190
+ const depthDelta = right.rootDir.length - left.rootDir.length;
191
+ if (depthDelta !== 0) {
192
+ return depthDelta;
193
+ }
194
+ const priorityDelta = right.priority - left.priority;
195
+ if (priorityDelta !== 0) {
196
+ return priorityDelta;
197
+ }
198
+ return left.id.localeCompare(right.id);
199
+ }
200
+ function isWithinRoot(filePath, rootDir) {
201
+ return filePath === rootDir || filePath.startsWith(`${rootDir}${import_node_path.default.sep}`);
202
+ }
203
+ function loadProject(descriptor) {
204
+ const id = descriptor.id.trim();
205
+ if (!id) {
206
+ throw new Error("Project id must be a non-empty string");
207
+ }
208
+ const tsconfigPath = canonicalPath(descriptor.tsconfigPath);
209
+ const rootDir = canonicalPath(descriptor.rootDir);
210
+ const readResult = import_typescript.default.readConfigFile(tsconfigPath, import_typescript.default.sys.readFile);
211
+ if (readResult.error) {
212
+ throw new Error(
213
+ `Failed to read tsconfig at ${tsconfigPath}: ${import_typescript.default.flattenDiagnosticMessageText(
214
+ readResult.error.messageText,
215
+ "\n"
216
+ )}`
217
+ );
218
+ }
219
+ const parsed = import_typescript.default.parseJsonConfigFileContent(
220
+ readResult.config,
221
+ import_typescript.default.sys,
222
+ import_node_path.default.dirname(tsconfigPath)
223
+ );
224
+ if (parsed.errors.length > 0) {
225
+ const message = parsed.errors.map(
226
+ (diagnostic) => import_typescript.default.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
227
+ ).join("; ");
228
+ throw new Error(`Failed to parse tsconfig at ${tsconfigPath}: ${message}`);
229
+ }
230
+ const normalizedFiles = parsed.fileNames.map(
231
+ (fileName) => canonicalPath(fileName)
232
+ );
233
+ return {
234
+ id,
235
+ rootDir,
236
+ tsconfigPath,
237
+ priority: descriptor.priority ?? 0,
238
+ options: parsed.options,
239
+ fileNames: normalizedFiles,
240
+ moduleResolutionCache: import_typescript.default.createModuleResolutionCache(
241
+ rootDir,
242
+ (value) => value,
243
+ parsed.options
244
+ )
245
+ };
246
+ }
247
+ function getFileMtimeVersion(filePath) {
248
+ try {
249
+ const stats = (0, import_node_fs.statSync)(filePath);
250
+ return String(stats.mtimeMs);
251
+ } catch {
252
+ return "0";
253
+ }
254
+ }
255
+ function createTsWorkspaceService(descriptor) {
256
+ if (descriptor.projects.length === 0) {
257
+ throw new Error(
258
+ "TsWorkspaceDescriptor.projects must include at least one project"
259
+ );
260
+ }
261
+ const workspaceRoot = canonicalPath(descriptor.workspaceRoot);
262
+ const loadedProjects = descriptor.projects.map(
263
+ (project) => loadProject(project)
264
+ );
265
+ const projectsById = /* @__PURE__ */ new Map();
266
+ for (const project of loadedProjects) {
267
+ if (projectsById.has(project.id)) {
268
+ throw new Error(`Duplicate project id: ${project.id}`);
269
+ }
270
+ projectsById.set(project.id, project);
271
+ }
272
+ const primaryProject = (descriptor.primaryProjectId ? projectsById.get(descriptor.primaryProjectId) : null) ?? loadedProjects[0];
273
+ if (descriptor.primaryProjectId && !projectsById.has(descriptor.primaryProjectId)) {
274
+ throw new Error(
275
+ `Primary project id not found: ${descriptor.primaryProjectId}`
276
+ );
277
+ }
278
+ const orderedProjects = [...loadedProjects].sort(compareProjectPriority);
279
+ const rootFileNames = /* @__PURE__ */ new Set();
280
+ for (const project of loadedProjects) {
281
+ for (const fileName of project.fileNames) {
282
+ rootFileNames.add(fileName);
283
+ }
284
+ }
285
+ const inMemoryFiles = /* @__PURE__ */ new Map();
286
+ let projectVersion = 0;
287
+ function getOwningProject(filePath) {
288
+ const canonicalFilePath = canonicalPath(filePath);
289
+ for (const project of orderedProjects) {
290
+ if (isWithinRoot(canonicalFilePath, project.rootDir)) {
291
+ return project;
292
+ }
293
+ }
294
+ return primaryProject;
295
+ }
296
+ const moduleResolutionHost = {
297
+ fileExists: import_typescript.default.sys.fileExists,
298
+ readFile: import_typescript.default.sys.readFile,
299
+ realpath: import_typescript.default.sys.realpath,
300
+ directoryExists: import_typescript.default.sys.directoryExists,
301
+ getCurrentDirectory: () => workspaceRoot,
302
+ getDirectories: import_typescript.default.sys.getDirectories
303
+ };
304
+ const host = {
305
+ getScriptFileNames: () => Array.from(rootFileNames),
306
+ getScriptVersion: (filePath) => {
307
+ const canonicalFilePath = canonicalPath(filePath);
308
+ const inMemory = inMemoryFiles.get(canonicalFilePath);
309
+ if (inMemory) {
310
+ return String(inMemory.version);
311
+ }
312
+ return getFileMtimeVersion(canonicalFilePath);
313
+ },
314
+ getScriptSnapshot: (filePath) => {
315
+ const canonicalFilePath = canonicalPath(filePath);
316
+ const inMemory = inMemoryFiles.get(canonicalFilePath);
317
+ if (inMemory) {
318
+ return import_typescript.default.ScriptSnapshot.fromString(inMemory.content);
319
+ }
320
+ const diskContent = import_typescript.default.sys.readFile(canonicalFilePath);
321
+ if (diskContent === void 0) {
322
+ return void 0;
323
+ }
324
+ return import_typescript.default.ScriptSnapshot.fromString(diskContent);
325
+ },
326
+ getCurrentDirectory: () => workspaceRoot,
327
+ getCompilationSettings: () => primaryProject.options,
328
+ getDefaultLibFileName: (options) => import_typescript.default.getDefaultLibFilePath(options),
329
+ fileExists: import_typescript.default.sys.fileExists,
330
+ readFile: import_typescript.default.sys.readFile,
331
+ readDirectory: import_typescript.default.sys.readDirectory,
332
+ directoryExists: import_typescript.default.sys.directoryExists,
333
+ getDirectories: import_typescript.default.sys.getDirectories,
334
+ useCaseSensitiveFileNames: () => import_typescript.default.sys.useCaseSensitiveFileNames,
335
+ getProjectVersion: () => String(projectVersion),
336
+ resolveModuleNames: (moduleNames, containingFile) => {
337
+ const owningProject = getOwningProject(containingFile);
338
+ return moduleNames.map((moduleName) => {
339
+ const ownerResolution = import_typescript.default.resolveModuleName(
340
+ moduleName,
341
+ containingFile,
342
+ owningProject.options,
343
+ moduleResolutionHost,
344
+ owningProject.moduleResolutionCache
345
+ ).resolvedModule;
346
+ if (ownerResolution) {
347
+ return ownerResolution;
348
+ }
349
+ if (owningProject.id === primaryProject.id) {
350
+ return void 0;
351
+ }
352
+ return import_typescript.default.resolveModuleName(
353
+ moduleName,
354
+ containingFile,
355
+ primaryProject.options,
356
+ moduleResolutionHost,
357
+ primaryProject.moduleResolutionCache
358
+ ).resolvedModule;
359
+ });
360
+ }
361
+ };
362
+ const languageService = import_typescript.default.createLanguageService(
363
+ host,
364
+ import_typescript.default.createDocumentRegistry()
365
+ );
366
+ return {
367
+ updateFile(filePath, content) {
368
+ const canonicalFilePath = canonicalPath(filePath);
369
+ const currentVersion = inMemoryFiles.get(canonicalFilePath)?.version ?? 0;
370
+ inMemoryFiles.set(canonicalFilePath, {
371
+ version: currentVersion + 1,
372
+ content
373
+ });
374
+ if (!rootFileNames.has(canonicalFilePath)) {
375
+ rootFileNames.add(canonicalFilePath);
376
+ }
377
+ projectVersion += 1;
378
+ },
379
+ closeFile(filePath) {
380
+ const canonicalFilePath = canonicalPath(filePath);
381
+ inMemoryFiles.delete(canonicalFilePath);
382
+ projectVersion += 1;
383
+ },
384
+ getProgram() {
385
+ return languageService.getProgram() ?? null;
386
+ },
387
+ getSemanticDiagnostics(filePath) {
388
+ const canonicalFilePath = canonicalPath(filePath);
389
+ return languageService.getSemanticDiagnostics(canonicalFilePath);
390
+ },
391
+ getDefinition(filePath, position) {
392
+ const canonicalFilePath = canonicalPath(filePath);
393
+ return languageService.getDefinitionAtPosition(
394
+ canonicalFilePath,
395
+ position
396
+ );
397
+ },
398
+ dispose() {
399
+ languageService.dispose();
400
+ }
401
+ };
402
+ }
403
+
404
+ // type-analyzer.ts
405
+ function isCustomComponent(node) {
406
+ const text = node.getText();
407
+ return text.length > 0 && text[0] !== text[0].toLowerCase();
408
+ }
409
+ function canonicalPath2(value) {
410
+ const resolved = import_node_path2.default.resolve(value);
411
+ try {
412
+ return import_node_fs2.realpathSync.native(resolved);
413
+ } catch {
414
+ return resolved;
415
+ }
416
+ }
417
+ function parseManagedTsconfigPaths(rawConfig) {
418
+ if (!rawConfig || typeof rawConfig !== "object" || Array.isArray(rawConfig)) {
419
+ return [];
420
+ }
421
+ const metadata = rawConfig.tempobook;
422
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
423
+ return [];
424
+ }
425
+ const managedPaths = metadata.managedTsconfigPaths;
426
+ if (!Array.isArray(managedPaths)) {
427
+ return [];
428
+ }
429
+ return managedPaths.filter(
430
+ (entry) => typeof entry === "string" && entry.trim().length > 0
431
+ );
432
+ }
433
+ function parseProjectReferenceTsconfigPaths(references, configDir) {
434
+ if (!references || references.length === 0) {
435
+ return [];
436
+ }
437
+ const entries = [];
438
+ for (const reference of references) {
439
+ const referencePath = reference.path;
440
+ if (!referencePath) {
441
+ continue;
442
+ }
443
+ const resolvedPath = import_node_path2.default.resolve(configDir, referencePath);
444
+ const tsconfigPath = resolvedPath.endsWith(".json") ? resolvedPath : import_node_path2.default.join(resolvedPath, "tsconfig.json");
445
+ entries.push(tsconfigPath);
446
+ }
447
+ return entries;
448
+ }
449
+ function buildWorkspaceProjects(root, configPath, parsedConfig, rawConfig) {
450
+ const configDir = import_node_path2.default.dirname(configPath);
451
+ const projects = [
452
+ {
453
+ id: "root",
454
+ rootDir: root,
455
+ tsconfigPath: configPath,
456
+ priority: 0
457
+ }
458
+ ];
459
+ const seenTsconfigPaths = /* @__PURE__ */ new Set([canonicalPath2(configPath)]);
460
+ const referencedTsconfigPaths = parseProjectReferenceTsconfigPaths(
461
+ parsedConfig.projectReferences,
462
+ configDir
463
+ );
464
+ const managedTsconfigPaths = parseManagedTsconfigPaths(rawConfig).map(
465
+ (entry) => import_node_path2.default.resolve(configDir, entry)
466
+ );
467
+ const candidateTsconfigPaths = [
468
+ ...managedTsconfigPaths,
469
+ ...referencedTsconfigPaths
470
+ ];
471
+ for (const candidatePath of candidateTsconfigPaths) {
472
+ const normalizedPath = canonicalPath2(candidatePath);
473
+ if (seenTsconfigPaths.has(normalizedPath)) {
474
+ continue;
475
+ }
476
+ if (!import_typescript2.default.sys.fileExists(normalizedPath)) {
477
+ continue;
478
+ }
479
+ seenTsconfigPaths.add(normalizedPath);
480
+ projects.push({
481
+ id: `external-${projects.length}`,
482
+ rootDir: import_node_path2.default.dirname(normalizedPath),
483
+ tsconfigPath: normalizedPath,
484
+ priority: 0
485
+ });
486
+ }
487
+ return projects;
488
+ }
489
+ function createTypeAnalyzer(root) {
490
+ const configPath = import_typescript2.default.findConfigFile(
491
+ root,
492
+ import_typescript2.default.sys.fileExists,
493
+ "tsconfig.json"
494
+ );
495
+ if (!configPath) return null;
496
+ const configFile = import_typescript2.default.readConfigFile(configPath, import_typescript2.default.sys.readFile);
497
+ if (configFile.error) return null;
498
+ const parsedConfig = import_typescript2.default.parseJsonConfigFileContent(
499
+ configFile.config,
500
+ import_typescript2.default.sys,
501
+ root
502
+ );
503
+ const workspaceProjects = buildWorkspaceProjects(
504
+ root,
505
+ configPath,
506
+ parsedConfig,
507
+ configFile.config
508
+ );
509
+ const workspaceProjectRoots = workspaceProjects.map(
510
+ (project) => canonicalPath2(project.rootDir)
511
+ );
512
+ const workspaceService = createTsWorkspaceService({
513
+ workspaceRoot: root,
514
+ primaryProjectId: "root",
515
+ projects: workspaceProjects
516
+ });
517
+ let cssPropertiesType;
518
+ function resolveCSSPropertiesType(checker, sourceFile) {
519
+ if (cssPropertiesType !== void 0) return cssPropertiesType;
520
+ try {
521
+ let jsxNs = checker.resolveName(
522
+ "JSX",
523
+ sourceFile,
524
+ import_typescript2.default.SymbolFlags.Namespace,
525
+ false
526
+ );
527
+ if (!jsxNs) {
528
+ const program = workspaceService.getProgram();
529
+ const compilerOptions = program?.getCompilerOptions();
530
+ const jsxImportSource = compilerOptions?.jsxImportSource ?? "react";
531
+ const resolved = import_typescript2.default.resolveModuleName(
532
+ `${jsxImportSource}/jsx-runtime`,
533
+ sourceFile.fileName,
534
+ compilerOptions,
535
+ import_typescript2.default.sys
536
+ );
537
+ if (resolved.resolvedModule) {
538
+ const runtimeFile = program?.getSourceFile(
539
+ resolved.resolvedModule.resolvedFileName
540
+ );
541
+ if (runtimeFile) {
542
+ const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);
543
+ if (runtimeSymbol) {
544
+ const exports2 = checker.getExportsOfModule(runtimeSymbol);
545
+ jsxNs = exports2.find((s) => s.name === "JSX");
546
+ }
547
+ }
548
+ }
549
+ }
550
+ if (!jsxNs) {
551
+ cssPropertiesType = null;
552
+ return null;
553
+ }
554
+ const intrinsicSym = checker.getExportsOfModule(jsxNs).find((s) => s.name === "IntrinsicElements") ?? checker.getDeclaredTypeOfSymbol(jsxNs).getProperty("IntrinsicElements");
555
+ if (!intrinsicSym) {
556
+ cssPropertiesType = null;
557
+ return null;
558
+ }
559
+ const divSym = checker.getDeclaredTypeOfSymbol(intrinsicSym).getProperty("div");
560
+ if (!divSym) {
561
+ cssPropertiesType = null;
562
+ return null;
563
+ }
564
+ const styleSym = checker.getTypeOfSymbol(divSym).getProperty("style");
565
+ if (!styleSym) {
566
+ cssPropertiesType = null;
567
+ return null;
568
+ }
569
+ const styleType = checker.getTypeOfSymbol(styleSym);
570
+ if (styleType.isUnion()) {
571
+ const nonUndefined = styleType.types.find(
572
+ (t) => !(t.flags & import_typescript2.default.TypeFlags.Undefined)
573
+ );
574
+ cssPropertiesType = nonUndefined ?? null;
575
+ } else {
576
+ cssPropertiesType = styleType;
577
+ }
578
+ } catch {
579
+ cssPropertiesType = null;
580
+ }
581
+ return cssPropertiesType;
582
+ }
583
+ let reactNodeType;
584
+ function resolveReactNodeType(checker, sourceFile) {
585
+ if (reactNodeType !== void 0) return reactNodeType;
586
+ try {
587
+ let jsxNs = checker.resolveName(
588
+ "JSX",
589
+ sourceFile,
590
+ import_typescript2.default.SymbolFlags.Namespace,
591
+ false
592
+ );
593
+ if (!jsxNs) {
594
+ const program = workspaceService.getProgram();
595
+ const compilerOptions = program?.getCompilerOptions();
596
+ const jsxImportSource = compilerOptions?.jsxImportSource ?? "react";
597
+ const resolved = import_typescript2.default.resolveModuleName(
598
+ `${jsxImportSource}/jsx-runtime`,
599
+ sourceFile.fileName,
600
+ compilerOptions,
601
+ import_typescript2.default.sys
602
+ );
603
+ if (resolved.resolvedModule) {
604
+ const runtimeFile = program?.getSourceFile(
605
+ resolved.resolvedModule.resolvedFileName
606
+ );
607
+ if (runtimeFile) {
608
+ const runtimeSymbol = checker.getSymbolAtLocation(runtimeFile);
609
+ if (runtimeSymbol) {
610
+ const exports2 = checker.getExportsOfModule(runtimeSymbol);
611
+ jsxNs = exports2.find((s) => s.name === "JSX");
612
+ }
613
+ }
614
+ }
615
+ }
616
+ if (!jsxNs) {
617
+ reactNodeType = null;
618
+ return null;
619
+ }
620
+ const intrinsicSym = checker.getExportsOfModule(jsxNs).find((s) => s.name === "IntrinsicElements") ?? checker.getDeclaredTypeOfSymbol(jsxNs).getProperty("IntrinsicElements");
621
+ if (!intrinsicSym) {
622
+ reactNodeType = null;
623
+ return null;
624
+ }
625
+ const divSym = checker.getDeclaredTypeOfSymbol(intrinsicSym).getProperty("div");
626
+ if (!divSym) {
627
+ reactNodeType = null;
628
+ return null;
629
+ }
630
+ const childrenSym = checker.getTypeOfSymbol(divSym).getProperty("children");
631
+ if (!childrenSym) {
632
+ reactNodeType = null;
633
+ return null;
634
+ }
635
+ const childrenType = checker.getTypeOfSymbol(childrenSym);
636
+ if (childrenType.isUnion()) {
637
+ const nonUndefined = childrenType.types.find(
638
+ (t) => !(t.flags & import_typescript2.default.TypeFlags.Undefined)
639
+ );
640
+ reactNodeType = nonUndefined ?? null;
641
+ } else {
642
+ reactNodeType = childrenType;
643
+ }
644
+ } catch {
645
+ reactNodeType = null;
646
+ }
647
+ return reactNodeType;
648
+ }
649
+ return {
650
+ analyzeFileTypes(filePath, source) {
651
+ const canonicalFilePath = canonicalPath2(filePath);
652
+ const belongsToWorkspace = workspaceProjectRoots.some(
653
+ (projectRoot) => canonicalFilePath === projectRoot || canonicalFilePath.startsWith(`${projectRoot}${import_node_path2.default.sep}`)
654
+ );
655
+ if (!belongsToWorkspace) {
656
+ return null;
657
+ }
658
+ workspaceService.updateFile(filePath, source);
659
+ const program = workspaceService.getProgram();
660
+ if (!program) return null;
661
+ const sourceFile = program.getSourceFile(filePath);
662
+ if (!sourceFile) return null;
663
+ const checker = program.getTypeChecker();
664
+ const cssProps = resolveCSSPropertiesType(checker, sourceFile);
665
+ const result = /* @__PURE__ */ new Map();
666
+ function visit(node) {
667
+ if ((import_typescript2.default.isJsxOpeningElement(node) || import_typescript2.default.isJsxSelfClosingElement(node)) && isCustomComponent(node.tagName)) {
668
+ const position = node.getStart(sourceFile);
669
+ const attrsType = checker.getContextualType(node.attributes);
670
+ let supportsStyle = false;
671
+ let supportsClassName = false;
672
+ let supportsChildren = false;
673
+ if (attrsType) {
674
+ const classNameProp = attrsType.getProperty("className");
675
+ if (classNameProp) {
676
+ const propType = checker.getTypeOfSymbol(classNameProp);
677
+ supportsClassName = checker.isTypeAssignableTo(
678
+ checker.getStringType(),
679
+ propType
680
+ );
681
+ }
682
+ const styleProp = attrsType.getProperty("style");
683
+ if (styleProp && cssProps) {
684
+ let propType = checker.getTypeOfSymbol(styleProp);
685
+ if (propType.isUnion()) {
686
+ const nonUndefined = propType.types.find(
687
+ (t) => !(t.flags & import_typescript2.default.TypeFlags.Undefined)
688
+ );
689
+ if (nonUndefined) propType = nonUndefined;
690
+ }
691
+ supportsStyle = checker.isTypeAssignableTo(cssProps, propType);
692
+ }
693
+ const reactNode = resolveReactNodeType(checker, sourceFile);
694
+ const childrenProp = attrsType.getProperty("children");
695
+ if (childrenProp && reactNode) {
696
+ let propType = checker.getTypeOfSymbol(childrenProp);
697
+ if (propType.isUnion()) {
698
+ const nonUndefined = propType.types.find(
699
+ (t) => !(t.flags & import_typescript2.default.TypeFlags.Undefined)
700
+ );
701
+ if (nonUndefined) propType = nonUndefined;
702
+ }
703
+ supportsChildren = checker.isTypeAssignableTo(
704
+ reactNode,
705
+ propType
706
+ );
707
+ }
708
+ }
709
+ result.set(position, { supportsStyle, supportsClassName, supportsChildren });
710
+ }
711
+ import_typescript2.default.forEachChild(node, visit);
712
+ }
713
+ visit(sourceFile);
714
+ return result;
715
+ }
716
+ };
717
+ }
718
+
719
+ // nextjs-loader.ts
720
+ var ROOT_META_NAME = "tempo-project-root";
721
+ var HTML_VOID_ELEMENTS = /* @__PURE__ */ new Set([
722
+ "area",
723
+ "base",
724
+ "br",
725
+ "col",
726
+ "embed",
727
+ "hr",
728
+ "img",
729
+ "input",
730
+ "link",
731
+ "meta",
732
+ "param",
733
+ "source",
734
+ "track",
735
+ "wbr"
736
+ ]);
737
+ var cachedCanonicalRoot = null;
738
+ var cachedTypeAnalyzer = null;
739
+ var cachedUserComputeProps;
740
+ var cachedComputeModulePath = null;
741
+ function _resetLoaderState() {
742
+ cachedCanonicalRoot = null;
743
+ cachedTypeAnalyzer = null;
744
+ cachedUserComputeProps = void 0;
745
+ cachedComputeModulePath = null;
746
+ }
747
+ function isIntrinsicElement(tagName) {
748
+ return tagName.length > 0 && tagName[0] === tagName[0].toLowerCase();
749
+ }
750
+ function defaultComputeAnnotatedProps(info, filepath, modifiedtsMs) {
751
+ return {
752
+ "data-tempo-filepath": filepath,
753
+ "data-tempo-position": info.element.openingElement.start,
754
+ "data-tempo-modifiedts": modifiedtsMs
755
+ };
756
+ }
757
+ function stripQueryAndHash(path3) {
758
+ const queryIdx = path3.indexOf("?");
759
+ const hashIdx = path3.indexOf("#");
760
+ let end = path3.length;
761
+ if (queryIdx !== -1) end = Math.min(end, queryIdx);
762
+ if (hashIdx !== -1) end = Math.min(end, hashIdx);
763
+ return path3.slice(0, end);
764
+ }
765
+ function resolveCanonicalRoot(rootContext) {
766
+ try {
767
+ return import_node_fs3.realpathSync.native(rootContext);
768
+ } catch {
769
+ return rootContext;
770
+ }
771
+ }
772
+ function isInNodeModules(path3) {
773
+ return path3.includes(`${import_node_path3.sep}node_modules${import_node_path3.sep}`);
774
+ }
775
+ function findFirstJSXElement(program, tagName) {
776
+ let result = null;
777
+ walk(program, {
778
+ JSXElement(node) {
779
+ if (result) return;
780
+ const element = node;
781
+ if (getTagName(element.openingElement.name) === tagName) {
782
+ result = element;
783
+ }
784
+ }
785
+ });
786
+ return result;
787
+ }
788
+ function hasRootMetaChild(headElement) {
789
+ for (const child of headElement.children ?? []) {
790
+ if (child.type !== "JSXElement") continue;
791
+ const childTag = getTagName(child.openingElement.name);
792
+ if (childTag !== "meta") continue;
793
+ for (const attr of child.openingElement.attributes ?? []) {
794
+ if (attr.type !== "JSXAttribute") continue;
795
+ if (getTagName(attr.name) !== "name") continue;
796
+ const value = attr.value;
797
+ if (value && value.type === "Literal" && value.value === ROOT_META_NAME) {
798
+ return true;
799
+ }
800
+ }
801
+ }
802
+ return false;
803
+ }
804
+ function injectFirstChildMarkup(source, element, childMarkup) {
805
+ const opening = element.openingElement;
806
+ if (!opening.selfClosing) {
807
+ const insertPos = opening.end;
808
+ return source.slice(0, insertPos) + childMarkup + source.slice(insertPos);
809
+ }
810
+ const tagName = getTagName(opening.name);
811
+ const reopened = source.slice(opening.start, opening.end).replace(/\s*\/>$/, ">");
812
+ return source.slice(0, opening.start) + `${reopened}${childMarkup}</${tagName}>` + source.slice(opening.end);
813
+ }
814
+ function injectRootMetaIntoSource(source, filename, root) {
815
+ let parseResult;
816
+ try {
817
+ parseResult = (0, import_oxc_parser3.parseSync)(filename, source);
818
+ } catch {
819
+ return source;
820
+ }
821
+ const metaTag = `<meta name="${ROOT_META_NAME}" content={${JSON.stringify(root)}} />`;
822
+ const headElement = findFirstJSXElement(parseResult.program, "head");
823
+ if (headElement) {
824
+ if (hasRootMetaChild(headElement)) return source;
825
+ return injectFirstChildMarkup(source, headElement, metaTag);
826
+ }
827
+ const htmlElement = findFirstJSXElement(parseResult.program, "html");
828
+ if (htmlElement) {
829
+ return injectFirstChildMarkup(
830
+ source,
831
+ htmlElement,
832
+ `<head>${metaTag}</head>`
833
+ );
834
+ }
835
+ return source;
836
+ }
837
+ function injectRootMetaIntoAnnotatedSource(annotatedSource, filename, root) {
838
+ return injectRootMetaIntoSource(annotatedSource, filename, root);
839
+ }
840
+ function loadUserComputeProps(modulePath, canonicalRoot) {
841
+ const resolved = (0, import_node_path3.resolve)(canonicalRoot, modulePath);
842
+ const requireFromRoot = (0, import_node_module.createRequire)(`${canonicalRoot}/__tempo_loader__.js`);
843
+ const mod = requireFromRoot(resolved);
844
+ const fn = mod && (mod.default ?? mod);
845
+ if (typeof fn !== "function") {
846
+ return null;
847
+ }
848
+ return fn;
849
+ }
850
+ function readOptions() {
851
+ if (typeof this.getOptions === "function") {
852
+ return this.getOptions() ?? {};
853
+ }
854
+ if (typeof this.query === "string") {
855
+ return {};
856
+ }
857
+ return this.query ?? {};
858
+ }
859
+ function nextjsLoader(source) {
860
+ this.cacheable?.(true);
861
+ if (!process.env.TEMPO) return source;
862
+ const cleanPath = stripQueryAndHash(this.resourcePath ?? "");
863
+ if (!/\.(tsx|jsx)$/.test(cleanPath)) return source;
864
+ if (isInNodeModules(cleanPath)) return source;
865
+ const options = readOptions.call(this);
866
+ try {
867
+ if (cachedCanonicalRoot === null) {
868
+ cachedCanonicalRoot = resolveCanonicalRoot(this.rootContext);
869
+ }
870
+ const canonicalRoot = cachedCanonicalRoot;
871
+ if (cachedTypeAnalyzer === null) {
872
+ try {
873
+ cachedTypeAnalyzer = createTypeAnalyzer(canonicalRoot);
874
+ } catch {
875
+ cachedTypeAnalyzer = { analyzeFileTypes: () => null };
876
+ }
877
+ }
878
+ const userModule = options.computeAnnotatedPropsModule;
879
+ if (userModule && userModule !== cachedComputeModulePath) {
880
+ try {
881
+ cachedUserComputeProps = loadUserComputeProps(userModule, canonicalRoot);
882
+ } catch {
883
+ cachedUserComputeProps = null;
884
+ }
885
+ cachedComputeModulePath = userModule;
886
+ } else if (cachedUserComputeProps === void 0) {
887
+ cachedUserComputeProps = null;
888
+ }
889
+ const userComputeProps = cachedUserComputeProps;
890
+ const filepath = (0, import_node_path3.relative)(canonicalRoot, cleanPath);
891
+ const modifiedtsMs = Math.trunc((0, import_node_fs3.statSync)(cleanPath).mtimeMs);
892
+ const typeInfo = cachedTypeAnalyzer?.analyzeFileTypes(
893
+ cleanPath,
894
+ source
895
+ ) ?? null;
896
+ const annotated = annotateFile(source, cleanPath, (info) => {
897
+ const compute = userComputeProps ?? defaultComputeAnnotatedProps;
898
+ const userProps = compute(info, filepath, modifiedtsMs);
899
+ if (isIntrinsicElement(info.tagName)) {
900
+ return {
901
+ ...userProps,
902
+ "data-tempo-supports-children": !HTML_VOID_ELEMENTS.has(info.tagName)
903
+ };
904
+ }
905
+ const support = typeInfo?.get(info.element.openingElement.start);
906
+ return {
907
+ ...userProps,
908
+ "data-tempo-supports-style": support?.supportsStyle ?? false,
909
+ "data-tempo-supports-classname": support?.supportsClassName ?? false,
910
+ "data-tempo-supports-children": support?.supportsChildren ?? false
911
+ };
912
+ });
913
+ let finalSource = annotated.annotatedSource;
914
+ if (options.autoInjectRootMeta !== false) {
915
+ finalSource = injectRootMetaIntoAnnotatedSource(
916
+ finalSource,
917
+ cleanPath,
918
+ canonicalRoot
919
+ );
920
+ }
921
+ if (finalSource === source) return source;
922
+ return finalSource;
923
+ } catch {
924
+ return source;
925
+ }
926
+ }
927
+ var nextjs_loader_default = nextjsLoader;
928
+ // Annotate the CommonJS export names for ESM import in node:
929
+ 0 && (module.exports = {
930
+ _resetLoaderState,
931
+ injectRootMetaIntoAnnotatedSource,
932
+ injectRootMetaIntoSource,
933
+ nextjsLoader
934
+ });
935
+ //# sourceMappingURL=nextjs-loader.cjs.map