wasm\api.mbt

0% · 0 / 118 points · 222 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # npm-wasm 导出层(S12)
  3. 3///
  4. 4/// 只做三件事:把 base64 当输入、把 JSON(base64) 当输出。
  5. 5/// 这样 wasm-gc 侧只需要 JS String Builtin(`wasm:js-string`),
  6. 6/// 不需要在 JS 里操作 MoonBit 的 GC 对象;Node 侧用 Buffer 做 base64 转换。
  7. 7///
  8. 8/// 导出的三个入口:
  9. 9/// - `image_info(base64) -> JSON`:格式/尺寸/通道/体积;
  10. 10/// - `image_convert(base64, format, quality) -> JSON{data}`:可写格式互转,`format=best` 选最小;
  11. 11/// - `image_resize(base64, w, h, mode, format, quality) -> JSON{data}`:cover / contain 缩放。
  12. 12
  13. 13///|
  14. 14/// 本包自己的 JSON 对象别名(不复用 imgcli 的私有类型)。
  15. 15type Out = Map[String, @json.Json]
  16. 16
  17. 17///|
  18. 18fn jstr(s : String) -> @json.Json {
  19. 19○ @json.Json::string(s)
  20. 20}
  21. 21
  22. 22///|
  23. 23fn jnum(n : Int32) -> @json.Json {
  24. 24○ @json.Json::number(n.to_double())
  25. 25}
  26. 26
  27. 27///|
  28. 28fn jbool(b : Bool) -> @json.Json {
  29. 29○ @json.Json::boolean(b)
  30. 30}
  31. 31
  32. 32///|
  33. 33fn format_name(f : @types.ImageFormat) -> String {
  34. 34○ match f {
  35. 35○ @types.ImageFormat::Png => "png"
  36. 36○ @types.ImageFormat::Jpeg => "jpeg"
  37. 37○ @types.ImageFormat::Bmp => "bmp"
  38. 38○ @types.ImageFormat::Gif => "gif"
  39. 39○ @types.ImageFormat::Webp => "webp"
  40. 40○ @types.ImageFormat::Qoi => "qoi"
  41. 41○ @types.ImageFormat::Pnm => "pnm"
  42. 42○ @types.ImageFormat::Tga => "tga"
  43. 43○ _ => "unknown"
  44. 44 }
  45. 45}
  46. 46
  47. 47///|
  48. 48fn parse_format_arg(s : String) -> @types.ImageFormat raise @types.ImageError {
  49. 49○ match s.to_lower() {
  50. 50○ "png" => @types.ImageFormat::Png
  51. 51○ "jpeg" | "jpg" => @types.ImageFormat::Jpeg
  52. 52○ "bmp" => @types.ImageFormat::Bmp
  53. 53○ "gif" => @types.ImageFormat::Gif
  54. 54○ "webp" => @types.ImageFormat::Webp
  55. 55○ "qoi" => @types.ImageFormat::Qoi
  56. 56○ "pnm" | "ppm" => @types.ImageFormat::Pnm
  57. 57○ "tga" => @types.ImageFormat::Tga
  58. 58 _ =>
  59. 59○ raise @types.ImageError::Process(
  60. 60 @types.ErrorCode::InvalidArgument,
  61. 61 "不支持的输出格式: \{s}(可用 png/jpeg/webp/bmp/qoi/pnm/tga/gif/best)",
  62. 62 )
  63. 63 }
  64. 64}
  65. 65
  66. 66///|
  67. 67fn b64_decode(text : String) -> Bytes raise @types.ImageError {
  68. 68○ @base64.decode(text) catch {
  69. 69 _ =>
  70. 70○ raise @types.ImageError::Decode(
  71. 71 @types.ErrorCode::InvalidArgument,
  72. 72 "base64 解码失败:输入不是合法的 base64",
  73. 73 )
  74. 74 }
  75. 75}
  76. 76
  77. 77///|
  78. 78fn load(b64 : String) -> (@types.Image, Bytes) raise @types.ImageError {
  79. 79○ let input = b64_decode(b64)
  80. 80○ let img = @lib.decode_with_limits(
  81. 81 input,
  82. 82○ @types.DecodeLimits::default_limits(),
  83. 83 )
  84. 84 (img, input)
  85. 85}
  86. 86
  87. 87///|
  88. 88fn err_json(e : @types.ImageError) -> String {
  89. 89○ let code = e.code()
  90. 90○ @json.Json::object({
  91. 91○ "ok": jbool(false),
  92. 92○ "code": jstr(code),
  93. 93○ "message": jstr(e.message()),
  94. 94○ "hint": jstr(@types.image_error_hint(code)),
  95. 95○ }).stringify()
  96. 96}
  97. 97
  98. 98///|
  99. 99fn ok_meta(img : @types.Image, extra : Out) -> Out {
  100. 100○ extra["ok"] = jbool(true)
  101. 101○ extra["width"] = jnum(img.width.to_int())
  102. 102○ extra["height"] = jnum(img.height.to_int())
  103. 103○ extra["channels"] = jnum(img.channels.to_int())
  104. 104 extra
  105. 105}
  106. 106
  107. 107///|
  108. 108fn info_impl(b64 : String) -> String raise @types.ImageError {
  109. 109○ let input = b64_decode(b64)
  110. 110○ let (w, h) = @lib.check_decode_budget(
  111. 111 input,
  112. 112○ @types.DecodeLimits::default_limits(),
  113. 113 )
  114. 114○ @json.Json::object({
  115. 115○ "ok": jbool(true),
  116. 116○ "format": jstr(format_name(@lib.detect_format(input))),
  117. 117○ "width": jnum(w.to_int()),
  118. 118○ "height": jnum(h.to_int()),
  119. 119○ "bytes": jnum(input.length()),
  120. 120○ }).stringify()
  121. 121}
  122. 122
  123. 123///|
  124. 124fn convert_impl(
  125. 125 b64 : String,
  126. 126 format : String,
  127. 127 quality : Int32,
  128. 128) -> String raise @types.ImageError {
  129. 129○ let (img, _) = load(b64)
  130. 130○ let enc : @lib.EncodedImage = if format.to_lower() == "best" {
  131. 131○ @lib.encode_best(img, quality)
  132. 132 } else {
  133. 133○ let fmt = parse_format_arg(format)
  134. 134○ let data = @lib.save_image_with_quality(img, fmt, quality) catch {
  135. 135○ e => raise @types.image_error_from_load(e)
  136. 136 }
  137. 137 { format: fmt, bytes: data, }
  138. 138 }
  139. 139○ let out = ok_meta(img, {
  140. 140○ "format": jstr(format_name(enc.format)),
  141. 141○ "bytes": jnum(enc.bytes.length()),
  142. 142○ "data": jstr(@base64.encode(enc.bytes)),
  143. 143 })
  144. 144○ @json.Json::object(out).stringify()
  145. 145}
  146. 146
  147. 147///|
  148. 148fn resize_impl(
  149. 149 b64 : String,
  150. 150 w : Int32,
  151. 151 h : Int32,
  152. 152 mode : String,
  153. 153 format : String,
  154. 154 quality : Int32,
  155. 155) -> String raise @types.ImageError {
  156. 156○ if w <= 0 || h <= 0 {
  157. 157○ raise @types.ImageError::Process(
  158. 158 @types.ErrorCode::InvalidArgument,
  159. 159 "resize 需要正整数宽高(收到 \{w}x\{h})",
  160. 160 )
  161. 161 }
  162. 162○ let (img, _) = load(b64)
  163. 163 let resized = try {
  164. 164○ if mode.to_lower() == "contain" {
  165. 165○ let fill : Array[Byte] = []
  166. 166 for _ in 0..<img.channels {
  167. 167○ fill.push(b'\xff')
  168. 168 }
  169. 169○ @transform.resize_to_contain(img, w, h, fill)
  170. 170 } else {
  171. 171○ @transform.resize_to_cover(img, w, h)
  172. 172 }
  173. 173 } catch {
  174. 174○ e => raise @types.image_error_from_load(e)
  175. 175 }
  176. 176○ let enc : @lib.EncodedImage = if format.to_lower() == "best" {
  177. 177○ @lib.encode_best(resized, quality)
  178. 178 } else {
  179. 179○ let fmt = parse_format_arg(format)
  180. 180○ let data = @lib.save_image_with_quality(resized, fmt, quality) catch {
  181. 181○ e => raise @types.image_error_from_load(e)
  182. 182 }
  183. 183 { format: fmt, bytes: data, }
  184. 184 }
  185. 185○ let out = ok_meta(resized, {
  186. 186○ "format": jstr(format_name(enc.format)),
  187. 187○ "bytes": jnum(enc.bytes.length()),
  188. 188○ "data": jstr(@base64.encode(enc.bytes)),
  189. 189 })
  190. 190○ @json.Json::object(out).stringify()
  191. 191}
  192. 192
  193. 193///|
  194. 194#export_name("image_info")
  195. 195pub fn image_info(b64 : String) -> String {
  196. 196○ info_impl(b64) catch {
  197. 197○ e => err_json(e)
  198. 198 }
  199. 199}
  200. 200
  201. 201///|
  202. 202#export_name("image_convert")
  203. 203pub fn image_convert(b64 : String, format : String, quality : Int32) -> String {
  204. 204○ convert_impl(b64, format, quality) catch {
  205. 205○ e => err_json(e)
  206. 206 }
  207. 207}
  208. 208
  209. 209///|
  210. 210#export_name("image_resize")
  211. 211pub fn image_resize(
  212. 212 b64 : String,
  213. 213 w : Int32,
  214. 214 h : Int32,
  215. 215 mode : String,
  216. 216 format : String,
  217. 217 quality : Int32,
  218. 218) -> String {
  219. 219○ resize_impl(b64, w, h, mode, format, quality) catch {
  220. 220○ e => err_json(e)
  221. 221 }
  222. 222}