@ttsc/wasm 0.13.0 → 0.14.0-dev.20250530.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +60 -15
  2. package/dist/ttsc.wasm +0 -0
  3. package/host/api.go +5 -4
  4. package/host/doc.go +7 -5
  5. package/host/fountain.go +505 -0
  6. package/host/host.go +64 -10
  7. package/host/plugin.go +6 -5
  8. package/lib/src/MemFSError.d.ts +15 -0
  9. package/lib/src/MemFSError.js +47 -0
  10. package/lib/src/MemFSError.js.map +1 -0
  11. package/lib/src/bootTtsc.d.ts +21 -0
  12. package/lib/src/bootTtsc.js +179 -0
  13. package/lib/src/bootTtsc.js.map +1 -0
  14. package/lib/src/createMemFS.d.ts +11 -0
  15. package/lib/src/{MemFS.js → createMemFS.js} +28 -63
  16. package/lib/src/createMemFS.js.map +1 -0
  17. package/lib/src/index.d.ts +5 -6
  18. package/lib/src/index.js +19 -8
  19. package/lib/src/index.js.map +1 -1
  20. package/lib/src/parseResult.d.ts +8 -0
  21. package/lib/src/parseResult.js +20 -0
  22. package/lib/src/parseResult.js.map +1 -0
  23. package/lib/src/structures/IBootResult.d.ts +9 -0
  24. package/lib/src/structures/IBootResult.js +3 -0
  25. package/lib/src/structures/IBootResult.js.map +1 -0
  26. package/lib/src/{instantiate.d.ts → structures/IBootTtscOptions.d.ts} +2 -12
  27. package/lib/src/structures/IBootTtscOptions.js +3 -0
  28. package/lib/src/structures/IBootTtscOptions.js.map +1 -0
  29. package/lib/src/structures/IFileStats.d.ts +23 -0
  30. package/lib/src/structures/IFileStats.js +3 -0
  31. package/lib/src/structures/IFileStats.js.map +1 -0
  32. package/lib/src/structures/IMemFSHost.d.ts +21 -0
  33. package/lib/src/structures/IMemFSHost.js +3 -0
  34. package/lib/src/structures/IMemFSHost.js.map +1 -0
  35. package/lib/src/structures/ITtscApi.d.ts +86 -0
  36. package/lib/src/structures/ITtscApi.js +3 -0
  37. package/lib/src/structures/ITtscApi.js.map +1 -0
  38. package/lib/src/structures/ITtscBuildOpts.d.ts +7 -0
  39. package/lib/src/structures/ITtscBuildOpts.js +3 -0
  40. package/lib/src/structures/ITtscBuildOpts.js.map +1 -0
  41. package/lib/src/structures/ITtscCompileResult.d.ts +11 -0
  42. package/lib/src/structures/ITtscCompileResult.js +3 -0
  43. package/lib/src/structures/ITtscCompileResult.js.map +1 -0
  44. package/lib/src/structures/ITtscDiagnostic.d.ts +14 -0
  45. package/lib/src/structures/ITtscDiagnostic.js +3 -0
  46. package/lib/src/structures/ITtscDiagnostic.js.map +1 -0
  47. package/lib/src/structures/ITtscFileQuery.d.ts +6 -0
  48. package/lib/src/structures/ITtscFileQuery.js +3 -0
  49. package/lib/src/structures/ITtscFileQuery.js.map +1 -0
  50. package/lib/src/structures/ITtscFountainDiagnosticsResult.d.ts +5 -0
  51. package/lib/src/structures/ITtscFountainDiagnosticsResult.js +3 -0
  52. package/lib/src/structures/ITtscFountainDiagnosticsResult.js.map +1 -0
  53. package/lib/src/structures/ITtscNodeAtPositionResult.d.ts +6 -0
  54. package/lib/src/structures/ITtscNodeAtPositionResult.js +3 -0
  55. package/lib/src/structures/ITtscNodeAtPositionResult.js.map +1 -0
  56. package/lib/src/structures/ITtscNodeInfo.d.ts +13 -0
  57. package/lib/src/structures/ITtscNodeInfo.js +3 -0
  58. package/lib/src/structures/ITtscNodeInfo.js.map +1 -0
  59. package/lib/src/structures/ITtscPluginOpts.d.ts +13 -0
  60. package/lib/src/structures/ITtscPluginOpts.js +3 -0
  61. package/lib/src/structures/ITtscPluginOpts.js.map +1 -0
  62. package/lib/src/structures/ITtscPositionQuery.d.ts +12 -0
  63. package/lib/src/structures/ITtscPositionQuery.js +3 -0
  64. package/lib/src/structures/ITtscPositionQuery.js.map +1 -0
  65. package/lib/src/structures/ITtscReleaseSnapshotResult.d.ts +5 -0
  66. package/lib/src/structures/ITtscReleaseSnapshotResult.js +3 -0
  67. package/lib/src/structures/ITtscReleaseSnapshotResult.js.map +1 -0
  68. package/lib/src/structures/ITtscResult.d.ts +15 -0
  69. package/lib/src/structures/ITtscResult.js +3 -0
  70. package/lib/src/structures/ITtscResult.js.map +1 -0
  71. package/lib/src/structures/ITtscSnapshotHandle.d.ts +5 -0
  72. package/lib/src/structures/ITtscSnapshotHandle.js +3 -0
  73. package/lib/src/structures/ITtscSnapshotHandle.js.map +1 -0
  74. package/lib/src/structures/ITtscSnapshotResult.d.ts +5 -0
  75. package/lib/src/structures/ITtscSnapshotResult.js +3 -0
  76. package/lib/src/structures/ITtscSnapshotResult.js.map +1 -0
  77. package/lib/src/structures/ITtscSnapshotsResult.d.ts +4 -0
  78. package/lib/src/structures/ITtscSnapshotsResult.js +3 -0
  79. package/lib/src/structures/ITtscSnapshotsResult.js.map +1 -0
  80. package/lib/src/structures/ITtscSourceFileTextResult.d.ts +5 -0
  81. package/lib/src/structures/ITtscSourceFileTextResult.js +3 -0
  82. package/lib/src/structures/ITtscSourceFileTextResult.js.map +1 -0
  83. package/lib/src/structures/ITtscSourceFilesResult.d.ts +5 -0
  84. package/lib/src/structures/ITtscSourceFilesResult.js +3 -0
  85. package/lib/src/structures/ITtscSourceFilesResult.js.map +1 -0
  86. package/lib/src/structures/ITtscSymbolAtPositionResult.d.ts +6 -0
  87. package/lib/src/structures/ITtscSymbolAtPositionResult.js +3 -0
  88. package/lib/src/structures/ITtscSymbolAtPositionResult.js.map +1 -0
  89. package/lib/src/structures/ITtscSymbolDeclaration.d.ts +7 -0
  90. package/lib/src/structures/ITtscSymbolDeclaration.js +3 -0
  91. package/lib/src/structures/ITtscSymbolDeclaration.js.map +1 -0
  92. package/lib/src/structures/ITtscSymbolInfo.d.ts +14 -0
  93. package/lib/src/structures/ITtscSymbolInfo.js +3 -0
  94. package/lib/src/structures/ITtscSymbolInfo.js.map +1 -0
  95. package/lib/src/structures/ITtscTransformResult.d.ts +12 -0
  96. package/lib/src/structures/ITtscTransformResult.js +3 -0
  97. package/lib/src/structures/ITtscTransformResult.js.map +1 -0
  98. package/lib/src/structures/ITtscTypeAtPositionResult.d.ts +6 -0
  99. package/lib/src/structures/ITtscTypeAtPositionResult.js +3 -0
  100. package/lib/src/structures/ITtscTypeAtPositionResult.js.map +1 -0
  101. package/lib/src/structures/ITtscTypeInfo.d.ts +7 -0
  102. package/lib/src/structures/ITtscTypeInfo.js +3 -0
  103. package/lib/src/structures/ITtscTypeInfo.js.map +1 -0
  104. package/lib/src/structures/ITtscVersion.d.ts +9 -0
  105. package/lib/src/structures/ITtscVersion.js +3 -0
  106. package/lib/src/structures/ITtscVersion.js.map +1 -0
  107. package/lib/src/{MemFS.d.ts → structures/IWasmExecFS.d.ts} +7 -66
  108. package/lib/src/structures/IWasmExecFS.js +3 -0
  109. package/lib/src/structures/IWasmExecFS.js.map +1 -0
  110. package/lib/src/structures/index.d.ts +29 -0
  111. package/lib/src/structures/index.js +46 -0
  112. package/lib/src/structures/index.js.map +1 -0
  113. package/package.json +2 -2
  114. package/shim-vendor/shim/ast/lint.go +7 -1
  115. package/shim-vendor/shim/checker/shim.go +3 -0
  116. package/shim-vendor/shim/core/shim.go +11 -0
  117. package/src/MemFSError.ts +43 -0
  118. package/src/bootTtsc.ts +212 -0
  119. package/src/{MemFS.ts → createMemFS.ts} +12 -231
  120. package/src/index.ts +5 -17
  121. package/src/parseResult.ts +16 -0
  122. package/src/structures/IBootResult.ts +10 -0
  123. package/src/structures/IBootTtscOptions.ts +21 -0
  124. package/src/structures/IFileStats.ts +23 -0
  125. package/src/structures/IMemFSHost.ts +18 -0
  126. package/src/structures/ITtscApi.ts +101 -0
  127. package/src/structures/ITtscBuildOpts.ts +7 -0
  128. package/src/structures/ITtscCompileResult.ts +12 -0
  129. package/src/structures/ITtscDiagnostic.ts +14 -0
  130. package/src/structures/ITtscFileQuery.ts +7 -0
  131. package/src/structures/ITtscFountainDiagnosticsResult.ts +6 -0
  132. package/src/structures/ITtscNodeAtPositionResult.ts +7 -0
  133. package/src/structures/ITtscNodeInfo.ts +13 -0
  134. package/src/structures/ITtscPluginOpts.ts +13 -0
  135. package/src/structures/ITtscPositionQuery.ts +13 -0
  136. package/src/structures/ITtscReleaseSnapshotResult.ts +5 -0
  137. package/src/structures/ITtscResult.ts +15 -0
  138. package/src/structures/ITtscSnapshotHandle.ts +5 -0
  139. package/src/structures/ITtscSnapshotResult.ts +5 -0
  140. package/src/structures/ITtscSnapshotsResult.ts +4 -0
  141. package/src/structures/ITtscSourceFileTextResult.ts +5 -0
  142. package/src/structures/ITtscSourceFilesResult.ts +5 -0
  143. package/src/structures/ITtscSymbolAtPositionResult.ts +7 -0
  144. package/src/structures/ITtscSymbolDeclaration.ts +7 -0
  145. package/src/structures/ITtscSymbolInfo.ts +15 -0
  146. package/src/structures/ITtscTransformResult.ts +13 -0
  147. package/src/structures/ITtscTypeAtPositionResult.ts +7 -0
  148. package/src/structures/ITtscTypeInfo.ts +7 -0
  149. package/src/structures/ITtscVersion.ts +9 -0
  150. package/src/structures/IWasmExecFS.ts +150 -0
  151. package/src/structures/index.ts +29 -0
  152. package/lib/src/MemFS.js.map +0 -1
  153. package/lib/src/api.d.ts +0 -120
  154. package/lib/src/api.js +0 -23
  155. package/lib/src/api.js.map +0 -1
  156. package/lib/src/instantiate.js +0 -88
  157. package/lib/src/instantiate.js.map +0 -1
  158. package/src/api.ts +0 -145
  159. package/src/instantiate.ts +0 -137
