typenative 0.0.17 → 0.0.19
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.
- package/.github/workflows/npm-publish-github-packages.yml +75 -36
- package/CHANGELOG.md +119 -95
- package/LICENSE +21 -21
- package/README.md +158 -152
- package/TODO.md +29 -0
- package/bin/index.js +176 -33
- package/bin/transpiler.js +502 -19
- package/go.d.ts +1 -0
- package/index.d.ts +1 -0
- package/npm.d.ts +1 -0
- package/package.json +68 -59
- package/types/typenative-go.d.ts +15 -0
- package/types/typenative-npm.d.ts +5 -0
- package/types/typenative.d.ts +249 -193
package/README.md
CHANGED
|
@@ -1,152 +1,158 @@
|
|
|
1
|
-
# TypeNative
|
|
2
|
-
|
|
3
|
-
Build native applications using Typescript.
|
|
4
|
-
|
|
5
|
-
## PreRequisites
|
|
6
|
-
|
|
7
|
-
- [Nodejs v24](https://nodejs.org/en) or newer.
|
|
8
|
-
- [Go 1.21](https://go.dev/doc/install) or newer.
|
|
9
|
-
|
|
10
|
-
## Get Started
|
|
11
|
-
|
|
12
|
-
- Write a file `test.ts` with content `console.log('Hello World!');` or any other message
|
|
13
|
-
- Run `npx typenative --source test.ts --script`
|
|
14
|
-
|
|
15
|
-
## Typescript Syntax Support
|
|
16
|
-
|
|
17
|
-
TypeNative currently supports a focused subset of TypeScript syntax elements that are transpiled to Go code. The support is grouped by topic for easier scanning.
|
|
18
|
-
|
|
19
|
-
**Basic Types**
|
|
20
|
-
|
|
21
|
-
| Feature | Supported | Notes |
|
|
22
|
-
| -------------- | :-------: | ------------------------------------------------------------- |
|
|
23
|
-
| number | ✅ | Transpiled to `float64` |
|
|
24
|
-
| boolean | ✅ | Transpiled to `bool` |
|
|
25
|
-
| string | ✅ | |
|
|
26
|
-
| null | ✅ | |
|
|
27
|
-
| any | ✅ | Used for type inference |
|
|
28
|
-
| Nullable types | ✅ | `T \| null` / `T \| undefined` transpiled to Go pointer types |
|
|
29
|
-
|
|
30
|
-
**Variables & Objects**
|
|
31
|
-
|
|
32
|
-
| Feature | Supported | Notes |
|
|
33
|
-
| --------------------- | :-------: | -------------------------------- |
|
|
34
|
-
| Variable declarations | ✅ | `let` and `const` |
|
|
35
|
-
| Object literals | ✅ | Transpiled to Go struct literals |
|
|
36
|
-
|
|
37
|
-
**Operators**
|
|
38
|
-
|
|
39
|
-
| Feature | Supported | Notes |
|
|
40
|
-
| ------------------------ | :-------: | ------------------------------ |
|
|
41
|
-
| Arithmetic operators | ✅ | `+`, `-`, etc. |
|
|
42
|
-
| Comparison operators | ✅ | `==`, `!=`, `===`, `!==`, etc. |
|
|
43
|
-
| Logical operators | ✅ | `&&`, `\|\|` |
|
|
44
|
-
| Increment/Decrement | ✅ | `++`, `--` |
|
|
45
|
-
| Non-null assertion (`!`) | ✅ | Stripped during transpilation |
|
|
46
|
-
| Ternary expressions | ✅ | `condition ? a : b` |
|
|
47
|
-
| Nullish coalescing | ✅ | `??` operator |
|
|
48
|
-
| Optional chaining | ✅ | `obj?.prop`, `arr?.[i]` |
|
|
49
|
-
|
|
50
|
-
**Control Flow**
|
|
51
|
-
|
|
52
|
-
| Feature | Supported | Notes
|
|
53
|
-
| ------------------ | :-------: |
|
|
54
|
-
| If/Else statements | ✅ | Fully supported
|
|
55
|
-
| Switch statements | ✅ | Case and default statements
|
|
56
|
-
| For loops | ✅ | Standard `for` loops
|
|
57
|
-
| For...of loops | ✅ | Iteration over arrays
|
|
58
|
-
| While loops | ✅ | Transpiled to Go's `for` loops
|
|
59
|
-
| Do...while loops | ✅ | Implemented with conditional break
|
|
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
|
-
|
|
1
|
+
# TypeNative
|
|
2
|
+
|
|
3
|
+
Build native applications using Typescript.
|
|
4
|
+
|
|
5
|
+
## PreRequisites
|
|
6
|
+
|
|
7
|
+
- [Nodejs v24](https://nodejs.org/en) or newer.
|
|
8
|
+
- [Go 1.21](https://go.dev/doc/install) or newer.
|
|
9
|
+
|
|
10
|
+
## Get Started
|
|
11
|
+
|
|
12
|
+
- Write a file `test.ts` with content `console.log('Hello World!');` or any other message
|
|
13
|
+
- Run `npx typenative --source test.ts --script`
|
|
14
|
+
|
|
15
|
+
## Typescript Syntax Support
|
|
16
|
+
|
|
17
|
+
TypeNative currently supports a focused subset of TypeScript syntax elements that are transpiled to Go code. The support is grouped by topic for easier scanning.
|
|
18
|
+
|
|
19
|
+
**Basic Types**
|
|
20
|
+
|
|
21
|
+
| Feature | Supported | Notes |
|
|
22
|
+
| -------------- | :-------: | ------------------------------------------------------------- |
|
|
23
|
+
| number | ✅ | Transpiled to `float64` |
|
|
24
|
+
| boolean | ✅ | Transpiled to `bool` |
|
|
25
|
+
| string | ✅ | |
|
|
26
|
+
| null | ✅ | |
|
|
27
|
+
| any | ✅ | Used for type inference |
|
|
28
|
+
| Nullable types | ✅ | `T \| null` / `T \| undefined` transpiled to Go pointer types |
|
|
29
|
+
|
|
30
|
+
**Variables & Objects**
|
|
31
|
+
|
|
32
|
+
| Feature | Supported | Notes |
|
|
33
|
+
| --------------------- | :-------: | -------------------------------- |
|
|
34
|
+
| Variable declarations | ✅ | `let` and `const` |
|
|
35
|
+
| Object literals | ✅ | Transpiled to Go struct literals |
|
|
36
|
+
|
|
37
|
+
**Operators**
|
|
38
|
+
|
|
39
|
+
| Feature | Supported | Notes |
|
|
40
|
+
| ------------------------ | :-------: | ------------------------------ |
|
|
41
|
+
| Arithmetic operators | ✅ | `+`, `-`, etc. |
|
|
42
|
+
| Comparison operators | ✅ | `==`, `!=`, `===`, `!==`, etc. |
|
|
43
|
+
| Logical operators | ✅ | `&&`, `\|\|` |
|
|
44
|
+
| Increment/Decrement | ✅ | `++`, `--` |
|
|
45
|
+
| Non-null assertion (`!`) | ✅ | Stripped during transpilation |
|
|
46
|
+
| Ternary expressions | ✅ | `condition ? a : b` |
|
|
47
|
+
| Nullish coalescing | ✅ | `??` operator |
|
|
48
|
+
| Optional chaining | ✅ | `obj?.prop`, `arr?.[i]` |
|
|
49
|
+
|
|
50
|
+
**Control Flow**
|
|
51
|
+
|
|
52
|
+
| Feature | Supported | Notes |
|
|
53
|
+
| ------------------ | :-------: | ------------------------------------------------------ |
|
|
54
|
+
| If/Else statements | ✅ | Fully supported |
|
|
55
|
+
| Switch statements | ✅ | Case and default statements |
|
|
56
|
+
| For loops | ✅ | Standard `for` loops |
|
|
57
|
+
| For...of loops | ✅ | Iteration over arrays |
|
|
58
|
+
| While loops | ✅ | Transpiled to Go's `for` loops |
|
|
59
|
+
| Do...while loops | ✅ | Implemented with conditional break |
|
|
60
|
+
| Try/Catch/Finally | ✅ | `throw` → `panic`; catch/finally via `defer`/`recover` |
|
|
61
|
+
|
|
62
|
+
**Data Structures & Array Methods**
|
|
63
|
+
|
|
64
|
+
| Feature | Supported | Notes |
|
|
65
|
+
| -------------------------- | :-------: | ------------------------------------------------------------------------------------------ |
|
|
66
|
+
| Arrays | ✅ | Basic array operations |
|
|
67
|
+
| Array methods | ✅ | `push`, `join`, `slice` |
|
|
68
|
+
| Higher-order array methods | ✅ | `.map()`, `.filter()`, `.some()`, `.find()` |
|
|
69
|
+
| Method chaining | ✅ | Chaining array methods such as `.map(...).filter(...).join(...)` |
|
|
70
|
+
| Map | ✅ | `Map<K, V>` → Go `map[K]V`; `.set()`, `.get()`, `.has()`, `.delete()`, `.clear()`, `.size` |
|
|
71
|
+
| Set | ✅ | `Set<T>` → Go `map[T]struct{}`; `.add()`, `.has()`, `.delete()`, `.clear()`, `.size` |
|
|
72
|
+
|
|
73
|
+
**Functions**
|
|
74
|
+
|
|
75
|
+
| Feature | Supported | Notes |
|
|
76
|
+
| ---------------------------- | :-------: | ----------------------------------------------------------- |
|
|
77
|
+
| Function declarations | ✅ | Transpiled to Go functions |
|
|
78
|
+
| Arrow functions | ✅ | Transpiled to anonymous functions |
|
|
79
|
+
| Closures over mutable state | ✅ | Functions capturing and mutating outer variables |
|
|
80
|
+
| Function types | ✅ | `() => number`, `(x: number) => string` as type annotations |
|
|
81
|
+
| Generics (functions/classes) | ✅ | Type parameters via Go generics |
|
|
82
|
+
| Default parameter values | ✅ | `function(x = defaultValue)` |
|
|
83
|
+
|
|
84
|
+
**Classes & Interfaces**
|
|
85
|
+
|
|
86
|
+
| Feature | Supported | Notes |
|
|
87
|
+
| ------------------- | :-------: | -------------------------------------------------------------- |
|
|
88
|
+
| Classes | ✅ | Transpiled to Go structs with constructor and receiver methods |
|
|
89
|
+
| Class inheritance | ✅ | `extends` via embedded structs, `super()` supported |
|
|
90
|
+
| Interfaces | ✅ | Transpiled to Go interfaces, supports `extends` |
|
|
91
|
+
| Optional properties | ✅ | `prop?: Type` in interfaces/types |
|
|
92
|
+
| Enums | ✅ | `enum` declarations and member access |
|
|
93
|
+
|
|
94
|
+
**Async & Timing**
|
|
95
|
+
|
|
96
|
+
| Feature | Supported | Notes |
|
|
97
|
+
| ----------- | :-------: | ----------------------------------------------------------------- |
|
|
98
|
+
| Async/Await | ✅ | `async` functions return Go channels, `await` reads from channels |
|
|
99
|
+
| Promises | ✅ | `new Promise` transpiled to channel + goroutine pattern |
|
|
100
|
+
| setTimeout | ✅ | Mapped to Go's `time.AfterFunc` |
|
|
101
|
+
|
|
102
|
+
**Built-in Functions & Utilities**
|
|
103
|
+
|
|
104
|
+
| Feature | Supported | Notes |
|
|
105
|
+
| --------------------- | :-------: | ----------------------------------------------------- |
|
|
106
|
+
| console.log | ✅ | Mapped to `fmt.Println` |
|
|
107
|
+
| console.time/timeEnd | ✅ | Performance measurement via `time.Now` / `time.Since` |
|
|
108
|
+
| assert | ✅ | Transpiled to `panic` on failure |
|
|
109
|
+
| parseInt / parseFloat | ✅ | Mapped to Go's `strconv` package |
|
|
110
|
+
|
|
111
|
+
**Math Methods**
|
|
112
|
+
|
|
113
|
+
| Feature | Supported | Notes |
|
|
114
|
+
| ------------------------- | :-------: | ------------------------------------------------- |
|
|
115
|
+
| Math.random | ✅ | Mapped to `rand.Float64()` |
|
|
116
|
+
| Math.floor / ceil / round | ✅ | Mapped to `math.Floor`, `math.Ceil`, `math.Round` |
|
|
117
|
+
| Math.abs / sqrt / pow | ✅ | Mapped to corresponding `math` functions |
|
|
118
|
+
| Math.min / max | ✅ | Mapped to `math.Min`, `math.Max` |
|
|
119
|
+
|
|
120
|
+
**String Methods**
|
|
121
|
+
|
|
122
|
+
| Feature | Supported | Notes |
|
|
123
|
+
| -------------------------- | :-------: | --------------------------------------------- |
|
|
124
|
+
| Template literals | ✅ | Backtick strings with `${expr}` interpolation |
|
|
125
|
+
| toUpperCase / toLowerCase | ✅ | Via `strings` package |
|
|
126
|
+
| trim / trimStart / trimEnd | ✅ | Via `strings` package |
|
|
127
|
+
| split / includes / indexOf | ✅ | Via `strings` package |
|
|
128
|
+
| startsWith / endsWith | ✅ | Via `strings` package |
|
|
129
|
+
| replace / replaceAll | ✅ | Via `strings` package |
|
|
130
|
+
| charAt / substring / slice | ✅ | Direct Go string indexing/slicing |
|
|
131
|
+
| concat / repeat | ✅ | String concatenation and `strings.Repeat` |
|
|
132
|
+
|
|
133
|
+
**Number / Object Methods**
|
|
134
|
+
|
|
135
|
+
| Feature | Supported | Notes |
|
|
136
|
+
| -------- | :-------: | ----------------------------------------------------- |
|
|
137
|
+
| toString | ✅ | Universal `toString()` via `fmt.Sprintf` for any type |
|
|
138
|
+
|
|
139
|
+
**RegExp**
|
|
140
|
+
|
|
141
|
+
| Feature | Supported | Notes |
|
|
142
|
+
| -------------- | :-------: | --------------------------------------------------- |
|
|
143
|
+
| Regex literals | ✅ | `/pattern/flags` transpiled to `regexp.MustCompile` |
|
|
144
|
+
| new RegExp() | ✅ | Constructor with optional flags |
|
|
145
|
+
| test() | ✅ | Mapped to `regexp.MatchString` |
|
|
146
|
+
| exec() | ✅ | Mapped to `regexp.FindStringSubmatch` |
|
|
147
|
+
|
|
148
|
+
**Modules & Imports**
|
|
149
|
+
|
|
150
|
+
| Feature | Supported | Notes |
|
|
151
|
+
| ------------------------ | :-------: | ------------------------------------------------------------ |
|
|
152
|
+
| Local file imports | ✅ | `import { x } from './file'` transpiled to Go package import |
|
|
153
|
+
| Node.js built-in imports | ✅ | `import { join } from 'node:path'` mapped to Go stdlib |
|
|
154
|
+
| Go package imports | ✅ | `import { x } from 'go:pkg'` |
|
|
155
|
+
| npm package imports | ✅ | `import { x } from 'pkg'` mapped to Go module imports |
|
|
156
|
+
| Named exports | ✅ | `export function` / `export const` declarations |
|
|
157
|
+
|
|
158
|
+
TypeNative is currently in early development and new features are being added regularly. The goal for `1.0` release is for TypeNative to transpile itself.
|
package/TODO.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
**index.ts needs:**
|
|
2
|
+
|
|
3
|
+
| Feature | Example |
|
|
4
|
+
| ------------------------------- | ------------------------------------------------------------------- |
|
|
5
|
+
| Default imports | `import inquirer from 'inquirer'`, `import fs from 'fs-extra'` |
|
|
6
|
+
| `process` global | `process.argv`, `process.platform` |
|
|
7
|
+
| Array `findIndex` | `process.argv.findIndex(a => a === '--script')` |
|
|
8
|
+
| `JSON.parse` / `JSON.stringify` | `JSON.parse(fs.readFileSync(...))`, `JSON.stringify(pckg, null, 2)` |
|
|
9
|
+
| Named async IIFE | `(async function main() { ... })()` |
|
|
10
|
+
|
|
11
|
+
**transpiler.ts additionally needs:**
|
|
12
|
+
|
|
13
|
+
| Feature | Example |
|
|
14
|
+
| ----------------------------------- | --------------------------------------------------- |
|
|
15
|
+
| Default imports | `import ts from 'typescript'` |
|
|
16
|
+
| Spread in array literals | `[...importedPackages]`, `[...arr1, ...arr2]` |
|
|
17
|
+
| `for...of` with tuple destructuring | `for (const [funcName, fn] of Object.entries(...))` |
|
|
18
|
+
| `Object.entries()` | `Object.entries(mapping.functions)` |
|
|
19
|
+
| Arrow function IIFE | `(() => { ... })()` |
|
|
20
|
+
| Array `findIndex` | `parameters.findIndex(p => !!p.initializer)` |
|
|
21
|
+
|
|
22
|
+
**Priority order** (most blocking first):
|
|
23
|
+
|
|
24
|
+
1. **Default imports** — used at the top of both files, nothing runs without this
|
|
25
|
+
2. **Spread in array literals** — used throughout transpiler.ts for array construction
|
|
26
|
+
3. **`for...of` with tuple destructuring + `Object.entries`** — used for iterating import mappings
|
|
27
|
+
4. **`process` global** — core to CLI argument parsing in index.ts
|
|
28
|
+
5. **IIFE** — the entire entry point of index.ts is an async IIFE
|
|
29
|
+
6. **`findIndex`**, **`JSON.parse/stringify`** — utility methods used in both files
|
package/bin/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import inquirer from 'inquirer';
|
|
3
3
|
import fs from 'fs-extra';
|
|
4
|
-
import path from 'path';
|
|
4
|
+
import path from 'node:path';
|
|
5
5
|
import { execa } from 'execa';
|
|
6
6
|
import { transpileToNative } from './transpiler.js';
|
|
7
|
-
import { fileURLToPath } from 'url';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
8
|
const __filename = fileURLToPath(import.meta.url);
|
|
9
9
|
const __dirname = path.dirname(__filename);
|
|
10
10
|
(async function main() {
|
|
@@ -69,43 +69,184 @@ const __dirname = path.dirname(__filename);
|
|
|
69
69
|
console.log(`Project "${projectName}" created successfully!`);
|
|
70
70
|
if (answers.installDependencies) {
|
|
71
71
|
console.log('Installing dependencies...');
|
|
72
|
-
await execa('npm install', { cwd: projectName, stdio: 'inherit' });
|
|
72
|
+
await execa('npm', ['install'], { cwd: projectName, stdio: 'inherit' });
|
|
73
73
|
console.log('Dependencies installed successfully!');
|
|
74
74
|
}
|
|
75
75
|
return;
|
|
76
76
|
}
|
|
77
|
+
const sourcePath = answers.tsCode ? null : (source ?? answers.path ?? null);
|
|
77
78
|
const tsCode = answers.tsCode
|
|
78
79
|
? answers.tsCode
|
|
79
|
-
: await fs.readFile(
|
|
80
|
-
const
|
|
80
|
+
: await fs.readFile(sourcePath, { encoding: 'utf-8' });
|
|
81
|
+
const sourceDir = sourcePath ? path.dirname(path.resolve(sourcePath)) : null;
|
|
82
|
+
const transpileResult = transpileToNative(tsCode, sourceDir
|
|
83
|
+
? {
|
|
84
|
+
readFile: (specifier, fromDir) => {
|
|
85
|
+
const baseDir = fromDir ?? sourceDir;
|
|
86
|
+
// Relative or absolute path → resolve from baseDir
|
|
87
|
+
if (specifier.startsWith('.') || specifier.startsWith('/')) {
|
|
88
|
+
for (const candidate of [specifier + '.ts', specifier]) {
|
|
89
|
+
try {
|
|
90
|
+
const fullPath = path.resolve(baseDir, candidate);
|
|
91
|
+
return {
|
|
92
|
+
content: fs.readFileSync(fullPath, 'utf-8'),
|
|
93
|
+
dir: path.dirname(fullPath)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
/* not found */
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
// npm package — walk up from baseDir looking for node_modules/<name>
|
|
103
|
+
const resolved = resolveNpmPackage(baseDir, specifier);
|
|
104
|
+
if (!resolved)
|
|
105
|
+
return null;
|
|
106
|
+
let { content, dir } = resolved;
|
|
107
|
+
// Normalize CommonJS to ES module syntax
|
|
108
|
+
if (!content.includes('export ') && (content.includes('module.exports') || content.includes('exports.'))) {
|
|
109
|
+
content = normalizeCjsContent(content);
|
|
110
|
+
}
|
|
111
|
+
// Inject types from a local ambient .d.ts if available
|
|
112
|
+
const typed = tryInjectDtsTypes(content, specifier, sourceDir);
|
|
113
|
+
if (typed)
|
|
114
|
+
content = typed;
|
|
115
|
+
return { content, dir };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
: undefined);
|
|
119
|
+
const exeName = process.platform === 'win32' ? 'native.exe' : 'native';
|
|
120
|
+
const exePath = `dist/${exeName}`;
|
|
81
121
|
await fs.ensureDir('dist');
|
|
82
|
-
|
|
83
|
-
|
|
122
|
+
// Clean up stale Go files from previous runs before writing new ones
|
|
123
|
+
for (const existing of await fs.readdir('dist')) {
|
|
124
|
+
if (existing.endsWith('.go'))
|
|
125
|
+
await fs.remove(`dist/${existing}`);
|
|
126
|
+
}
|
|
127
|
+
await fs.writeFile('dist/code.go', transpileResult.main, { encoding: 'utf-8' });
|
|
128
|
+
const goFiles = ['dist/code.go'];
|
|
129
|
+
for (const [filename, content] of transpileResult.files) {
|
|
130
|
+
await fs.writeFile(`dist/${filename}`, content, { encoding: 'utf-8' });
|
|
131
|
+
goFiles.push(`dist/${filename}`);
|
|
132
|
+
}
|
|
133
|
+
await execa('go', ['build', '-o', exePath, ...goFiles], {
|
|
84
134
|
stdio: 'inherit'
|
|
85
135
|
});
|
|
86
136
|
// await fs.remove('dist/code.go');
|
|
87
137
|
if (scriptMode) {
|
|
88
|
-
await execa(
|
|
138
|
+
await execa(exePath, {
|
|
89
139
|
stdio: 'inherit'
|
|
90
140
|
});
|
|
91
|
-
//await fs.remove(
|
|
141
|
+
//await fs.remove(exePath);
|
|
92
142
|
}
|
|
93
143
|
else if (output || answers.output) {
|
|
94
|
-
await fs.copy(
|
|
95
|
-
//await fs.remove(
|
|
144
|
+
await fs.copy(exePath, output ?? answers.output, { overwrite: true });
|
|
145
|
+
//await fs.remove(exePath);
|
|
96
146
|
console.log(`Created native executable at: ${output ?? answers.output}`);
|
|
97
147
|
}
|
|
98
148
|
})();
|
|
149
|
+
function normalizeCjsContent(code) {
|
|
150
|
+
code = code.replace(/['"]use strict['"];?\n?/g, '');
|
|
151
|
+
code = code.replace(/(?:module\.exports|exports)\.(\w+)\s*=\s*function\s*\w*\s*\(/g, 'export function $1(');
|
|
152
|
+
return code;
|
|
153
|
+
}
|
|
154
|
+
function tryInjectDtsTypes(jsContent, packageName, searchDir) {
|
|
155
|
+
if (!searchDir)
|
|
156
|
+
return null;
|
|
157
|
+
// Look for *.d.ts files in searchDir that declare the module
|
|
158
|
+
let dtsBody = null;
|
|
159
|
+
try {
|
|
160
|
+
const escaped = packageName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
161
|
+
for (const file of fs.readdirSync(searchDir)) {
|
|
162
|
+
if (!file.endsWith('.d.ts'))
|
|
163
|
+
continue;
|
|
164
|
+
const content = fs.readFileSync(path.join(searchDir, file), 'utf-8');
|
|
165
|
+
const match = content.match(new RegExp(`declare module ['"]${escaped}['"][^{]*\\{([\\s\\S]*?)\\}`));
|
|
166
|
+
if (match) {
|
|
167
|
+
dtsBody = match[1];
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
if (!dtsBody)
|
|
176
|
+
return null;
|
|
177
|
+
// Extract typed function signatures from the .d.ts module body
|
|
178
|
+
const signatures = new Map();
|
|
179
|
+
const sigRegex = /export function (\w+)\(([^)]*)\)\s*:\s*([^\n;]+)/g;
|
|
180
|
+
let m;
|
|
181
|
+
while ((m = sigRegex.exec(dtsBody)) !== null) {
|
|
182
|
+
signatures.set(m[1], { params: m[2].trim(), returnType: m[3].trim() });
|
|
183
|
+
}
|
|
184
|
+
if (signatures.size === 0)
|
|
185
|
+
return null;
|
|
186
|
+
// Replace untyped signatures in the normalized JS with typed ones from .d.ts
|
|
187
|
+
return jsContent.replace(/export function (\w+)\s*\(([^)]*)\)/g, (match, name) => {
|
|
188
|
+
const sig = signatures.get(name);
|
|
189
|
+
if (!sig)
|
|
190
|
+
return match;
|
|
191
|
+
return `export function ${name}(${sig.params}): ${sig.returnType}`;
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
function resolveNpmPackage(fromDir, packageName) {
|
|
195
|
+
// Walk up the directory tree looking for node_modules/<packageName>
|
|
196
|
+
let searchDir = fromDir;
|
|
197
|
+
while (true) {
|
|
198
|
+
const pkgDir = path.join(searchDir, 'node_modules', packageName);
|
|
199
|
+
const pkgJsonPath = path.join(pkgDir, 'package.json');
|
|
200
|
+
try {
|
|
201
|
+
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
|
|
202
|
+
// Build candidate entry points: TypeScript preferred, JavaScript as fallback
|
|
203
|
+
const tsCandidates = [];
|
|
204
|
+
const jsCandidates = [];
|
|
205
|
+
for (const field of ['source', 'main', 'module']) {
|
|
206
|
+
const entry = pkgJson[field];
|
|
207
|
+
if (!entry)
|
|
208
|
+
continue;
|
|
209
|
+
if (entry.endsWith('.ts'))
|
|
210
|
+
tsCandidates.push(entry);
|
|
211
|
+
else if (entry.endsWith('.js')) {
|
|
212
|
+
tsCandidates.push(entry.replace(/\.js$/, '.ts'));
|
|
213
|
+
jsCandidates.push(entry);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
tsCandidates.push('index.ts', 'src/index.ts');
|
|
217
|
+
jsCandidates.push('index.js', 'src/index.js');
|
|
218
|
+
const candidates = [...tsCandidates, ...jsCandidates];
|
|
219
|
+
for (const candidate of candidates) {
|
|
220
|
+
const fullPath = path.resolve(pkgDir, candidate);
|
|
221
|
+
try {
|
|
222
|
+
return { content: fs.readFileSync(fullPath, 'utf-8'), dir: path.dirname(fullPath) };
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
/* try next candidate */
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
/* no package.json here, keep walking up */
|
|
231
|
+
}
|
|
232
|
+
const parent = path.dirname(searchDir);
|
|
233
|
+
if (parent === searchDir)
|
|
234
|
+
break; // filesystem root
|
|
235
|
+
searchDir = parent;
|
|
236
|
+
}
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
99
239
|
function getPackageJson(projectName) {
|
|
240
|
+
const exeName = process.platform === 'win32' ? `${projectName}.exe` : projectName;
|
|
100
241
|
const pckg = {
|
|
101
242
|
name: projectName,
|
|
102
243
|
version: '1.0.0',
|
|
103
244
|
scripts: {
|
|
104
245
|
execute: 'npx typenative --source main.ts --script',
|
|
105
|
-
build: `npx typenative --source main.ts --output bin/${
|
|
246
|
+
build: `npx typenative --source main.ts --output bin/${exeName}`
|
|
106
247
|
},
|
|
107
248
|
devDependencies: {
|
|
108
|
-
typenative: '^0.0.
|
|
249
|
+
typenative: '^0.0.19'
|
|
109
250
|
}
|
|
110
251
|
};
|
|
111
252
|
return JSON.stringify(pckg, null, 2);
|
|
@@ -116,35 +257,37 @@ function getTsConfig() {
|
|
|
116
257
|
compilerOptions: {
|
|
117
258
|
target: 'es2020',
|
|
118
259
|
lib: [],
|
|
119
|
-
types: ['
|
|
260
|
+
types: ['typenative', 'typenative/go', 'typenative/npm'],
|
|
120
261
|
rootDir: '.',
|
|
121
262
|
strict: true,
|
|
122
|
-
noImplicitAny: true
|
|
263
|
+
noImplicitAny: true,
|
|
264
|
+
allowSyntheticDefaultImports: true
|
|
123
265
|
}
|
|
124
266
|
};
|
|
125
267
|
return JSON.stringify(tsConfig, null, 2);
|
|
126
268
|
}
|
|
127
269
|
function getGitIgnore() {
|
|
128
|
-
return `# TypeNative generated files
|
|
129
|
-
node_modules/
|
|
130
|
-
dist/
|
|
131
|
-
bin/
|
|
270
|
+
return `# TypeNative generated files
|
|
271
|
+
node_modules/
|
|
272
|
+
dist/
|
|
273
|
+
bin/
|
|
132
274
|
`;
|
|
133
275
|
}
|
|
134
276
|
function getReadMe(projectName) {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
You can
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
277
|
+
const exeName = process.platform === 'win32' ? `${projectName}.exe` : projectName;
|
|
278
|
+
return `# ${projectName}
|
|
279
|
+
|
|
280
|
+
This project was created using TypeNative, a tool to transpile TypeScript code to native Go code.
|
|
281
|
+
|
|
282
|
+
## How to Run
|
|
283
|
+
|
|
284
|
+
You can write your TypeScript code in the \`main.ts\` file. The code will be transpiled to Go and compiled into a native executable.
|
|
285
|
+
You can also run the code directly in script mode using \`npm run execute\`.
|
|
286
|
+
|
|
287
|
+
## How to Build
|
|
288
|
+
|
|
289
|
+
1. Install dependencies: \`npm install\` (if not done already)
|
|
290
|
+
2. Build the project: \`npm run build\`
|
|
291
|
+
3. Run the executable: \`./bin/${exeName}\`
|
|
149
292
|
`;
|
|
150
293
|
}
|