-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathtypescript.mjs
More file actions
956 lines (802 loc) · 30.4 KB
/
typescript.mjs
File metadata and controls
956 lines (802 loc) · 30.4 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { processData } from './data-processor.mjs';
import { descriptionStringForTypeScript } from './shared-helpers.mjs';
import { applyPatches } from './patch.mjs';
import { strandsBuiltinFunctions as builtInGLSLFunctions } from '../src/strands/strands_builtins.js';
import { DataType } from '../src/strands/ir_types.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Clear existing types directory and recreate it
const typesDir = path.join(__dirname, '../types');
if (fs.existsSync(typesDir)) {
fs.rmSync(typesDir, { recursive: true, force: true });
}
fs.mkdirSync(typesDir, { recursive: true });
const rawData = JSON.parse(fs.readFileSync(path.join(__dirname, '../docs/data.json')));
// Pre-build constants lookup
import { getAllEntries } from './shared-helpers.mjs';
const allRawData = getAllEntries(rawData);
const constantsLookup = new Set();
const typedefs = {};
const mutableProperties = new Set(['disableFriendlyErrors']); // Properties that should be mutable, not constants
allRawData.forEach(entry => {
if (entry.kind === 'constant' || entry.kind === 'typedef') {
constantsLookup.add(entry.name);
if (entry.kind === 'typedef') {
// Store the full entry so we have access to both .type and .properties
typedefs[entry.name] = entry;
}
}
});
// Process strands functions to extract p5 methods
function processStrandsFunctions() {
const strandsMethods = [
{
name: 'instanceID',
overloads: [{
params: [],
return: {
type: { type: 'NameExpression', name: 'any' } // Return 'any' for strands nodes
}
}],
description: `Returns the ID when drawing many instances`,
static: false
},
{
name: 'discard',
overloads: [{
params: [],
}],
description: `Discards the current pixel`,
static: false
},
{
name: 'getTexture',
overloads: [{
params: [
{
name: 'tex',
type: { type: 'NameExpression', name: 'any' },
optional: false,
},
{
name: 'coord',
type: { type: 'NameExpression', name: 'any' },
optional: false,
},
],
return: {
type: { type: 'NameExpression', name: 'any' } // Return 'any' for strands nodes
}
}],
}
];
// Add ALL GLSL builtin functions (both isp5Function: true and false)
for (const [functionName, overloads] of Object.entries(builtInGLSLFunctions)) {
// Create method definition with simplified any types for all overloads
const method = {
name: functionName,
overloads: overloads.map(overload => ({
params: overload.params.map((paramType, index) => ({
name: `param${index}`,
type: { type: 'NameExpression', name: 'any' }, // Use 'any' for strands node types
optional: false
})),
return: {
type: { type: 'NameExpression', name: 'any' } // Return 'any' for strands nodes
}
})),
description: `GLSL built-in function ${functionName}`,
static: false
};
strandsMethods.push(method);
}
// Add uniform functions: uniformFloat, uniformVec2, etc.
const typeMethods = [];
for (const type in DataType) {
if (type === 'defer' || type === 'assign_on_use') {
continue;
}
const typeInfo = DataType[type];
let pascalTypeName;
const typeAliases = [];
if (/^[ib]vec/.test(typeInfo.fnName)) {
pascalTypeName = typeInfo.fnName
.slice(0, 2).toUpperCase()
+ typeInfo.fnName
.slice(2)
.toLowerCase();
typeAliases.push(pascalTypeName.replace('Vec', 'Vector'));
} else {
pascalTypeName = typeInfo.fnName.charAt(0).toUpperCase()
+ typeInfo.fnName.slice(1);
if (pascalTypeName === 'Sampler2D') {
typeAliases.push('Texture')
} else if (/^vec/.test(typeInfo.fnName)) {
typeAliases.push(pascalTypeName.replace('Vec', 'Vector'));
}
}
typeMethods.push(...[pascalTypeName, ...typeAliases].flatMap((typeName) => [
{
name: `uniform${typeName}`,
overloads: [{
params: [
{
name: 'defaultValue',
type: { type: 'NameExpression', name: 'any' },
optional: true
}
],
return: {
type: { type: 'NameExpression', name: 'any' }
}
}],
description: `Create a ${pascalTypeName} uniform variable`,
static: false
},
...['varying', 'shared'].map((prefix) => ({
name: `${prefix}${typeName}`,
overloads: [{
params: [],
return: {
type: { type: 'NameExpression', name: 'any' }
}
}],
description: `Create a shared ${pascalTypeName} to pass data between hooks`,
static: false
}))
]));
}
// Add type casting functions (DataType constructor functions)
const typeCastingMethods = [];
for (const type in DataType) {
if (type === 'defer' || !DataType[type].fnName) {
continue;
}
const typeInfo = DataType[type];
const castingMethod = {
name: typeInfo.fnName,
overloads: [{
params: [
{
name: 'value',
type: { type: 'NameExpression', name: 'any' },
optional: false
}
],
return: {
type: { type: 'NameExpression', name: 'any' }
}
}],
description: `GLSL type constructor for ${typeInfo.fnName}`,
static: false
};
typeCastingMethods.push(castingMethod);
}
return [...strandsMethods, ...typeMethods, ...typeCastingMethods];
}
// TypeScript-specific type conversion from raw type objects
function convertTypeToTypeScript(typeNode, options = {}) {
if (!typeNode) return 'any';
// Validate that typeNode is always an object
if (typeof typeNode !== 'object' || Array.isArray(typeNode)) {
throw new Error(`convertTypeToTypeScript expects an object, got: ${typeof typeNode} - ${JSON.stringify(typeNode)}`);
}
const { currentClass = null, isInsideNamespace = false, inGlobalMode = false, isConstantDef = false } = options;
switch (typeNode.type) {
case 'NameExpression': {
const typeName = typeNode.name;
// Handle primitive types
const primitiveTypes = {
'String': 'string',
'Number': 'number',
'Integer': 'number',
'Boolean': 'boolean',
'Void': 'void',
'Object': 'object',
'Any': 'any',
'Array': 'any[]',
'Promise': 'Promise<any>',
'Function': 'Function',
'HTMLElement': 'HTMLElement',
'Event': 'Event',
'Request': 'Request'
};
if (primitiveTypes[typeName]) {
return primitiveTypes[typeName];
}
// Handle self-referential types within the same class
if (currentClass && (typeName === `p5.${currentClass}` || typeName === currentClass)) {
return currentClass;
}
// If we're inside the p5 namespace, remove p5. prefix from other p5 classes
if (isInsideNamespace && typeName.startsWith('p5.')) {
if (inGlobalMode) {
return 'P5.' + typeName.substring(3);
} else {
return typeName.substring(3);
}
}
// Check if this is a p5 constant/typedef
if (constantsLookup.has(typeName)) {
const typedefEntry = typedefs[typeName];
// Use interface name for object-shaped typedefs in all contexts
if (typedefEntry && hasTypedefProperties(typedefEntry)) {
if (inGlobalMode) {
return `P5.${typeName}`;
} else if (isInsideNamespace) {
return typeName;
} else {
return `p5.${typeName}`;
}
}
// Fallback to typeof or primitive resolution for alias-style typedefs
if (inGlobalMode) {
return `typeof P5.${typeName}`;
} else if (typedefEntry) {
if (isConstantDef) {
return convertTypeToTypeScript(typedefEntry.type, options);
} else {
return `typeof p5.${typeName}`;
}
} else {
return `Symbol`;
}
}
return typeName;
}
case 'TypeApplication': {
const baseTypeName = typeNode.expression.name;
if (baseTypeName === 'Array' && typeNode.applications.length === 1) {
const innerType = convertTypeToTypeScript(typeNode.applications[0], options);
return `${innerType}[]`;
}
// For generic types, use the base type name directly to avoid double conversion
const typeParams = typeNode.applications
.map(app => convertTypeToTypeScript(app, options))
.join(', ');
return `${baseTypeName}<${typeParams}>`;
}
case 'UnionType': {
const unionTypes = typeNode.elements
.map(el => convertTypeToTypeScript(el, options))
.join(' | ');
return unionTypes;
}
case 'OptionalType':
return convertTypeToTypeScript(typeNode.expression, options);
case 'AllLiteral':
return 'any';
case 'RecordType':
return 'object';
case 'NumericLiteralType':
return `${typeNode.value}`;
case 'StringLiteralType':
return `'${typeNode.value}'`;
case 'NullLiteral':
return 'null';
case 'UndefinedLiteral':
return 'undefined';
case 'ArrayType': {
const innerTypes = typeNode.elements.map(e => convertTypeToTypeScript(e, options));
return `[${innerTypes.join(', ')}]`;
}
case 'RestType':
return `${convertTypeToTypeScript(typeNode.expression, options)}[]`;
case 'FunctionType': {
const params = (typeNode.params || [])
.map((param, i) => {
const paramType = convertTypeToTypeScript(param, options);
return `arg${i}: ${paramType}`;
})
.join(', ');
const returnType = typeNode.result
? convertTypeToTypeScript(typeNode.result, options)
: 'void';
return `(${params}) => ${returnType}`;
}
default:
return 'any';
}
}
// Check if typedef represents a real object shape
function hasTypedefProperties(typedefEntry) {
if (!Array.isArray(typedefEntry.properties) || typedefEntry.properties.length === 0) {
return false;
}
// Reject self-referential single-property typedefs
if (
typedefEntry.properties.length === 1 &&
typedefEntry.properties[0].name === typedefEntry.name
) {
return false;
}
return true;
}
// Convert JSDoc FunctionType into a TypeScript function signature string
function convertFunctionTypeForInterface(typeNode, options) {
const params = (typeNode.params || [])
.map((param, i) => {
let typeObj;
let paramName;
if (param.type === 'ParameterType') {
typeObj = param.expression;
paramName = param.name ?? `p${i}`;
} else if (typeof param.type === 'object' && param.type !== null) {
typeObj = param.type;
paramName = param.name ?? `p${i}`;
} else {
// param itself is a plain type node
typeObj = param;
paramName = `p${i}`;
}
const paramType = convertTypeToTypeScript(typeObj, options);
return `${paramName}: ${paramType}`;
})
.join(', ');
const returnType = typeNode.result
? convertTypeToTypeScript(typeNode.result, options)
: 'void';
// Normalise 'undefined' return to 'void' for idiomatic TypeScript
const normalisedReturn = returnType === 'undefined' ? 'void' : returnType;
return `(${params}) => ${normalisedReturn}`;
}
// Generate a TypeScript interface from a typedef with @property fields
function generateTypedefInterface(name, typedefEntry, options = {}, indent = 2) {
const pad = ' '.repeat(indent);
const innerPad = ' '.repeat(indent + 2);
let output = '';
if (typedefEntry.description) {
const descStr = typeof typedefEntry.description === 'string'
? typedefEntry.description
: descriptionStringForTypeScript(typedefEntry.description);
if (descStr) {
output += `${pad}/**\n`;
output += formatJSDocComment(descStr, indent) + '\n';
output += `${pad} */\n`;
}
}
output += `${pad}interface ${name} {\n`;
for (const prop of typedefEntry.properties) {
// Each prop: { name, type, description, optional }
const propName = prop.name;
const rawType = prop.type;
const isOptional = prop.optional || rawType?.type === 'OptionalType';
const optMark = isOptional ? '?' : '';
if (prop.description) {
const propDescStr = typeof prop.description === 'string'
? prop.description.trim()
: descriptionStringForTypeScript(prop.description);
if (propDescStr) {
output += `${innerPad}/** ${propDescStr} */\n`;
}
}
if (rawType?.type === 'FunctionType') {
// Render FunctionType properties as method signatures instead of arrow properties
const sig = convertFunctionTypeForInterface(rawType, options);
const arrowIdx = sig.lastIndexOf('=>');
const paramsPart = sig.substring(0, arrowIdx).trim();
const retPart = sig.substring(arrowIdx + 2).trim();
output += `${innerPad}${propName}${paramsPart}: ${retPart};\n`;
} else {
const tsType = rawType ? convertTypeToTypeScript(rawType, options) : 'any';
output += `${innerPad}${propName}${optMark}: ${tsType};\n`;
}
}
output += `${pad}}\n\n`;
return output;
}
// Strategy for TypeScript output
const typescriptStrategy = {
shouldSkipEntry: (entry, context) => {
// Skip Foundation module for TypeScript output
return context.module === 'Foundation';
},
processDescription: (desc) => descriptionStringForTypeScript(desc),
processType: (type, param) => {
// Return an object with the original type preserved
// This matches the expected data structure from the data processor
const result = {
type: type, // Keep the original raw type object
originalType: type // Also store it here for clarity
};
// Extract optional flag from OptionalType
if (type?.type === 'OptionalType') {
result.optional = true;
}
// Extract rest flag from RestType
if (type?.type === 'RestType') {
result.rest = true;
}
// Preserve properties array for nested object parameters
if (param && param.properties) {
result.properties = param.properties;
}
return result;
}
};
const processed = processData(rawData, typescriptStrategy);
function normalizeIdentifier(name) {
return (
'0123456789'.includes(name[0]) ||
name === 'class'
) ? '$' + name : name;
}
function formatJSDocComment(text, indentLevel = 0) {
if (!text) return '';
const indent = ' '.repeat(indentLevel);
const lines = text
.split('\n')
.map(line => line.trim())
.reduce((acc, line) => {
if (acc.length === 0 && line === '') return acc;
if (acc.length > 0 && line === '' && acc[acc.length - 1] === '') return acc;
acc.push(line);
return acc;
}, [])
.filter((line, i, arr) => i < arr.length - 1 || line !== '');
return lines
.map(line => `${indent} * ${line}`)
.join('\n');
}
function generateObjectInterface(param, allParams, options = {}) {
// Check if this is an object parameter (either required or optional)
const isObjectParam = param.type && (
(param.type.type === 'OptionalType' && param.type.expression?.name === 'Object') ||
(param.type.type === 'NameExpression' && param.type.name === 'Object')
);
if (!isObjectParam || !param.name) {
return null;
}
let nestedParams = [];
// First, check if the parameter has a properties array (JSDoc properties field)
if (param.properties && Array.isArray(param.properties)) {
nestedParams = param.properties.filter(prop =>
prop.name && prop.name.startsWith(param.name + '.')
);
}
// Fallback: Look for nested parameters with dot notation in allParams
if (nestedParams.length === 0) {
nestedParams = allParams.filter(p =>
p.name && p.name.startsWith(param.name + '.') && p.name !== param.name
);
}
if (nestedParams.length === 0) {
return null;
}
// Generate interface properties
const properties = nestedParams.map(nestedParam => {
const propName = nestedParam.name.substring(param.name.length + 1); // Remove 'paramName.' prefix
const propType = nestedParam.type ? convertTypeToTypeScript(nestedParam.type, options) : 'any';
// Properties are optional if they have a default value or are explicitly marked as optional
const isOptional = nestedParam.optional || nestedParam.type?.type === 'OptionalType' || nestedParam.default !== undefined;
return `${propName}${isOptional ? '?' : ''}: ${propType}`;
});
return `{ ${properties.join('; ')} }`;
}
function generateParamDeclaration(param, options = {}, allParams = []) {
if (!param) return '';
const name = normalizeIdentifier(param.name);
// Check if this is an object parameter that we can generate a better interface for
const objectInterface = generateObjectInterface(param, allParams, options);
// Convert the type - should always be an object
let type = 'any';
if (objectInterface) {
type = objectInterface;
} else if (param.type) {
type = convertTypeToTypeScript(param.type, options);
}
const isOptional = param.optional;
let prefix = '';
if (param.rest) {
prefix = '...';
}
return `${prefix}${name}${isOptional ? '?' : ''}: ${type}`;
}
function generateMethodDeclaration(method, options = {}) {
let output = '';
const { globalFunction = false } = options;
const indent = globalFunction ? '' : ' ';
const commentIndent = globalFunction ? 0 : 2;
if (method.description) {
output += `${indent}/**\n`;
output += formatJSDocComment(method.description, commentIndent) + '\n';
// Add param docs from first overload
if (method.overloads?.[0]?.params) {
method.overloads[0].params.forEach(param => {
if (param.description) {
output += formatJSDocComment(`@param ${param.name} ${param.description}`, commentIndent) + '\n';
}
});
}
// Add return docs
if (method.return?.description) {
output += formatJSDocComment(`@returns ${method.return.description}`, commentIndent) + '\n';
}
output += `${indent} */\n`;
}
const staticPrefix = method.static ? 'static ' : '';
const declarationPrefix = globalFunction ? 'function ' : `${indent}${staticPrefix}`;
// Generate overload declarations
if (method.overloads && method.overloads.length > 0) {
method.overloads.forEach(overload => {
const params = (overload.params || [])
.map(param => generateParamDeclaration(param, options, overload.params))
.join(', ');
let returnType = 'void';
if (overload.chainable && !globalFunction && options.currentClass !== 'p5') {
returnType = options.currentClass || 'this';
// TODO: Decide what should be chainable. Many of these are accidental / not thought through
} else if (overload.return && overload.return.type) {
returnType = convertTypeToTypeScript(overload.return.type, options);
} else if (method.return && method.return.type) {
returnType = convertTypeToTypeScript(method.return.type, options);
}
output += `${declarationPrefix}${method.name}(${params}): ${returnType};\n`;
});
}
output += '\n';
return output;
}
function generateClassDeclaration(classData) {
let output = '';
const className = classData.name.startsWith('p5.') ? classData.name.substring(3) : classData.name;
const actualClassName = className === 'Graphics' ? '__Graphics' : className;
if (classData.description) {
output += ' /**\n';
output += formatJSDocComment(classData.description, 2) + '\n';
output += ' */\n';
}
const extendsClause = classData.extends ? ` extends ${classData.extends}` : '';
output += ` class ${actualClassName}${extendsClause} {\n`;
// Constructor
if (classData.params?.length > 0) {
output += ' constructor(';
output += classData.params
.map(param => generateParamDeclaration(param, { currentClass: className, isInsideNamespace: true }, classData.params))
.join(', ');
output += ');\n\n';
}
const options = { currentClass: className, isInsideNamespace: true };
const originalClassName = classData.name;
// Class methods
const classMethodsList = Object.values(processed.classMethods[originalClassName] || {});
const methodNames = new Set(classMethodsList.map(method => method.name));
// Class properties
const classProperties = processed.classitems.filter(item =>
item.class === originalClassName && item.itemtype === 'property'
);
classProperties.forEach(prop => {
// Skip properties that conflict with method names
if (methodNames.has(prop.name)) {
return;
}
if (prop.description) {
output += ' /**\n';
output += formatJSDocComment(prop.description, 4) + '\n';
output += ' */\n';
}
const type = convertTypeToTypeScript(prop.type, options);
output += ` ${prop.name}: ${type};\n\n`;
});
const staticMethods = classMethodsList.filter(method => method.static);
const instanceMethods = classMethodsList.filter(method => !method.static);
staticMethods.forEach(method => {
output += generateMethodDeclaration(method, options);
});
instanceMethods.forEach(method => {
output += generateMethodDeclaration(method, options);
});
output += ' }\n\n';
// Add type alias for Graphics
if (className === 'Graphics') {
output += ' type Graphics = __Graphics & p5;\n\n';
}
return output;
}
// Generate TypeScript definitions
function generateTypeDefinitions() {
let output = '// This file is auto-generated from JSDoc documentation\n\n';
// First, define all constants at the top level with their actual values
const seenConstants = new Set();
const p5Constants = processed.classitems.filter(item => {
if (item.class === 'p5' && item.itemtype === 'property' && item.name in processed.consts) {
// Skip defineProperty, undefined and avoid duplicates
if (item.name === 'defineProperty' || !item.name) {
return false;
}
if (seenConstants.has(item.name)) {
return false;
}
// Skip typedefs that have real object shapes
if (typedefs[item.name] && hasTypedefProperties(typedefs[item.name])) {
return false;
}
seenConstants.add(item.name);
return true;
}
return false;
});
p5Constants.forEach(constant => {
if (constant.description) {
output += '/**\n';
output += formatJSDocComment(constant.description, 0) + '\n';
output += ' */\n';
}
const type = convertTypeToTypeScript(constant.type, { isInsideNamespace: false, isConstantDef: true });
const isMutable = mutableProperties.has(constant.name);
const declaration = isMutable ? 'declare let' : 'declare const';
output += `${declaration} ${constant.name}: ${type};\n\n`;
// Duplicate with a private identifier so we can re-export in the namespace later
output += `${declaration} __${constant.name}: typeof ${constant.name};\n\n`;
});
// Generate main p5 class
output += 'declare class p5 {\n';
output += ' constructor(sketch?: (p: p5) => void, node?: HTMLElement, sync?: boolean);\n\n';
const p5Options = { currentClass: 'p5', isInsideNamespace: false };
// Generate p5 static methods
const p5StaticMethods = Object.values(processed.classMethods.p5 || {}).filter(method => method.static);
p5StaticMethods.forEach(method => {
output += generateMethodDeclaration(method, p5Options);
});
// Generate p5 instance methods
const p5InstanceMethods = Object.values(processed.classMethods.p5 || {}).filter(method => !method.static);
p5InstanceMethods.forEach(method => {
output += generateMethodDeclaration(method, p5Options);
});
// Add strands functions to p5 instance
const strandsMethods = processStrandsFunctions();
strandsMethods.forEach(method => {
output += generateMethodDeclaration(method, p5Options);
});
// Add constants as both instance and static properties (referencing the top-level constants)
p5Constants.forEach(constant => {
const isMutable = mutableProperties.has(constant.name);
const readonly = isMutable ? '' : 'readonly ';
output += ` ${readonly}${constant.name}: typeof ${constant.name};\n`;
});
output += '}\n\n';
output += 'declare const __p5: typeof p5;\n\n';
// Generate p5 namespace
output += 'declare namespace p5 {\n';
output += ' const p5: typeof __p5;\n';
output += '\n';
p5Constants.forEach(constant => {
output += `${mutableProperties.has(constant.name) ? 'let' : 'const'} ${constant.name}: typeof __${constant.name};\n`;
});
output += '\n';
// Emit interfaces for typedefs that define object shapes
const namespaceOptions = { isInsideNamespace: true };
for (const [name, typedefEntry] of Object.entries(typedefs)) {
if (hasTypedefProperties(typedefEntry)) {
output += generateTypedefInterface(name, typedefEntry, namespaceOptions, 2);
}
}
// Generate other classes in namespace
Object.values(processed.classes).forEach(classData => {
if (classData.name !== 'p5') {
output += generateClassDeclaration(classData);
}
});
// Generate placeholder types for private classes that we need to be able to
// reference, but have no public APIs
const privateClasses = ['Renderer', 'Renderer2D', 'RendererGL', 'FramebufferTexture', 'Texture', 'Quat'];
// Define base classes for private classes, if they should extend something
const privateClassBases = { Renderer: 'Element' };
for (const className of privateClasses) {
const baseClass = privateClassBases[className];
if (baseClass) {
output += ` class ${className} extends ${baseClass} {}\n`;
} else {
output += ` class ${className} {}\n`;
}
}
output += '}\n\n';
// Export declarations
output += 'export default p5;\n';
output += 'export as namespace p5;\n';
const instanceDefinitions = output;
let globalDefinitions = `// This file is auto-generated from JSDoc documentation
import P5 from './p5';
declare global {
interface Window {
p5: P5;
`;
p5Constants.forEach(constant => {
if (constant.description) {
globalDefinitions += '/**\n';
globalDefinitions += formatJSDocComment(constant.description, 0) + '\n';
globalDefinitions += ' */\n';
}
globalDefinitions += `${constant.name}: typeof P5.${constant.name};\n\n`;
});
const globalP5Methods = Object.values(processed.classMethods.p5 || {})
.filter(method => !method.static && method.name !== 'p5');
globalP5Methods.forEach(method => {
globalDefinitions += generateMethodDeclaration(method, { currentClass: 'p5', isInsideNamespace: true, inGlobalMode: true });
});
// Add strands functions to global scope
const conflictingDOMFunctions = ['length']; // Add other conflicting function names here as needed
strandsMethods.forEach(method => {
if (!conflictingDOMFunctions.includes(method.name)) {
globalDefinitions += generateMethodDeclaration(method, { currentClass: 'p5', isInsideNamespace: true, inGlobalMode: true });
}
});
globalDefinitions += '}\n';
// Add global p5 namespace with all class types and constants
globalDefinitions += '\nnamespace p5 {\n';
// Add all constants
p5Constants.forEach(constant => {
const isMutable = mutableProperties.has(constant.name);
const declaration = isMutable ? 'let' : 'const';
globalDefinitions += ` ${declaration} ${constant.name}: typeof P5.${constant.name};\n`;
});
globalDefinitions += '\n';
// Mirror typedef interfaces for global-mode usage
const globalNamespaceOptions = { isInsideNamespace: true, inGlobalMode: true };
for (const [name, typedefEntry] of Object.entries(typedefs)) {
if (hasTypedefProperties(typedefEntry)) {
globalDefinitions += generateTypedefInterface(name, typedefEntry, globalNamespaceOptions, 2);
}
}
// Add all real classes as both types and constructors
Object.values(processed.classes).forEach(classData => {
if (classData.name !== 'p5') {
const className = classData.name.startsWith('p5.') ? classData.name.substring(3) : classData.name;
// For Graphics, use __Graphics for constructor
if (className === 'Graphics') {
globalDefinitions += ` type ${className} = P5.${className};\n`;
globalDefinitions += ` const ${className}: typeof P5.__${className};\n`;
} else {
globalDefinitions += ` type ${className} = P5.${className};\n`;
globalDefinitions += ` const ${className}: typeof P5.${className};\n`;
}
}
});
// Add private classes
for (const className of privateClasses) {
globalDefinitions += ` type ${className} = P5.${className};\n`;
globalDefinitions += ` const ${className}: typeof P5.${className};\n`;
}
globalDefinitions += '}\n\n';
// Also declare constants in global scope (deduplicated)
const alreadyDeclaredConstants = new Set();
p5Constants.forEach(constant => {
if (alreadyDeclaredConstants.has(constant.name)) {
return; // Skip duplicates
}
if (constant.name === 'defineProperty' || !constant.name) {
return; // Skip problematic constants
}
alreadyDeclaredConstants.add(constant.name);
if (constant.description) {
globalDefinitions += '/**\n';
globalDefinitions += formatJSDocComment(constant.description, 0) + '\n';
globalDefinitions += ' */\n';
}
globalDefinitions += `const ${constant.name}: typeof P5.${constant.name};\n\n`;
});
// Also declare functions in global scope
globalP5Methods.forEach(method => {
globalDefinitions += generateMethodDeclaration(method, { currentClass: 'p5', isInsideNamespace: true, inGlobalMode: true, globalFunction: true });
});
// Add strands functions as global functions
strandsMethods.forEach(method => {
if (!conflictingDOMFunctions.includes(method.name)) {
globalDefinitions += generateMethodDeclaration(method, { currentClass: 'p5', isInsideNamespace: true, inGlobalMode: true, globalFunction: true });
}
});
globalDefinitions += '}\n\n';
globalDefinitions += 'export default p5;\n\n';
return { instanceDefinitions, globalDefinitions };
}
// Generate and write TypeScript definitions
const { instanceDefinitions, globalDefinitions } = generateTypeDefinitions();
fs.writeFileSync(path.join(__dirname, '../types/p5.d.ts'), instanceDefinitions);
fs.writeFileSync(path.join(__dirname, '../types/global.d.ts'), globalDefinitions);
console.log('TypeScript definitions generated successfully!');
// Apply patches
console.log('Applying TypeScript patches...');
applyPatches();