package/host/host.go CHANGED
@@ -3,16 +3,17 @@
3
3
  // JS-side bindings for the host package.
4
4
  //
5
5
  // `Expose` installs `globalThis[apiName]` with the base ttsc endpoints
6
- // (version, build, check, transform) plus a `plugin(name, command, opts)`
7
- // dispatcher that routes into the consumer's registered plugins. The handler
8
- // shape mirrors typia's `ttsc-typia` wasm so JS callers can build a single
9
- // boot helper that works against any host-built binary.
6
+ // (version, build, check, transform) plus `plugin({ name, command, ...opts })`,
7
+ // routing into the consumer's registered plugins. Every async endpoint returns
8
+ // the JS result envelope so callers can build a single boot helper that works
9
+ // against any host-built binary.
10
10
  package host
11
11
 
12
12
  import (
13
13
  "fmt"
14
14
  "os"
15
15
  "runtime"
16
+ "sync"
16
17
  "sync/atomic"
17
18
  "syscall/js"
18
19
  "time"
@@ -26,6 +27,10 @@ var (
26
27
  date = "unknown"
27
28
  )
28
29
 
30
+ // exposed gates Expose so a duplicate call panics instead of leaking the
31
+ // previous batch of js.Funcs + spawning a second keepalive goroutine.
32
+ var exposed atomic.Bool
33
+
29
34
  // API stability: experimental until v1.0; signatures may change between
30
35
  // minor releases. Pin exact versions in production playgrounds.
31
36
  //
@@ -35,15 +40,36 @@ var (
35
40
  // The contract:
36
41
  //
37
42
  // - globalThis[apiName].version() → version banner
38
- // - globalThis[apiName].build({ cwd, tsconfig }) → Promise<CompileResult>
39
- // - globalThis[apiName].check({ cwd, tsconfig }) → Promise<CompileResult>
40
- // - globalThis[apiName].transform({ cwd, tsconfig }) → Promise<TransformResult>
41
- // - globalThis[apiName].plugin({ name, command, ...opts}) → Promise<APIResult>
43
+ // - globalThis[apiName].build({ cwd, tsconfig }) → Promise<ITtscResult>
44
+ // - globalThis[apiName].check({ cwd, tsconfig }) → Promise<ITtscResult>
45
+ // - globalThis[apiName].transform({ cwd, tsconfig }) → Promise<ITtscResult>
46
+ // - globalThis[apiName].plugin({ name, command, ...opts}) → Promise<ITtscResult>
42
47
  // - globalThis[apiName].plugins() → string[] of registered names
43
48
  //
49
+ // build/check/transform encode their structured payloads as JSON in
50
+ // ITtscResult.result. Plugin stdout/stderr are captured in the envelope streams.
51
+ //
44
52
  // A matching readiness resolver is invoked: `globalThis[`${apiName}Ready`]`.
45
53
  // JS callers register this BEFORE go.run begins so they can await wasm boot.
46
54
  func Expose(apiName string, cfg Config) {
55
+ // Refuse double-Expose: the second call would leak every js.FuncOf from
56
+ // the first batch (Go pins js.Funcs and they're not GC'd), spin a second
57
+ // keepalive goroutine forever, and overwrite the ready resolver so JS
58
+ // may await against a different generation than the api globals.
59
+ //
60
+ // Surface the refusal as console.error + a JS-visible reject signal
61
+ // (`globalThis[apiName+"Failed"](err)`) and return without panicking.
62
+ // A panic would terminate the Go runtime before any Ready resolver
63
+ // could fire, and bootTtsc's `await ready` (no timeout) would hang
64
+ // indefinitely with no observable cause.
65
+ if !exposed.CompareAndSwap(false, true) {
66
+ msg := "host.Expose: must be called at most once per wasm instance"
67
+ fmt.Fprintln(os.Stderr, msg)
68
+ if failed := js.Global().Get(apiName + "Failed"); failed.Type() == js.TypeFunction {
69
+ failed.Invoke(js.Global().Get("Error").New(msg))
70
+ }
71
+ return
72
+ }
47
73
  plugins := map[string]Plugin{}
48
74
  pluginNames := make([]string, 0, len(cfg.Plugins))
49
75
  for _, p := range cfg.Plugins {
@@ -69,6 +95,9 @@ func Expose(apiName string, cfg Config) {
69
95
  "plugin": js.FuncOf(jsPluginDispatch(plugins)),
70
96
  "plugins": js.FuncOf(jsPluginsList(pluginNames)),
71
97
  }
98
+ for verb, fn := range fountainAPIMap() {
99
+ api[verb] = fn
100
+ }
72
101
  js.Global().Set(apiName, js.ValueOf(api))
73
102
 
74
103
  if ready := js.Global().Get(apiName + "Ready"); ready.Type() == js.TypeFunction {
@@ -294,6 +323,9 @@ func stringProp(obj js.Value, key string) string {
294
323
  // supported on the wasm target. The temp-file approach works because the
295
324
  // MemFS shim implements file open/write/read.
296
325
  func runWithCapturedIO(task func() int) APIResult {
326
+ captureMu.Lock()
327
+ defer captureMu.Unlock()
328
+
297
329
  prevOut, prevErr := os.Stdout, os.Stderr
298
330
  // The defer is a safety net: if an early return skips the explicit restore
299
331
  // below, os.Stdout/os.Stderr are still restored. The explicit restore that
@@ -329,9 +361,25 @@ func runWithCapturedIO(task func() int) APIResult {
329
361
  }
330
362
  return APIResult{Code: task()}
331
363
  }
364
+ capturing := false
365
+ defer func() {
366
+ if capturing {
367
+ os.Stdout = prevOut
368
+ os.Stderr = prevErr
369
+ }
370
+ if outFile != nil {
371
+ _ = outFile.Close()
372
+ }
373
+ if errFile != nil {
374
+ _ = errFile.Close()
375
+ }
376
+ _ = os.Remove(stdoutPath)
377
+ _ = os.Remove(stderrPath)
378
+ }()
332
379
 
333
380
  os.Stdout = outFile
334
381
  os.Stderr = errFile
382
+ capturing = true
335
383
 
336
384
  code := task()
337
385
 
@@ -340,15 +388,16 @@ func runWithCapturedIO(task func() int) APIResult {
340
388
  _ = outFile.Sync()
341
389
  _ = errFile.Sync()
342
390
  _ = outFile.Close()
391
+ outFile = nil
343
392
  _ = errFile.Close()
393
+ errFile = nil
344
394
 
345
395
  os.Stdout = prevOut
346
396
  os.Stderr = prevErr
397
+ capturing = false
347
398
 
348
399
  stdoutBytes, _ := os.ReadFile(stdoutPath)
349
400
  stderrBytes, _ := os.ReadFile(stderrPath)
350
- _ = os.Remove(stdoutPath)
351
- _ = os.Remove(stderrPath)
352
401
 
353
402
  return APIResult{
354
403
  Code: code,
@@ -361,3 +410,8 @@ func runWithCapturedIO(task func() int) APIResult {
361
410
  // overlap (multiple goroutines could be in runWithCapturedIO concurrently
362
411
  // from independent JS callers).
363
412
  var captureCounter atomic.Uint64
413
+
414
+ // captureMu serializes temporary replacement of package-global stdout/stderr.
415
+ // The temp filenames are unique, but os.Stdout/os.Stderr themselves are shared
416
+ // process state in the wasm runtime.
417
+ var captureMu sync.Mutex
package/host/plugin.go CHANGED
@@ -30,8 +30,9 @@ package host
30
30
  // streams is captured and returned to the JS caller.
31
31
  type Plugin interface {
32
32
  // Name is the npm-style plugin id (e.g. `@ttsc/banner`). The JS side
33
- // passes this exact string when dispatching: `api.plugin("@ttsc/banner",
34
- // "build", opts)`. Names must be unique within a Config.
33
+ // passes this exact string when dispatching:
34
+ // `api.plugin({ name: "@ttsc/banner", command: "build", ...opts })`.
35
+ // Names must be unique within a Config.
35
36
  Name() string
36
37
 
37
38
  // Run dispatches a subcommand. `command` is the verb the JS caller asked
@@ -39,8 +40,8 @@ type Plugin interface {
39
40
  // `args` is the rest of the argv, already prefixed with `--flag=value`
40
41
  // pairs the host built from the JS options object.
41
42
  //
42
- // Return the exit code (0 for success, 2 for usage errors, 3 for runtime
43
- // errors — mirrors the native CLI exit-code contract). Anything written
43
+ // Return the exit code (0 for success, 2 for compiler/config/usage errors, 3
44
+ // for runtime errors — mirrors the native CLI exit-code contract). Anything written
44
45
  // to `os.Stdout` / `os.Stderr` is captured by the host.
45
46
  //
46
47
  // API stability: experimental until v1.0; the signature is expected to
@@ -51,7 +52,7 @@ type Plugin interface {
51
52
  // Config carries the optional registrations the host applies before binding
52
53
  // `globalThis[name]`. Pass `Config{}` for a vanilla ttsc + tsgo wasm.
53
54
  type Config struct {
54
- // Plugins are dispatched through `api.plugin(name, command, opts)` from
55
+ // Plugins are dispatched through `api.plugin({ name, command, ...opts })` from
55
56
  // JS. Their Run methods share the same `os.Stdout` / `os.Stderr` streams
56
57
  // the base build/check/transform endpoints use, so diagnostics render
57
58
  // the same way no matter which lane produced them.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Filesystem error with a POSIX error code and numeric `errno`.
3
+ *
4
+ * Matches the shape of `NodeJS.ErrnoException` so Go's `os` package interprets
5
+ * it as a proper `os.PathError` with a numeric error code. Thrown by the MemFS
6
+ * implementation when a callback would otherwise pass `null` for an impossible
7
+ * filesystem operation (missing path, type mismatch, …).
8
+ */
9
+ export declare class MemFSError extends Error {
10
+ code: string;
11
+ errno: number;
12
+ path?: string;
13
+ syscall?: string;
14
+ constructor(code: string, syscall: string, path?: string);
15
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemFSError = void 0;
4
+ /**
5
+ * Filesystem error with a POSIX error code and numeric `errno`.
6
+ *
7
+ * Matches the shape of `NodeJS.ErrnoException` so Go's `os` package interprets
8
+ * it as a proper `os.PathError` with a numeric error code. Thrown by the MemFS
9
+ * implementation when a callback would otherwise pass `null` for an impossible
10
+ * filesystem operation (missing path, type mismatch, …).
11
+ */
12
+ class MemFSError extends Error {
13
+ code;
14
+ errno;
15
+ path;
16
+ syscall;
17
+ constructor(code, syscall, path) {
18
+ super(`${code}: ${syscall} ${path ?? ""}`.trim());
19
+ this.code = code;
20
+ this.errno = errnoForCode(code);
21
+ this.path = path;
22
+ this.syscall = syscall;
23
+ }
24
+ }
25
+ exports.MemFSError = MemFSError;
26
+ /** Map a POSIX error name to its Linux numeric errno (negative by convention). */
27
+ function errnoForCode(code) {
28
+ switch (code) {
29
+ case "ENOENT":
30
+ return -2;
31
+ case "EBADF":
32
+ return -9;
33
+ case "EEXIST":
34
+ return -17;
35
+ case "ENOTDIR":
36
+ return -20;
37
+ case "EISDIR":
38
+ return -21;
39
+ case "EINVAL":
40
+ return -22;
41
+ case "ESPIPE":
42
+ return -29;
43
+ default:
44
+ return -1;
45
+ }
46
+ }
47
+ //# sourceMappingURL=MemFSError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MemFSError.js","sourceRoot":"","sources":["../../src/MemFSError.ts"],"names":[],"mappings":";;;AAAA;;;;;;;GAOG;AACH,gBAAwB,SAAQ,KAAK;IAC5B,IAAI,CAAS;IACb,KAAK,CAAS;IACd,IAAI,CAAU;IACd,OAAO,CAAU;IACxB,YAAY,IAAY,EAAE,OAAe,EAAE,IAAa;QACtD,KAAK,CAAC,GAAG,IAAI,KAAK,OAAO,IAAI,IAAI,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;;AAED,kFAAkF;AAClF,SAAS,YAAY,CAAC,IAAY;IAChC,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,QAAQ;YACX,OAAO,CAAC,CAAC,CAAC;QACZ,KAAK,OAAO;YACV,OAAO,CAAC,CAAC,CAAC;QACZ,KAAK,QAAQ;YACX,OAAO,CAAC,EAAE,CAAC;QACb,KAAK,SAAS;YACZ,OAAO,CAAC,EAAE,CAAC;QACb,KAAK,QAAQ;YACX,OAAO,CAAC,EAAE,CAAC;QACb,KAAK,QAAQ;YACX,OAAO,CAAC,EAAE,CAAC;QACb,KAAK,QAAQ;YACX,OAAO,CAAC,EAAE,CAAC;QACb;YACE,OAAO,CAAC,CAAC,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -0,0 +1,21 @@
1
+ import type { IBootResult } from "./structures/IBootResult";
2
+ import type { IBootTtscOptions } from "./structures/IBootTtscOptions";
3
+ /**
4
+ * Boot a host-built wasm. Re-entrant only if you reuse the same `host`.
5
+ *
6
+ * Concurrent calls with the same `(apiName, wasmUrl)` pair share the same
7
+ * in-flight boot. Calls with the same `apiName` but different `wasmUrl` are
8
+ * serialized via `bootChainByApiName` so they don't race on the shared
9
+ * `globalThis[apiName+"Ready"]` resolver slot. On rejection the cache entries
10
+ * are cleared so the next call retries from scratch.
11
+ *
12
+ * **Single-Worker caveat.** Even with the chain, a second boot loaded into the
13
+ * SAME Worker after a first boot completes will overlay its Go runtime on top
14
+ * of the first — `importScripts(wasmExecUrl)` rebinds `globalThis.Go`, and the
15
+ * first wasm's keepalive goroutine keeps running through the new runtime's
16
+ * js-bridge tables. The serialization is sufficient for the typical use case
17
+ * (one boot per Worker over the page's lifetime) but DOES NOT make a Worker
18
+ * safe to host two wasm instances at once. Create a fresh Worker per concurrent
19
+ * wasm.
20
+ */
21
+ export declare function bootTtsc(options: IBootTtscOptions): Promise<IBootResult>;
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bootTtsc = bootTtsc;
4
+ // Boots a host-built wasm and returns the JS-side handle.
5
+ //
6
+ // Order of operations matters: wasm_exec.js installs default no-op fs/process
7
+ // shims if `globalThis.fs` is missing at load time, so we must install our
8
+ // MemFS BEFORE importing wasm_exec.js.
9
+ //
10
+ // The boot helper is parameterized by `apiName` so any wasm built with
11
+ // `host.Expose(...)` can be loaded the same way. The base wasm uses "ttsc";
12
+ // downstream consumers pick their own (e.g. "ttscPlayground", "ttscTypia").
13
+ const createMemFS_1 = require("./createMemFS");
14
+ /**
15
+ * Per-(apiName, wasmUrl) single-flight cache for boots. Keying on apiName alone
16
+ * would let a second call with the same apiName but a different wasmUrl
17
+ * silently return the cached IBootResult of the first wasm — the caller would
18
+ * think they booted a fresh binary while the cached one stayed in place. The
19
+ * composite key lets HMR / cache-busting query strings get a fresh boot while
20
+ * still single-flighting genuine concurrent duplicate calls.
21
+ */
22
+ const bootsInFlight = new Map();
23
+ /**
24
+ * Per-apiName serialization chain. Two concurrent boots with the same apiName
25
+ * but different wasmUrls each install their own `globalThis[apiName
26
+ *
27
+ * - "Ready"]`resolver — they would race and the second would overwrite the first,
28
+ * stranding the first boot's await. The chain serializes them so one boot's
29
+ * Go-side`Ready.Invoke()` always lands on the resolver that boot installed.
30
+ */
31
+ const bootChainByApiName = new Map();
32
+ function bootKey(apiName, wasmUrl) {
33
+ return `${apiName}|${resolveWasmUrl(wasmUrl)}`;
34
+ }
35
+ /**
36
+ * Resolve `wasmUrl` against the current document base before keying so that
37
+ * `./playground.wasm`, `/compiler/playground.wasm`, and the fully qualified
38
+ * absolute href all collapse to the same cache entry instead of spawning
39
+ * duplicate boots. Falls back to the raw string when no base is available
40
+ * (Node-side tests, non-DOM workers).
41
+ */
42
+ function resolveWasmUrl(wasmUrl) {
43
+ try {
44
+ const base = typeof location !== "undefined" ? location.href : "http://local/";
45
+ return new URL(wasmUrl, base).href;
46
+ }
47
+ catch {
48
+ return wasmUrl;
49
+ }
50
+ }
51
+ /**
52
+ * Boot a host-built wasm. Re-entrant only if you reuse the same `host`.
53
+ *
54
+ * Concurrent calls with the same `(apiName, wasmUrl)` pair share the same
55
+ * in-flight boot. Calls with the same `apiName` but different `wasmUrl` are
56
+ * serialized via `bootChainByApiName` so they don't race on the shared
57
+ * `globalThis[apiName+"Ready"]` resolver slot. On rejection the cache entries
58
+ * are cleared so the next call retries from scratch.
59
+ *
60
+ * **Single-Worker caveat.** Even with the chain, a second boot loaded into the
61
+ * SAME Worker after a first boot completes will overlay its Go runtime on top
62
+ * of the first — `importScripts(wasmExecUrl)` rebinds `globalThis.Go`, and the
63
+ * first wasm's keepalive goroutine keeps running through the new runtime's
64
+ * js-bridge tables. The serialization is sufficient for the typical use case
65
+ * (one boot per Worker over the page's lifetime) but DOES NOT make a Worker
66
+ * safe to host two wasm instances at once. Create a fresh Worker per concurrent
67
+ * wasm.
68
+ */
69
+ function bootTtsc(options) {
70
+ const apiName = options.apiName ?? "ttsc";
71
+ const key = bootKey(apiName, options.wasmUrl);
72
+ const inflight = bootsInFlight.get(key);
73
+ if (inflight)
74
+ return inflight;
75
+ const prior = bootChainByApiName.get(apiName) ?? Promise.resolve();
76
+ const promise = prior
77
+ .catch(() => {
78
+ /* don't propagate a prior boot's rejection — let this one run */
79
+ })
80
+ .then(() => bootTtscOnce(options, apiName))
81
+ .catch((err) => {
82
+ bootsInFlight.delete(key);
83
+ throw err;
84
+ });
85
+ bootsInFlight.set(key, promise);
86
+ // Track the chain head for this apiName so the next boot waits on it.
87
+ // Swallow on the chain head specifically: we already throw to the
88
+ // immediate caller; surfacing it through the chain would reject every
89
+ // subsequent boot just because this one failed.
90
+ bootChainByApiName.set(apiName, promise.catch(() => { }));
91
+ return promise;
92
+ }
93
+ async function bootTtscOnce(options, apiName) {
94
+ const wasmUrl = options.wasmUrl;
95
+ const wasmExecUrl = options.wasmExecUrl ?? defaultWasmExecUrl(wasmUrl);
96
+ const host = options.host ?? (0, createMemFS_1.createMemFS)();
97
+ const globalAny = globalThis;
98
+ // Only install fs / process if they aren't already in place. A caller
99
+ // booting a second wasm over the same MemFS reuses the same shims.
100
+ if (!globalAny.fs)
101
+ globalAny.fs = host.fs;
102
+ if (!globalAny.process)
103
+ globalAny.process = createProcessShim();
104
+ // wasm_exec.js installs `globalThis.Go`. It also reads globalThis.fs at
105
+ // module-eval time, so this import must follow the assignment above.
106
+ importScripts(wasmExecUrl);
107
+ // Race the Ready resolver against a Failed signal so a wasm-side fault
108
+ // (e.g. `host.Expose` refusing a duplicate call) surfaces here instead of
109
+ // hanging on `await ready` forever. `go.run` is fire-and-forget so its
110
+ // own rejection cannot reach this promise without an explicit channel.
111
+ const ready = new Promise((resolve, reject) => {
112
+ globalAny[apiName + "Ready"] = () => {
113
+ delete globalAny[apiName + "Failed"];
114
+ resolve();
115
+ };
116
+ globalAny[apiName + "Failed"] = (err) => {
117
+ delete globalAny[apiName + "Ready"];
118
+ reject(err instanceof Error ? err : new Error(String(err)));
119
+ };
120
+ });
121
+ const goCtor = globalAny.Go;
122
+ if (typeof goCtor !== "function") {
123
+ throw new Error(`bootTtsc: globalThis.Go was not installed by ${wasmExecUrl} — the file may not have loaded (CSP block, wrong content type, 404), or it is not the wasm_exec.js shipped with the Go toolchain.`);
124
+ }
125
+ const go = new goCtor();
126
+ const response = await fetch(wasmUrl);
127
+ if (!response.ok) {
128
+ throw new Error(`bootTtsc: failed to fetch ${wasmUrl}: ${response.status}`);
129
+ }
130
+ const wasm = await WebAssembly.instantiateStreaming(response, go.importObject);
131
+ // go.run never resolves until the wasm exits; we don't await it.
132
+ void go.run(wasm.instance);
133
+ await ready;
134
+ const api = globalAny[apiName];
135
+ if (!api)
136
+ throw new Error(`bootTtsc: ${apiName} global was not set — was the wasm built with host.Expose(${JSON.stringify(apiName)}, ...)?`);
137
+ return { api, host };
138
+ }
139
+ /**
140
+ * Derive the `wasm_exec.js` URL from the wasm URL by replacing the filename.
141
+ *
142
+ * If `wasmUrl` has no directory component, returns `"wasm_exec.js"` (same
143
+ * directory as the caller's base URL).
144
+ */
145
+ function defaultWasmExecUrl(wasmUrl) {
146
+ const slash = wasmUrl.lastIndexOf("/");
147
+ if (slash < 0)
148
+ return "wasm_exec.js";
149
+ return wasmUrl.slice(0, slash + 1) + "wasm_exec.js";
150
+ }
151
+ /**
152
+ * Minimal `process` shim required by `wasm_exec.js` in non-Node environments.
153
+ *
154
+ * Go's js/wasm bridge reads `process.pid`, `process.ppid`, and calls
155
+ * `process.cwd()`. `getuid`/`getgid` and friends return `-1` (root-less).
156
+ * `umask` and `getgroups` are never exercised by the compiler but are included
157
+ * for completeness so unexpected calls surface as clear errors.
158
+ */
159
+ function createProcessShim() {
160
+ return {
161
+ getuid: () => -1,
162
+ getgid: () => -1,
163
+ geteuid: () => -1,
164
+ getegid: () => -1,
165
+ getgroups: () => {
166
+ throw new Error("not implemented");
167
+ },
168
+ pid: -1,
169
+ ppid: -1,
170
+ umask: () => {
171
+ throw new Error("not implemented");
172
+ },
173
+ cwd: () => "/",
174
+ chdir: () => {
175
+ /* no-op; the workspace lives inside the MemFS */
176
+ },
177
+ };
178
+ }
179
+ //# sourceMappingURL=bootTtsc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootTtsc.js","sourceRoot":"","sources":["../../src/bootTtsc.ts"],"names":[],"mappings":";;;AAAA,0DAA0D;AAC1D,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,uCAAuC;AACvC,EAAE;AACF,uEAAuE;AACvE,4EAA4E;AAC5E,4EAA4E;AAC5E,+CAA4C;AAO5C;;;;;;;GAOG;AACH,MAAM,aAAa,GAAG,IAAI,GAAG,EAAgC,CAAC;AAE9D;;;;;;;GAOG;AACH,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAA4B,CAAC;AAE/D,SAAS,OAAO,CAAC,OAAe,EAAE,OAAe;IAC/C,OAAO,GAAG,OAAO,IAAI,cAAc,CAAC,OAAO,CAAC,EAAE,CAAC;AACjD,CAAC;AAED;;;;;;GAMG;AACH,SAAS,cAAc,CAAC,OAAe;IACrC,IAAI,CAAC;QACH,MAAM,IAAI,GACR,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC;QACpE,OAAO,IAAI,GAAG,CAAC,OAAO,EAAE,IAAI,C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,CAAC,CAAC;QACrC,CAAC;QACD,GAAG,EAAE,CAAC,CAAC;QACP,IAAI,EAAE,CAAC,CAAC;QACR,KAAK,EAAE,GAAG,EAAE;YACV,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;QACrC,CAAC;QACD,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG;QACd,KAAK,EAAE,GAAG,EAAE;YACV,iDAAiD;QACnD,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { IMemFSHost } from "./structures/IMemFSHost";
2
+ /**
3
+ * Create an in-memory filesystem suitable for use as `globalThis.fs` inside a
4
+ * Go/wasm runtime.
5
+ *
6
+ * The returned host exposes the low-level `fs` object (install it on
7
+ * `globalThis.fs` before loading `wasm_exec.js`) and convenience helpers
8
+ * (`writeFile`, `readFile`, `mkdirp`, …) for seeding source files and reading
9
+ * compiler output without touching the real filesystem.
10
+ */
11
+ export declare function createMemFS(): IMemFSHost;