-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild.js
70 lines (63 loc) · 2.6 KB
/
build.js
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
const { build } = require('esbuild');
const replace = require('replace-in-file');
const fs = require('fs');
const package = require("./package.json");
(async () => {
let contractFunctions = fs.readdirSync('./src/functions/').map(contractFunction => contractFunction.slice(0, -(`.js`).length))
let contractFunctionsContents = contractFunctions.map(cf => fs.readFileSync("./src/functions/" + cf + ".js").toString())
let contractFunctionsDescriptions = contractFunctionsContents.map(cnt => extractDescription(cnt))
let specmd = `# ${package.name} v${package.version}\n\n${package.description}\n\n` +
contractFunctions.map((cf, cfi) => `\`${cf}\` \n
> ${contractFunctionsDescriptions[cfi]}\n`).join("\n")
fs.writeFileSync("./SPEC.md", specmd)
let contractCode = `//THIS FILE IS AUTOGENERATED BY build.js, PLEASE DO NOT EDIT IT
export async function handle(state, action) {
if (!action.input || typeof action.input !== "object" || typeof action.input.function !== "string") {
throw new ContractError("Invalid input");
}
const functionMap = {
${contractFunctions.map(cf => "\"" + cf + "\":require(\"./functions/" + cf + ".js\")").join(",\n")}
};
const selectedFunction = functionMap[action.input.function];
if (!selectedFunction) {
throw new ContractError(\`Function '\${action.input.function}' not found\`);
}
try {
return await selectedFunction(state, action, handle);
} catch (error) {
throw new ContractError(\`Error executing function '\${action.input.function}': \${ error.message }\`);
}
}
`
fs.writeFileSync("./src/contract.js", contractCode)
const contracts = ['/contract.js'];
// Build and bundle the contract code
build({
entryPoints: ["./src/contract.js"],
outdir: './dist',
minify: false,
bundle: true,
format: 'iife',
})
.catch(() => process.exit(1))
// Note: Warp SDK currently does not support files in IIFE bundle format, so we need to remove the "iife" part ;-)
// Update: it does since 0.4.31, but because viewblock.io is still incompatible with this version, leaving as is for now.
.finally(() => {
// Remove the "iife" part from the bundled file
const files = contracts.map((source) => {
return `./dist${source}`.replace('.ts', '.js');
});
replace.sync({
files: files,
from: [/\(\(\) => {/g, /}\)\(\);/g],
to: '',
countMatches: true,
});
});
})()
function extractDescription(functionCode) {
let descRegex = /(?<=\/\*function\-description)(.*?)(?=function-description\*\/)/s
let res = descRegex.exec(functionCode)
if (!res) { return "" }
return res[0].trim()
}