@typesol/cli 0.49.0 → 0.50.0
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.
- package/CHANGELOG.md +397 -0
- package/NOTICE +9 -0
- package/README.md +25 -8
- package/SECURITY.md +4 -3
- package/dist/compiler/analyze.d.ts +2 -0
- package/dist/compiler/analyze.js +7 -1
- package/dist/compiler/emit/base.d.ts +4 -3
- package/dist/compiler/emit/base.js +9 -3
- package/dist/compiler/emit/borsh.js +8 -8
- package/dist/compiler/emit/calls.d.ts +6 -0
- package/dist/compiler/emit/calls.js +71 -12
- package/dist/compiler/emit/cpi-core.js +3 -3
- package/dist/compiler/emit/cpi.js +2 -2
- package/dist/compiler/emit/expressions.d.ts +1 -0
- package/dist/compiler/emit/expressions.js +12 -0
- package/dist/compiler/emit/function.js +12 -8
- package/dist/compiler/emit/program.js +8 -2
- package/dist/compiler/emit/rbtree.js +1 -1
- package/dist/compiler/emit/shared.d.ts +12 -2
- package/dist/compiler/emit/shared.js +26 -6
- package/dist/compiler/emit/statements.d.ts +8 -1
- package/dist/compiler/emit/statements.js +53 -5
- package/dist/compiler/emit/storage.js +12 -10
- package/dist/compiler/emit/views.js +1 -1
- package/dist/compiler/index.d.ts +15 -1
- package/dist/compiler/index.js +50 -9
- package/dist/keys.d.ts +12 -1
- package/dist/keys.js +57 -7
- package/dist/workspace.d.ts +8 -0
- package/dist/workspace.js +90 -15
- package/docker/deps/0.50.0.lock.json +1206 -0
- package/docs/architecture.md +1 -1
- package/docs/audit.md +13 -12
- package/docs/case-study-jito-mev.md +14 -14
- package/docs/case-study-marginfi.md +127 -127
- package/docs/case-study-multisig.md +16 -4
- package/docs/case-study-raydium-clmm.md +44 -28
- package/docs/case-study-raydium-cp-swap.md +18 -18
- package/docs/cli.md +4 -3
- package/docs/language-accounts.md +16 -10
- package/docs/language-basics.md +4 -1
- package/docs/language-builtins.md +4 -2
- package/docs/language-cpi.md +34 -0
- package/docs/language-native.md +50 -4
- package/docs/language-statements.md +2 -1
- package/docs/language-types.md +13 -3
- package/docs/runtime.md +19 -2
- package/docs/security-model.md +4 -3
- package/docs/stability.md +5 -4
- package/docs/testing.md +6 -2
- package/lib/typesol.d.ts +25 -3
- package/llms-full.txt +136 -31
- package/package.json +1 -1
- package/releases/0.49.0.json +857 -0
- package/runtime/typesol_builtins.c +47 -2
- package/runtime/typesol_rt.h +129 -3
|
@@ -664,7 +664,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
664
664
|
const closure = { node: st.fn, name: "map's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
|
|
665
665
|
const sc = this.tmp("lm_s");
|
|
666
666
|
this.line(`TSS_${S.name} ${sc}__v;`);
|
|
667
|
-
this.line(`
|
|
667
|
+
this.line(`TS_ZERO_LOCAL(&${sc}__v, sizeof(${sc}__v));`);
|
|
668
668
|
this.expandClosure(closure, [element, idx].slice(0, st.fn.parameters.length), st.fn, {
|
|
669
669
|
lv: `${sc}__v`,
|
|
670
670
|
type: { kind: "struct", name: S.name },
|
|
@@ -1370,7 +1370,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1370
1370
|
if (frame.type.kind === "pubkey")
|
|
1371
1371
|
this.line(`${frame.result} = *(${v.c});`);
|
|
1372
1372
|
else if (frame.type.kind === "option" && v.isNull)
|
|
1373
|
-
this.line(`
|
|
1373
|
+
this.line(`TS_ZERO_LOCAL(&${frame.result}, sizeof(${frame.result}));`);
|
|
1374
1374
|
else
|
|
1375
1375
|
this.line(`${frame.result} = ${this.ownedString(v).c};`);
|
|
1376
1376
|
this.line(`goto ${frame.label};`);
|
|
@@ -1485,7 +1485,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1485
1485
|
continue;
|
|
1486
1486
|
}
|
|
1487
1487
|
if (ts.isArrayBindingPattern(d.name)) {
|
|
1488
|
-
|
|
1488
|
+
const init = d.initializer;
|
|
1489
|
+
if (init && ts.isCallExpression(init) && this.exportName(init.expression) === "getReturnData")
|
|
1490
|
+
this.programAndReturnData(d, d.name, init, mutable);
|
|
1491
|
+
else
|
|
1492
|
+
this.addressAndBump(d, d.name, mutable);
|
|
1489
1493
|
continue;
|
|
1490
1494
|
}
|
|
1491
1495
|
if (!ts.isIdentifier(d.name) || !d.initializer)
|
|
@@ -1830,15 +1834,59 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1830
1834
|
if (bytes > room)
|
|
1831
1835
|
this.fail(at, `this local takes ${bytes} bytes and the heap holds ${room} (raise HEAP_SIZE_KIB, at most 256)`);
|
|
1832
1836
|
}
|
|
1837
|
+
/**
|
|
1838
|
+
* `const [program, data] = getReturnData()`: Rust's `get_return_data()`, the return data as the runtime holds it
|
|
1839
|
+
* (sol_get_return_data): the program that set it and its bytes, read into 1 KiB of this function's stack frame (the
|
|
1840
|
+
* runtime's maximum, so nothing is cut). Rust's `None` is `data.length === 0n` (the runtime keeps no empty return
|
|
1841
|
+
* data), with `program` then all zeros.
|
|
1842
|
+
*/
|
|
1843
|
+
programAndReturnData(d, pattern, call, mutable) {
|
|
1844
|
+
const usage = "const [program, data] = getReturnData()";
|
|
1845
|
+
if (mutable)
|
|
1846
|
+
this.fail(d, `bind them with const: ${usage}`);
|
|
1847
|
+
if (d.type)
|
|
1848
|
+
this.fail(d.type, "leave the type out: the program is a Pubkey and the data a read-only list of u8 (InstructionBytes)");
|
|
1849
|
+
if (call.arguments.length)
|
|
1850
|
+
this.fail(call, "getReturnData() takes no arguments");
|
|
1851
|
+
if (pattern.elements.length > 2)
|
|
1852
|
+
this.fail(pattern, `getReturnData gives two values: ${usage}`);
|
|
1853
|
+
const names = pattern.elements.map((el) => {
|
|
1854
|
+
if (ts.isOmittedExpression(el))
|
|
1855
|
+
return undefined;
|
|
1856
|
+
if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name))
|
|
1857
|
+
this.fail(el, `name the program and the data: ${usage}`);
|
|
1858
|
+
const name = el.name.text;
|
|
1859
|
+
if (this.scopes.at(-1).has(name))
|
|
1860
|
+
this.fail(el.name, `"${name}" is already declared`);
|
|
1861
|
+
if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
|
|
1862
|
+
this.fail(el.name, `"${name}" shadows the parameter "${name}"; use another name`);
|
|
1863
|
+
return name;
|
|
1864
|
+
});
|
|
1865
|
+
const [program, data] = names;
|
|
1866
|
+
const key = program ? `l_${program}_${this.temp++}` : this.tmp("rdfrom");
|
|
1867
|
+
const buf = this.tmp("rdbuf");
|
|
1868
|
+
const len = this.tmp("rdlen");
|
|
1869
|
+
this.line(`SolPubkey ${key} = {0}; uint8_t ${buf}[1024];`);
|
|
1870
|
+
this.line(`uint64_t ${len} = sol_get_return_data(${buf}, sizeof(${buf}), &${key});`);
|
|
1871
|
+
if (program)
|
|
1872
|
+
this.scopes.at(-1).set(program, { c: key, type: PUBKEY, mutable: false });
|
|
1873
|
+
if (data) {
|
|
1874
|
+
const c = `l_${data}_${this.temp++}`;
|
|
1875
|
+
this.line(`TS_VecArg ${c} = {${buf}, (uint32_t)(${len} < sizeof(${buf}) ? ${len} : sizeof(${buf}))};`);
|
|
1876
|
+
this.scopes.at(-1).set(data, { c, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, mutable: false });
|
|
1877
|
+
}
|
|
1878
|
+
else
|
|
1879
|
+
this.line(`(void)${len};`);
|
|
1880
|
+
}
|
|
1833
1881
|
/**
|
|
1834
1882
|
* `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
|
|
1835
|
-
* Pubkey::find_program_address(…)`, both from one search (the only array destructuring
|
|
1883
|
+
* Pubkey::find_program_address(…)`, both from one search (with getReturnData, the only array destructuring).
|
|
1836
1884
|
*/
|
|
1837
1885
|
addressAndBump(d, pattern, mutable) {
|
|
1838
1886
|
const init = d.initializer;
|
|
1839
1887
|
const call = init && ts.isCallExpression(init) && this.exportName(init.expression) === "findProgramAddressWithBump" ? init : undefined;
|
|
1840
1888
|
if (!call)
|
|
1841
|
-
this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1889
|
+
this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program) and const [program, data] = getReturnData()");
|
|
1842
1890
|
if (mutable)
|
|
1843
1891
|
this.fail(d, "bind them with const: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1844
1892
|
if (d.type)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
2
|
import { heapVecOf, resolveScalarType, structNameOf, typesolName } from "../analyze.js";
|
|
3
3
|
import { INT_INFO, isScalar, isWritable, sameType, scalarSize, typeName } from "../model.js";
|
|
4
|
-
import { U64, BOOL, PUBKEY, STRING, F64_TO_INT, optC, fieldC, fixedVecC, storageDecl, vecCount, vecPlace, emptySizeC } from "./shared.js";
|
|
4
|
+
import { U64, BOOL, PUBKEY, STRING, F64_TO_INT, optC, fieldC, fixedVecC, storageDecl, vecCount, vecPlace, emptySizeC, throughPointer, copyMacro, } from "./shared.js";
|
|
5
5
|
import { AliasEmitter } from "./alias.js";
|
|
6
6
|
/**
|
|
7
7
|
* Places in account data and locals: references, reads and writes, Vec/array indexing, aliasing rules and
|
|
@@ -209,14 +209,14 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
209
209
|
this.checkLocalListSize(type, init);
|
|
210
210
|
const one = this.tmp("fill");
|
|
211
211
|
this.line(`${storageDecl(elem, one)};`);
|
|
212
|
-
this.line(`
|
|
212
|
+
this.line(`TS_ZERO_LOCAL(&${one}, sizeof(${one}));`);
|
|
213
213
|
const vt = this.storageValueType(elem);
|
|
214
214
|
if (vt)
|
|
215
215
|
this.line(this.writeStorage({ lv: one, type: elem, writable: true }, this.expect(this.expr(init.arguments[0], vt), vt, init.arguments[0]).c) + ";");
|
|
216
216
|
else
|
|
217
217
|
this.writeAggregate({ lv: one, type: elem, writable: true }, init.arguments[0], true);
|
|
218
218
|
this.line(`${storageDecl(type, c)};`);
|
|
219
|
-
this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++)
|
|
219
|
+
this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++) TS_MEMCPY(&${c}[${i}], &${one}, sizeof(${one}));`);
|
|
220
220
|
return type;
|
|
221
221
|
}
|
|
222
222
|
/** Resolve an expression to a storage location, if it names one. */
|
|
@@ -646,13 +646,13 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
646
646
|
if (target.type.kind === "option" && target.type.inner.kind === "struct") {
|
|
647
647
|
if (valueNode.kind === ts.SyntaxKind.NullKeyword) {
|
|
648
648
|
this.line(`${target.lv}.some = 0;`);
|
|
649
|
-
this.line(
|
|
649
|
+
this.line(`${throughPointer(target.lv) ? "TS_ZERO" : "TS_ZERO_LOCAL"}(&${target.lv}.v, sizeof(${target.lv}.v));`);
|
|
650
650
|
return;
|
|
651
651
|
}
|
|
652
652
|
// Another Option<same struct>: copy it whole (tag and value).
|
|
653
653
|
const whole = ts.isObjectLiteralExpression(valueNode) ? undefined : this.ref(valueNode);
|
|
654
654
|
if (whole && sameType(whole.type, target.type)) {
|
|
655
|
-
this.line(
|
|
655
|
+
this.line(`${copyMacro(target.lv, whole.lv)}(&${target.lv}, &${whole.lv}, sizeof(${target.lv}));`);
|
|
656
656
|
return;
|
|
657
657
|
}
|
|
658
658
|
this.writeAggregate({ ...target, lv: `${target.lv}.v`, type: target.type.inner }, valueNode);
|
|
@@ -665,10 +665,10 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
665
665
|
// Build the new value in a temporary: its fields may read the old value of the target.
|
|
666
666
|
const tmp = this.tmp("de");
|
|
667
667
|
this.line(`TSE_${e.name} ${tmp};`);
|
|
668
|
-
this.line(`
|
|
668
|
+
this.line(`TS_ZERO_LOCAL(&${tmp}, sizeof(${tmp}));`);
|
|
669
669
|
this.line(`${tmp}.tag = ${vi};`);
|
|
670
670
|
lit.writeFields(`${tmp}.v.${variant.name}`);
|
|
671
|
-
this.line(`
|
|
671
|
+
this.line(`TS_MEMCPY(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
|
|
672
672
|
return;
|
|
673
673
|
}
|
|
674
674
|
if (target.type.kind === "vec" && target.type.cap !== undefined && ts.isCallExpression(valueNode) && this.exportName(valueNode.expression) === "fixedVec") {
|
|
@@ -752,7 +752,7 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
752
752
|
this.writeAggregate(sub, e, true);
|
|
753
753
|
}
|
|
754
754
|
if (tmp)
|
|
755
|
-
this.line(`
|
|
755
|
+
this.line(`TS_MEMCPY(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
|
|
756
756
|
return;
|
|
757
757
|
}
|
|
758
758
|
if (ts.isConditionalExpression(valueNode)) {
|
|
@@ -811,8 +811,10 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
811
811
|
src = this.someValue(src);
|
|
812
812
|
if (!src || !sameType(src.type, target.type))
|
|
813
813
|
this.fail(valueNode, `expected a ${typeName(target.type)}: an object literal, another ${typeName(target.type)}${target.type.kind === "vec" && target.type.cap !== undefined ? " or a Vec of the same elements" : ""}`);
|
|
814
|
-
// Same-typed places are either distinct
|
|
815
|
-
|
|
814
|
+
// Same-typed places are either distinct, identical (`a.p = a.p`) or, through native views of one account at
|
|
815
|
+
// different offsets, overlapping: TS_COPY leaves the source's old bytes either way (below the threshold every byte
|
|
816
|
+
// is loaded before any is stored, from it the memmove syscall copies them as copy_within does).
|
|
817
|
+
this.line(`${copyMacro(target.lv, src.lv)}(&${target.lv}, &${src.lv}, sizeof(${target.lv}));`);
|
|
816
818
|
}
|
|
817
819
|
/** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
|
|
818
820
|
isListLiteral(node) {
|
|
@@ -308,7 +308,7 @@ export class ViewEmitter extends CallEmitter {
|
|
|
308
308
|
const o = this.tmp("rbopt");
|
|
309
309
|
this.line(`${optC(scalar)} ${o};`);
|
|
310
310
|
this.line(`${o}.some = ${idx} != 0;`);
|
|
311
|
-
this.line(`if (${idx})
|
|
311
|
+
this.line(`if (${idx}) TS_MEMCPY(&${o}.v, ${at}, ${inst.valueSize}); else TS_ZERO_LOCAL(&${o}.v, ${inst.valueSize});`);
|
|
312
312
|
return { c: o, type: { kind: "option", inner: scalar } };
|
|
313
313
|
}
|
|
314
314
|
treeCall(node) {
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface Generated {
|
|
|
18
18
|
c: string;
|
|
19
19
|
/** The TypeSOL source files of the program (entry and relative imports). */
|
|
20
20
|
files: string[];
|
|
21
|
+
/** Each source file's text as the compiler read it. */
|
|
22
|
+
texts: Map<string, string>;
|
|
21
23
|
}
|
|
22
24
|
/** Typecheck, enforce the TypeSOL subset, and generate C. Throws CompileError with every diagnostic. */
|
|
23
25
|
export declare function generate(entry: string, opts?: EmitOptions): Generated;
|
|
@@ -99,10 +101,22 @@ export interface BuildResult extends Generated {
|
|
|
99
101
|
idlPath: string;
|
|
100
102
|
idl: ReturnType<typeof buildIdl>;
|
|
101
103
|
}
|
|
102
|
-
/**
|
|
104
|
+
/** A step of `build`, for `onStep`: the C generated (the sources read), the C compiled and linked. */
|
|
105
|
+
export type BuildStep = "generated" | "compiled";
|
|
106
|
+
/**
|
|
107
|
+
* Full build: `<outDir>/<name>.c`, `<name>.so`, `<name>.json` (Anchor IDL) and `<name>.build.json`, the manifest.
|
|
108
|
+
*
|
|
109
|
+
* The manifest binds the binary to the exact inputs that made it: each source's sha256 is that of the bytes the
|
|
110
|
+
* compiler parsed (read once, checked against the text the TypeScript program holds), the runtime files are hashed
|
|
111
|
+
* before clang reads them, and every input is hashed again once the binary is linked. An input that changed in between
|
|
112
|
+
* (an editor saving a file mid-build) fails the build with no manifest: a previous build's manifest is removed before
|
|
113
|
+
* anything is written, so a reused build (buildForTest) never pairs a binary with sources that did not make it.
|
|
114
|
+
* `onStep` is called after each step (tests use it to change a file at that point).
|
|
115
|
+
*/
|
|
103
116
|
export declare function build(entry: string, outDir: string, programAddress: string, opts?: {
|
|
104
117
|
sbpf?: Sbpf;
|
|
105
118
|
profile?: boolean;
|
|
119
|
+
onStep?: (step: BuildStep) => void;
|
|
106
120
|
}): BuildResult;
|
|
107
121
|
/** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
|
|
108
122
|
export declare const COMPILER_VERSION: string;
|
package/dist/compiler/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import ts from "typescript";
|
|
4
|
-
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { analyze, LIB_PATH } from "./analyze.js";
|
|
7
7
|
import { hintForTypeScript, messageForTypeScript } from "./hints.js";
|
|
@@ -30,29 +30,58 @@ export function generate(entry, opts = {}) {
|
|
|
30
30
|
analysis.reporter.throwIfAny();
|
|
31
31
|
const c = emitProgram(analysis, opts);
|
|
32
32
|
analysis.reporter.throwIfAny();
|
|
33
|
-
return { model: analysis.model, c, files: analysis.files };
|
|
33
|
+
return { model: analysis.model, c, files: analysis.files, texts: analysis.texts };
|
|
34
34
|
}
|
|
35
35
|
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Full build: `<outDir>/<name>.c`, `<name>.so`, `<name>.json` (Anchor IDL) and `<name>.build.json`, the manifest.
|
|
38
|
+
*
|
|
39
|
+
* The manifest binds the binary to the exact inputs that made it: each source's sha256 is that of the bytes the
|
|
40
|
+
* compiler parsed (read once, checked against the text the TypeScript program holds), the runtime files are hashed
|
|
41
|
+
* before clang reads them, and every input is hashed again once the binary is linked. An input that changed in between
|
|
42
|
+
* (an editor saving a file mid-build) fails the build with no manifest: a previous build's manifest is removed before
|
|
43
|
+
* anything is written, so a reused build (buildForTest) never pairs a binary with sources that did not make it.
|
|
44
|
+
* `onStep` is called after each step (tests use it to change a file at that point).
|
|
45
|
+
*/
|
|
37
46
|
export function build(entry, outDir, programAddress, opts = {}) {
|
|
47
|
+
const runtime = {
|
|
48
|
+
"<runtime>/typesol_rt.h": path.join(RUNTIME_DIR, "typesol_rt.h"),
|
|
49
|
+
"<runtime>/typesol_builtins.c": BUILTINS_SOURCE,
|
|
50
|
+
};
|
|
51
|
+
const runtimeHashes = Object.fromEntries(Object.entries(runtime).map(([k, f]) => [k, sha256(readFileSync(f))]));
|
|
38
52
|
const gen = generate(entry, { profile: opts.profile });
|
|
53
|
+
opts.onStep?.("generated");
|
|
54
|
+
const root = path.dirname(path.resolve(entry));
|
|
55
|
+
const changed = (rel) => new Error(`${rel} changed while it was being built, so the binary may not be what it holds now: no manifest was written; build again`);
|
|
56
|
+
const sources = {};
|
|
57
|
+
for (const f of gen.files) {
|
|
58
|
+
const bytes = readFileSync(f);
|
|
59
|
+
if (decodeSource(bytes) !== gen.texts.get(f))
|
|
60
|
+
throw changed(path.relative(root, f));
|
|
61
|
+
sources[path.relative(root, f)] = sha256(bytes);
|
|
62
|
+
}
|
|
39
63
|
mkdirSync(outDir, { recursive: true });
|
|
40
64
|
const base = path.join(outDir, gen.model.name);
|
|
41
65
|
const cPath = `${base}.c`;
|
|
42
66
|
const soPath = `${base}.so`;
|
|
43
67
|
const idlPath = `${base}.json`;
|
|
68
|
+
const manifestPath = `${base}.build.json`;
|
|
69
|
+
rmSync(manifestPath, { force: true });
|
|
44
70
|
writeFileSync(cPath, gen.c);
|
|
45
71
|
// Before clang runs: an untested toolchain is a warning (once), or an error in strict mode.
|
|
46
72
|
const toolchain = checkToolchain();
|
|
47
73
|
buildSharedObject(cPath, soPath, opts.sbpf);
|
|
74
|
+
opts.onStep?.("compiled");
|
|
48
75
|
const idl = buildIdl(gen.model, programAddress);
|
|
49
76
|
writeFileSync(idlPath, JSON.stringify(idl, null, 2) + "\n");
|
|
50
|
-
const root = path.dirname(path.resolve(entry));
|
|
51
|
-
const sources = {};
|
|
52
77
|
for (const f of gen.files)
|
|
53
|
-
sources[path.relative(root, f)]
|
|
54
|
-
|
|
55
|
-
|
|
78
|
+
if (sha256(readFileSync(f)) !== sources[path.relative(root, f)])
|
|
79
|
+
throw changed(path.relative(root, f));
|
|
80
|
+
for (const [k, f] of Object.entries(runtime)) {
|
|
81
|
+
if (sha256(readFileSync(f)) !== runtimeHashes[k])
|
|
82
|
+
throw changed(f);
|
|
83
|
+
sources[k] = runtimeHashes[k];
|
|
84
|
+
}
|
|
56
85
|
const manifest = {
|
|
57
86
|
program: gen.model.name,
|
|
58
87
|
compiler: COMPILER_VERSION,
|
|
@@ -65,10 +94,22 @@ export function build(entry, outDir, programAddress, opts = {}) {
|
|
|
65
94
|
sources,
|
|
66
95
|
binary: sha256(readFileSync(soPath)),
|
|
67
96
|
};
|
|
68
|
-
const manifestPath = `${base}.build.json`;
|
|
69
97
|
writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
|
|
70
98
|
return { ...gen, cPath, soPath, idlPath, idl, manifest, manifestPath };
|
|
71
99
|
}
|
|
100
|
+
/** A source file's bytes as TypeScript reads them (ts.sys.readFile): UTF-8, or UTF-16 with its byte-order mark, no BOM. */
|
|
101
|
+
function decodeSource(b) {
|
|
102
|
+
if (b.length >= 2 && b[0] === 0xfe && b[1] === 0xff) {
|
|
103
|
+
const swapped = Buffer.from(b.subarray(2, 2 + ((b.length - 2) & ~1)));
|
|
104
|
+
swapped.swap16();
|
|
105
|
+
return swapped.toString("utf16le");
|
|
106
|
+
}
|
|
107
|
+
if (b.length >= 2 && b[0] === 0xff && b[1] === 0xfe)
|
|
108
|
+
return b.toString("utf16le", 2);
|
|
109
|
+
if (b.length >= 3 && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf)
|
|
110
|
+
return b.toString("utf8", 3);
|
|
111
|
+
return b.toString("utf8");
|
|
112
|
+
}
|
|
72
113
|
/** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
|
|
73
114
|
export const COMPILER_VERSION = createRequire(import.meta.url)("../../package.json").version;
|
|
74
115
|
/** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
|
package/dist/keys.d.ts
CHANGED
|
@@ -3,8 +3,19 @@ export declare function base58(bytes: Uint8Array): string;
|
|
|
3
3
|
export declare function decodeAddress(text: string): Uint8Array | undefined;
|
|
4
4
|
/** The 64 bytes of a Solana CLI keypair file (a JSON array), with errors that name the file. */
|
|
5
5
|
export declare function readKeypair(file: string): Uint8Array;
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* Read a Solana CLI keypair file, or create one, and return its base58 address. Creation is exclusive and atomic: the
|
|
8
|
+
* key is written whole to a temporary file next to it, then linked into place, which fails if the file appeared in the
|
|
9
|
+
* meantime. Two callers creating the same file at once (two first builds) therefore end with one key: the loser reads
|
|
10
|
+
* the winner's file, and no reader ever sees a partly written one.
|
|
11
|
+
*/
|
|
7
12
|
export declare function loadOrCreateKeypair(file: string): {
|
|
8
13
|
address: string;
|
|
9
14
|
created: boolean;
|
|
10
15
|
};
|
|
16
|
+
/**
|
|
17
|
+
* Create `file` with `text` (mode 0600) unless it exists: false if another writer created it first. The text goes to a
|
|
18
|
+
* temporary file in the same directory, which is then hard-linked to `file` (link fails if `file` exists), so `file`
|
|
19
|
+
* appears complete or not at all. On a file system without hard links, an exclusive create (`wx`) instead.
|
|
20
|
+
*/
|
|
21
|
+
export declare function createExclusive(file: string, text: string): boolean;
|
package/dist/keys.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { generateKeyPairSync } from "node:crypto";
|
|
2
|
-
import { existsSync, readFileSync,
|
|
2
|
+
import { closeSync, existsSync, linkSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
|
|
3
3
|
const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
4
4
|
export function base58(bytes) {
|
|
5
5
|
let n = 0n;
|
|
@@ -48,16 +48,66 @@ export function readKeypair(file) {
|
|
|
48
48
|
throw new Error(`${file} is not a 64-byte Solana keypair`);
|
|
49
49
|
return Uint8Array.from(raw);
|
|
50
50
|
}
|
|
51
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* Read a Solana CLI keypair file, or create one, and return its base58 address. Creation is exclusive and atomic: the
|
|
53
|
+
* key is written whole to a temporary file next to it, then linked into place, which fails if the file appeared in the
|
|
54
|
+
* meantime. Two callers creating the same file at once (two first builds) therefore end with one key: the loser reads
|
|
55
|
+
* the winner's file, and no reader ever sees a partly written one.
|
|
56
|
+
*/
|
|
52
57
|
export function loadOrCreateKeypair(file) {
|
|
53
|
-
if (existsSync(file))
|
|
54
|
-
|
|
55
|
-
return { address: base58(bytes.subarray(32)), created: false };
|
|
56
|
-
}
|
|
58
|
+
if (existsSync(file))
|
|
59
|
+
return { address: base58(readKeypair(file).subarray(32)), created: false };
|
|
57
60
|
const { privateKey } = generateKeyPairSync("ed25519");
|
|
58
61
|
const jwk = privateKey.export({ format: "jwk" });
|
|
59
62
|
const secret = Buffer.from(jwk.d, "base64url");
|
|
60
63
|
const pub = Buffer.from(jwk.x, "base64url");
|
|
61
|
-
|
|
64
|
+
if (!createExclusive(file, JSON.stringify([...secret, ...pub]) + "\n"))
|
|
65
|
+
return { address: base58(readKeypair(file).subarray(32)), created: false };
|
|
62
66
|
return { address: base58(pub), created: true };
|
|
63
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* Create `file` with `text` (mode 0600) unless it exists: false if another writer created it first. The text goes to a
|
|
70
|
+
* temporary file in the same directory, which is then hard-linked to `file` (link fails if `file` exists), so `file`
|
|
71
|
+
* appears complete or not at all. On a file system without hard links, an exclusive create (`wx`) instead.
|
|
72
|
+
*/
|
|
73
|
+
export function createExclusive(file, text) {
|
|
74
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
75
|
+
writeNew(tmp, text);
|
|
76
|
+
try {
|
|
77
|
+
linkSync(tmp, file);
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
const code = e.code;
|
|
82
|
+
if (code === "EEXIST")
|
|
83
|
+
return false;
|
|
84
|
+
if (code !== "EPERM" && code !== "ENOTSUP" && code !== "ENOSYS" && code !== "EXDEV")
|
|
85
|
+
throw e;
|
|
86
|
+
try {
|
|
87
|
+
writeNew(file, text);
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
catch (e2) {
|
|
91
|
+
if (e2.code === "EEXIST")
|
|
92
|
+
return false;
|
|
93
|
+
throw e2;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
try {
|
|
98
|
+
unlinkSync(tmp);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// Already gone.
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function writeNew(file, text) {
|
|
106
|
+
const fd = openSync(file, "wx", 0o600);
|
|
107
|
+
try {
|
|
108
|
+
writeSync(fd, text);
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
closeSync(fd);
|
|
112
|
+
}
|
|
113
|
+
}
|
package/dist/workspace.d.ts
CHANGED
|
@@ -40,6 +40,14 @@ export declare function programAddress(ws: Workspace, name: string, opts?: {
|
|
|
40
40
|
created: boolean;
|
|
41
41
|
keyless?: boolean;
|
|
42
42
|
};
|
|
43
|
+
/**
|
|
44
|
+
* Change typesol.json: read it, `edit` it and write it back, one process at a time (`<file>.lock`, as a build's
|
|
45
|
+
* lock), the new text written to a temporary file and renamed over it, so that concurrent first builds each keep
|
|
46
|
+
* their address and no reader sees a partly written file.
|
|
47
|
+
*/
|
|
48
|
+
export declare function updateConfig(ws: Workspace, edit: (raw: {
|
|
49
|
+
programs: Record<string, string | ProgramEntry>;
|
|
50
|
+
}) => void): void;
|
|
43
51
|
/** Build every program (or the ones named). */
|
|
44
52
|
export declare function buildWorkspace(ws: Workspace, names?: string[], opts?: {
|
|
45
53
|
sbpf?: Sbpf;
|
package/dist/workspace.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import { agentsMd, CLAUDE_MD, cursorRule, MCP_JSON } from "./ai.js";
|
|
15
15
|
import { createHash } from "node:crypto";
|
|
16
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync,
|
|
16
|
+
import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
|
|
17
17
|
import os from "node:os";
|
|
18
18
|
import path from "node:path";
|
|
19
19
|
import ts from "typescript";
|
|
@@ -97,13 +97,45 @@ export function programAddress(ws, name, opts = {}) {
|
|
|
97
97
|
if (recorded && recorded !== address)
|
|
98
98
|
throw new Error(`${name}: ${path.relative(ws.root, paths.keypair)} is ${address}, but ${CONFIG} records ${recorded}. Restore the right keypair.`);
|
|
99
99
|
if (!recorded) {
|
|
100
|
-
|
|
101
|
-
raw
|
|
102
|
-
|
|
100
|
+
// Another process (a first build of another program, under its own lock) may be recording its address now.
|
|
101
|
+
updateConfig(ws, (raw) => {
|
|
102
|
+
const entry = raw.programs[name];
|
|
103
|
+
const current = typeof entry === "object" ? entry : { path: entry ?? ws.programs[name].path };
|
|
104
|
+
if (current.address && current.address !== address)
|
|
105
|
+
throw new Error(`${name}: ${CONFIG} now records ${current.address}, but ${path.relative(ws.root, paths.keypair)} is ${address}. Restore the right keypair.`);
|
|
106
|
+
raw.programs[name] = { ...current, address };
|
|
107
|
+
});
|
|
103
108
|
ws.programs[name].address = address;
|
|
104
109
|
}
|
|
105
110
|
return { address, created };
|
|
106
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* Change typesol.json: read it, `edit` it and write it back, one process at a time (`<file>.lock`, as a build's
|
|
114
|
+
* lock), the new text written to a temporary file and renamed over it, so that concurrent first builds each keep
|
|
115
|
+
* their address and no reader sees a partly written file.
|
|
116
|
+
*/
|
|
117
|
+
export function updateConfig(ws, edit) {
|
|
118
|
+
withLockFile(`${ws.file}.lock`, () => {
|
|
119
|
+
const raw = JSON.parse(readFileSync(ws.file, "utf8"));
|
|
120
|
+
edit(raw);
|
|
121
|
+
// A linked typesol.json stays a link: the file it points to is the one replaced.
|
|
122
|
+
const target = realpathSync(ws.file);
|
|
123
|
+
const tmp = `${target}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
124
|
+
writeNewFile(tmp, JSON.stringify(raw, null, 2) + "\n");
|
|
125
|
+
try {
|
|
126
|
+
renameSync(tmp, target);
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
try {
|
|
130
|
+
unlinkSync(tmp);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Already gone.
|
|
134
|
+
}
|
|
135
|
+
throw e;
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
107
139
|
/** Build every program (or the ones named). */
|
|
108
140
|
export function buildWorkspace(ws, names = Object.keys(ws.programs), opts = {}) {
|
|
109
141
|
return names.map((name) => {
|
|
@@ -217,7 +249,10 @@ const LOCK_POLL_MS = 100;
|
|
|
217
249
|
*/
|
|
218
250
|
export function withBuildLock(dir, fn) {
|
|
219
251
|
mkdirSync(dir, { recursive: true });
|
|
220
|
-
|
|
252
|
+
return withLockFile(path.join(dir, ".typesol-build.lock"), fn);
|
|
253
|
+
}
|
|
254
|
+
/** Run `fn` holding `lock` (see withBuildLock): created exclusively, taken over when its holder is gone or it is stale. */
|
|
255
|
+
function withLockFile(lock, fn) {
|
|
221
256
|
const me = `${os.hostname()} ${process.pid} ${Date.now()}`;
|
|
222
257
|
const deadline = Date.now() + LOCK_STALE_MS + 60_000;
|
|
223
258
|
for (;;) {
|
|
@@ -401,11 +436,52 @@ export function scaffold(dir, name, template = "counter", opts = {}) {
|
|
|
401
436
|
const agent = existing.some((f) => AGENT_FILES.includes(f));
|
|
402
437
|
if (existing.length)
|
|
403
438
|
throw new Error(`refusing to overwrite: ${existing.join(", ")}${agent ? " (--no-agent-files leaves out the files for AI coding agents)" : ""}`);
|
|
439
|
+
writeProjectFiles(dir, files);
|
|
440
|
+
return Object.keys(files);
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Write new files under `root` (paths relative to it). Refuses, before writing anything, a path through a symbolic link
|
|
444
|
+
* below `root` (a linked directory or a link where a file goes, which would put the file outside the project), then
|
|
445
|
+
* creates each directory and each file exclusively, so an existing file (or one created meanwhile) is never overwritten.
|
|
446
|
+
* `root` itself may be a link: the project is where it points.
|
|
447
|
+
*/
|
|
448
|
+
function writeProjectFiles(root, files) {
|
|
449
|
+
for (const file of Object.keys(files)) {
|
|
450
|
+
const parts = file.split("/");
|
|
451
|
+
for (let i = 1; i <= parts.length; i++) {
|
|
452
|
+
const rel = parts.slice(0, i).join("/");
|
|
453
|
+
let link = false;
|
|
454
|
+
try {
|
|
455
|
+
link = lstatSync(path.join(root, rel)).isSymbolicLink();
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
break; // Does not exist: neither does anything below it.
|
|
459
|
+
}
|
|
460
|
+
if (link)
|
|
461
|
+
throw new Error(`refusing to write ${file}: ${rel} is a symbolic link (it may point outside the project); replace it with a directory or file of the project`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
404
464
|
for (const [file, text] of Object.entries(files)) {
|
|
405
|
-
mkdirSync(path.dirname(path.join(
|
|
406
|
-
|
|
465
|
+
mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
|
|
466
|
+
try {
|
|
467
|
+
writeNewFile(path.join(root, file), text);
|
|
468
|
+
}
|
|
469
|
+
catch (e) {
|
|
470
|
+
if (e.code === "EEXIST")
|
|
471
|
+
throw new Error(`refusing to overwrite: ${file}`);
|
|
472
|
+
throw e;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
/** Create `file` with `text`; fails with EEXIST if anything (a file, a link, even a dangling one) is already there. */
|
|
477
|
+
function writeNewFile(file, text) {
|
|
478
|
+
const fd = openSync(file, "wx");
|
|
479
|
+
try {
|
|
480
|
+
writeSync(fd, text);
|
|
481
|
+
}
|
|
482
|
+
finally {
|
|
483
|
+
closeSync(fd);
|
|
407
484
|
}
|
|
408
|
-
return Object.keys(files);
|
|
409
485
|
}
|
|
410
486
|
/**
|
|
411
487
|
* Add a program to an existing project: programs/<name>.ts and tests/<name>.test.ts from a template, and its entry in
|
|
@@ -421,13 +497,12 @@ export function addProgram(ws, name, template = "counter") {
|
|
|
421
497
|
const existing = Object.keys(files).filter((f) => existsSync(path.join(ws.root, f)));
|
|
422
498
|
if (existing.length)
|
|
423
499
|
throw new Error(`refusing to overwrite: ${existing.join(", ")}`);
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
writeFileSync(ws.file, JSON.stringify(raw, null, 2) + "\n");
|
|
500
|
+
writeProjectFiles(ws.root, files);
|
|
501
|
+
updateConfig(ws, (raw) => {
|
|
502
|
+
if (raw.programs[name])
|
|
503
|
+
throw new Error(`${CONFIG} already has a program "${name}"`);
|
|
504
|
+
raw.programs[name] = { path: `programs/${name}.ts` };
|
|
505
|
+
});
|
|
431
506
|
ws.programs[name] = { path: `programs/${name}.ts` };
|
|
432
507
|
const pkgFile = path.join(ws.root, "package.json");
|
|
433
508
|
const pkg = existsSync(pkgFile)
|