-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathBridgeJSTool.swift
More file actions
328 lines (296 loc) · 12.8 KB
/
BridgeJSTool.swift
File metadata and controls
328 lines (296 loc) · 12.8 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
@preconcurrency import func Foundation.exit
@preconcurrency import func Foundation.fputs
@preconcurrency import var Foundation.stderr
@preconcurrency import struct Foundation.URL
@preconcurrency import struct Foundation.Data
@preconcurrency import struct Foundation.ObjCBool
@preconcurrency import class Foundation.JSONEncoder
@preconcurrency import class Foundation.FileManager
@preconcurrency import class Foundation.JSONDecoder
@preconcurrency import class Foundation.ProcessInfo
import SwiftParser
#if canImport(BridgeJSCore)
import BridgeJSCore
#endif
#if canImport(BridgeJSSkeleton)
import BridgeJSSkeleton
#endif
#if canImport(TS2Skeleton)
import TS2Skeleton
#endif
/// BridgeJS Tool
///
/// A command-line tool to generate Swift-JavaScript bridge code for WebAssembly applications.
/// This tool enables bidirectional interoperability between Swift and JavaScript:
///
/// 1. Import: Generate Swift bindings for TypeScript declarations
/// 2. Export: Generate JavaScript bindings for Swift declarations
///
/// Usage:
/// For importing TypeScript:
/// $ bridge-js import --module-name <name> --output-swift <path> --output-skeleton <path> --project <tsconfig.json> <input.d.ts>
/// For exporting Swift:
/// $ bridge-js export --output-swift <path> --output-skeleton <path> <input.swift>
///
/// This tool is intended to be used through the Swift Package Manager plugin system
/// and is not typically called directly by end users.
@main struct BridgeJSTool {
static func help() -> String {
return """
Usage: \(CommandLine.arguments.first ?? "bridge-js-tool") <subcommand> [options]
Subcommands:
import Generate binding code to import TypeScript APIs into Swift
export Generate binding code to export Swift APIs to JavaScript
"""
}
static func main() throws {
do {
try run()
} catch {
printStderr("error: \(error)")
exit(1)
}
}
static func run() throws {
let arguments = Array(CommandLine.arguments.dropFirst())
guard let subcommand = arguments.first else {
throw BridgeJSToolError(
"""
Error: No subcommand provided
\(BridgeJSTool.help())
"""
)
}
switch subcommand {
case "import":
let parser = ArgumentParser(
singleDashOptions: [:],
doubleDashOptions: [
"module-name": OptionRule(
help: "The name of the module to import the TypeScript API into",
required: true
),
"always-write": OptionRule(
help: "Always write the output files even if no APIs are imported",
required: false
),
"verbose": OptionRule(
help: "Print verbose output",
required: false
),
"target-dir": OptionRule(
help: "The SwiftPM package target directory",
required: true
),
"output-swift": OptionRule(help: "The output file path for the Swift source code", required: true),
"output-skeleton": OptionRule(
help: "The output file path for the skeleton of the imported TypeScript APIs",
required: true
),
"project": OptionRule(
help: "The path to the TypeScript project configuration file",
required: true
),
]
)
let (positionalArguments, _, doubleDashOptions) = try parser.parse(
arguments: Array(arguments.dropFirst())
)
let progress = ProgressReporting(verbose: doubleDashOptions["verbose"] == "true")
var importer = ImportTS(progress: progress, moduleName: doubleDashOptions["module-name"]!)
let targetDirectory = URL(fileURLWithPath: doubleDashOptions["target-dir"]!)
let config = try BridgeJSConfig.load(targetDirectory: targetDirectory)
let nodePath: URL = try config.findTool("node", targetDirectory: targetDirectory)
for inputFile in positionalArguments {
if inputFile.hasSuffix(".json") {
let sourceURL = URL(fileURLWithPath: inputFile)
let skeleton = try JSONDecoder().decode(
ImportedFileSkeleton.self,
from: Data(contentsOf: sourceURL)
)
importer.addSkeleton(skeleton)
} else if inputFile.hasSuffix(".d.ts") {
let tsconfigPath = URL(fileURLWithPath: doubleDashOptions["project"]!)
try importer.addSourceFile(inputFile, tsconfigPath: tsconfigPath.path, nodePath: nodePath)
}
}
let outputSwift = try importer.finalize()
let shouldWrite = doubleDashOptions["always-write"] == "true" || outputSwift != nil
guard shouldWrite else {
progress.print("No imported TypeScript APIs found")
return
}
let outputSwiftURL = URL(fileURLWithPath: doubleDashOptions["output-swift"]!)
try FileManager.default.createDirectory(
at: outputSwiftURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
try (outputSwift ?? "").write(to: outputSwiftURL, atomically: true, encoding: .utf8)
let outputSkeletonsURL = URL(fileURLWithPath: doubleDashOptions["output-skeleton"]!)
try FileManager.default.createDirectory(
at: outputSkeletonsURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
try encoder.encode(importer.skeleton).write(to: outputSkeletonsURL)
progress.print(
"""
Imported TypeScript APIs:
- \(outputSwiftURL.path)
- \(outputSkeletonsURL.path)
"""
)
case "export":
let parser = ArgumentParser(
singleDashOptions: [:],
doubleDashOptions: [
"module-name": OptionRule(
help: "The name of the module for external function references",
required: true
),
"output-skeleton": OptionRule(
help: "The output file path for the skeleton of the exported Swift APIs",
required: true
),
"output-swift": OptionRule(help: "The output file path for the Swift source code", required: true),
"always-write": OptionRule(
help: "Always write the output files even if no APIs are exported",
required: false
),
"verbose": OptionRule(
help: "Print verbose output",
required: false
),
]
)
let (positionalArguments, _, doubleDashOptions) = try parser.parse(
arguments: Array(arguments.dropFirst())
)
let progress = ProgressReporting(verbose: doubleDashOptions["verbose"] == "true")
let exporter = ExportSwift(progress: progress, moduleName: doubleDashOptions["module-name"]!)
for inputFile in positionalArguments.sorted() {
let sourceURL = URL(fileURLWithPath: inputFile)
guard sourceURL.pathExtension == "swift" else { continue }
let sourceContent = try String(contentsOf: sourceURL, encoding: .utf8)
let sourceFile = Parser.parse(source: sourceContent)
try exporter.addSourceFile(sourceFile, sourceURL.path)
}
// Finalize the export
let output = try exporter.finalize()
let outputSwiftURL = URL(fileURLWithPath: doubleDashOptions["output-swift"]!)
let outputSkeletonURL = URL(fileURLWithPath: doubleDashOptions["output-skeleton"]!)
let shouldWrite = doubleDashOptions["always-write"] == "true" || output != nil
guard shouldWrite else {
progress.print("No exported Swift APIs found")
return
}
// Create the output directory if it doesn't exist
try FileManager.default.createDirectory(
at: outputSwiftURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
try FileManager.default.createDirectory(
at: outputSkeletonURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil
)
// Write the output Swift file
try (output?.outputSwift ?? "").write(to: outputSwiftURL, atomically: true, encoding: .utf8)
if let outputSkeleton = output?.outputSkeleton {
// Write the output skeleton file
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let outputSkeletonData = try encoder.encode(outputSkeleton)
try outputSkeletonData.write(to: outputSkeletonURL)
}
progress.print(
"""
Exported Swift APIs:
- \(outputSwiftURL.path)
- \(outputSkeletonURL.path)
"""
)
default:
throw BridgeJSToolError(
"""
Error: Invalid subcommand: \(subcommand)
\(BridgeJSTool.help())
"""
)
}
}
}
struct BridgeJSToolError: Swift.Error, CustomStringConvertible {
let description: String
init(_ message: String) {
self.description = message
}
}
private func printStderr(_ message: String) {
fputs(message + "\n", stderr)
}
// MARK: - Minimal Argument Parsing
struct OptionRule {
var help: String
var required: Bool = false
}
struct ArgumentParser {
let singleDashOptions: [String: OptionRule]
let doubleDashOptions: [String: OptionRule]
init(singleDashOptions: [String: OptionRule], doubleDashOptions: [String: OptionRule]) {
self.singleDashOptions = singleDashOptions
self.doubleDashOptions = doubleDashOptions
}
typealias ParsedArguments = (
positionalArguments: [String],
singleDashOptions: [String: String],
doubleDashOptions: [String: String]
)
func help() -> String {
var help = "Usage: \(CommandLine.arguments.first ?? "bridge-js-tool") [options] <positional arguments>\n\n"
help += "Options:\n"
// Align the options by the longest option
let maxOptionLength = max(
(singleDashOptions.keys.map(\.count).max() ?? 0) + 1,
(doubleDashOptions.keys.map(\.count).max() ?? 0) + 2
)
for (key, rule) in singleDashOptions {
help += " -\(key)\(String(repeating: " ", count: maxOptionLength - key.count)): \(rule.help)\n"
}
for (key, rule) in doubleDashOptions {
help += " --\(key)\(String(repeating: " ", count: maxOptionLength - key.count)): \(rule.help)\n"
}
return help
}
func parse(arguments: [String]) throws -> ParsedArguments {
var positionalArguments: [String] = []
var singleDashOptions: [String: String] = [:]
var doubleDashOptions: [String: String] = [:]
var arguments = arguments.makeIterator()
while let arg = arguments.next() {
if arg.starts(with: "-") {
if arg.starts(with: "--") {
let key = String(arg.dropFirst(2))
let value = arguments.next()
doubleDashOptions[key] = value
} else {
let key = String(arg.dropFirst(1))
let value = arguments.next()
singleDashOptions[key] = value
}
} else {
positionalArguments.append(arg)
}
}
for (key, rule) in self.doubleDashOptions {
if rule.required, doubleDashOptions[key] == nil {
throw BridgeJSToolError("Option --\(key) is required")
}
}
return (positionalArguments, singleDashOptions, doubleDashOptions)
}
}