summary refs log tree commit diff
path: root/ui/util/generate-tauri-bindings.js
blob: 11c8b61f4861d8ba7c9e7fb32d57c587fb0d4b5e (plain)
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
import path from 'node:path'
import {existsSync, readFileSync, writeFileSync} from 'node:fs'

const typedefPath = path.join(import.meta.dirname, '../../target/doc/foxfleet_applib.json')
const outputPath = path.join(import.meta.dirname, '../bindings/index.ts')

if (!existsSync(typedefPath)) {
  console.error(`Could not find rustdoc type definitions`)
  process.exit(1)
}

const commandPrefix = '::foxfleet_applib::commands'
const {root, index} = JSON.parse(readFileSync(typedefPath))

function traverseModuleForFunctions(startIndex, namespace = '') {
  const node = index[startIndex]

  if (!node) return []

  // If it's a module
  if (node.inner?.module) {
    const childItems = node.inner.module.items
    return childItems.map(childIndex => traverseModuleForFunctions(childIndex, namespace + '::' + node.name))
  }

  // If it's a function
  if (node.inner?.function) {
    return {...node, namespace}
  }

  return []
}

function getParameters(functionDef) {
  let params = []

  const skipped = ['tauri::State', 'tauri::AppHandle']
  for (const [name, typedef] of functionDef.inner.function.sig.inputs) {
    const typeName = typedef.resolved_path?.name
    if (skipped.includes(typeName)) continue


    const type = typedef.resolved_path ? convertType(typedef.resolved_path) : convertType(typedef.borrowed_ref)
    params.push({name, type})
  }

  return params
}

function getReturnType(functionDef) {
  if (functionDef.inner.function.sig.output.resolved_path.name === "Result")
    return convertType(functionDef.inner.function.sig.output.resolved_path.args.angle_bracketed.args[0].type.resolved_path)

  return convertType(functionDef.inner.function.sig.output.resolved_path)
}

let imports = []

function convertType(typeDef) {
  if (typeof typeDef === 'undefined') return undefined

  const {name, id, args: {angle_bracketed: {args = []} = {}} = {}} = typeDef

  if(args.length && name !== 'Vec') throw new Error(`Unknown generic type ${name}`)
  if(name === 'Vec' && !args) throw new Errror(`Unknown inner type for vec`)
  
  if(name === 'Vec') return convertType(args[0].type.resolved_path) + '[]'
  if(name === 'Result') return `Promise<${convertType(args[0].type.resolved_path)}>`

  if(name === 'String' || typeDef?.type?.primitive === 'str') return 'string'

  // Otherwise look up the definition and make sure it has the ![derive(TS)]
  const def = index[id]
  if (!def.attrs || !def.attrs.includes('#[ts(export)]')) {
    throw new Error(`Complex type ${name} does not have Typescript definitions exported`)
  }

  imports.push(name)
  return name
}

function convertCamelCase(name) {
  return name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
}

function convertUpperCamelCase(name) {
  return name.replace(/(_|^)([a-z])/g, (_, _first, letter) => letter.toUpperCase())
}

const publicFunctions = traverseModuleForFunctions(root).flat(Infinity)
const commandFunctions = publicFunctions
  .filter(({namespace}) => namespace.startsWith(commandPrefix))
  .map(({namespace, ...rest}) => ({...rest, namespace: namespace.replace(commandPrefix + '::', '')}))

const namespaces = {}
for(const func of commandFunctions) {
  if(!namespaces[func.namespace])
    namespaces[func.namespace] = []

  namespaces[func.namespace].push(func)
}

const invokeLine = `import { invoke } from '@tauri-apps/api/core';`
const namespaceBlocks = Object.keys(namespaces).map(namespace => {
  const functions = namespaces[namespace]
  const functionBlocks = functions.map(func => {
    const params = getParameters(func)
    const parametersString = params.map(({name, type}) => `${name}: ${type}`).join(', ')
    let returnTypeString = getReturnType(func)
    if (!/^Promise<.*>$/.test(returnTypeString))
      returnTypeString = `Promise<${returnTypeString}>`

    return `
  export async function ${convertCamelCase(func.name)}(${parametersString}): ${returnTypeString} {
    return await invoke('${func.name}', {${params.map(param => convertCamelCase(param.name) + ': ' + param.name).join(', ')}}) as any as ${returnTypeString}
  }`
  })

  return `export namespace ${convertUpperCamelCase(namespace)} {\n${functionBlocks.join('\n')}\n}`
})
// This needs to be last so it gets populated by the above calls
const importLines = imports.map(type => `import type {${type}} from './${type}.ts'`)

const fileData = `
${invokeLine}
${importLines}

${namespaceBlocks.join('\n\n')}
`

writeFileSync(outputPath, fileData)