@zktx.io/sui-move-builder 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -34,7 +34,11 @@ module hello_world::hello_world {
34
34
  };
35
35
 
36
36
  // 3) Compile
37
- const result = await buildMovePackage({ files, dependencies: {} });
37
+ const result = await buildMovePackage({
38
+ files,
39
+ dependencies: {},
40
+ autoSystemDeps: true, // Sui CLI-like defaults for std/Sui packages
41
+ });
38
42
 
39
43
  if (result.success) {
40
44
  console.log(result.digest);
@@ -67,8 +71,12 @@ const depsJson =
67
71
  const result = await buildMovePackage({
68
72
  files: filesJson,
69
73
  dependencies: depsJson,
74
+ autoSystemDeps: true,
70
75
  });
71
76
 
77
+ // If autoSystemDeps is enabled and std/Sui packages are missing,
78
+ // the builder fetches them from GitHub using the Sui framework snapshot.
79
+
72
80
  // Enable ANSI-colored diagnostics (CLI-like output)
73
81
  const resultWithColor = await buildMovePackage({
74
82
  files: filesJson,
@@ -89,3 +97,7 @@ const resultWithColor = await buildMovePackage({
89
97
  npm run serve:test # serves ./test via python -m http.server
90
98
  # open http://localhost:8000/test/index.html
91
99
  ```
100
+
101
+ ## Source
102
+
103
+ > **Upstream source (Sui repository):** https://github.com/MystenLabs/sui
package/dist/index.cjs CHANGED
@@ -1,547 +1,15 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Fetcher: () => Fetcher,
34
- GitHubFetcher: () => GitHubFetcher,
35
- Resolver: () => Resolver,
36
- buildMovePackage: () => buildMovePackage,
37
- compileRaw: () => compileRaw,
38
- getSuiMoveVersion: () => getSuiMoveVersion,
39
- getSuiVersion: () => getSuiVersion,
40
- getWasmBindings: () => getWasmBindings,
41
- initMoveCompiler: () => initMoveCompiler,
42
- parseToml: () => parseToml,
43
- resolve: () => resolve
44
- });
45
- module.exports = __toCommonJS(index_exports);
46
-
47
- // src/tomlParser.ts
48
- function stripInlineComment(line) {
49
- let inQuote = false;
50
- let quoteChar = "";
51
- for (let i = 0; i < line.length; i++) {
52
- const ch = line[i];
53
- if ((ch === '"' || ch === "'") && (!inQuote || ch === quoteChar)) {
54
- inQuote = !inQuote;
55
- quoteChar = ch;
56
- }
57
- if (!inQuote && ch === "#") {
58
- return line.slice(0, i);
59
- }
60
- }
61
- return line;
62
- }
63
- function parseScalar(value) {
64
- const trimmed = value.trim();
65
- if (!trimmed) return "";
66
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
67
- return trimmed.slice(1, -1);
68
- }
69
- if (trimmed === "true") return true;
70
- if (trimmed === "false") return false;
71
- const num = Number(trimmed);
72
- if (!Number.isNaN(num)) return num;
73
- return trimmed;
74
- }
75
- function parseInlineTable(value) {
76
- const result = {};
77
- const inner = value.trim().replace(/^\{/, "").replace(/\}$/, "");
78
- let current = "";
79
- let inQuote = false;
80
- let quoteChar = "";
81
- const parts = [];
82
- for (let i = 0; i < inner.length; i++) {
83
- const ch = inner[i];
84
- if ((ch === '"' || ch === "'") && (!inQuote || ch === quoteChar)) {
85
- inQuote = !inQuote;
86
- quoteChar = ch;
87
- }
88
- if (!inQuote && ch === ",") {
89
- parts.push(current);
90
- current = "";
91
- continue;
92
- }
93
- current += ch;
94
- }
95
- if (current.trim()) {
96
- parts.push(current);
97
- }
98
- for (const part of parts) {
99
- const eq = part.indexOf("=");
100
- if (eq === -1) continue;
101
- const key = part.slice(0, eq).trim();
102
- const val = part.slice(eq + 1).trim();
103
- result[key] = parseScalar(val);
104
- }
105
- return result;
106
- }
107
- function parseToml(content) {
108
- const result = {
109
- package: {},
110
- dependencies: {},
111
- addresses: {}
112
- };
113
- let section = null;
114
- const lines = content.split(/\r?\n/);
115
- for (const rawLine of lines) {
116
- const line = stripInlineComment(rawLine).trim();
117
- if (!line) continue;
118
- const sectionMatch = line.match(/^\[([^\]]+)\]$/);
119
- if (sectionMatch) {
120
- section = sectionMatch[1].trim();
121
- continue;
122
- }
123
- const eq = line.indexOf("=");
124
- if (eq === -1 || !section) continue;
125
- const key = line.slice(0, eq).trim();
126
- const value = line.slice(eq + 1).trim();
127
- if (section === "package") {
128
- result.package[key.replace(/-/g, "_")] = parseScalar(value);
129
- } else if (section === "dependencies") {
130
- if (value.startsWith("{")) {
131
- result.dependencies[key] = parseInlineTable(value);
132
- } else {
133
- result.dependencies[key] = parseScalar(value);
134
- }
135
- } else if (section === "addresses") {
136
- result.addresses[key] = parseScalar(value);
137
- }
138
- }
139
- return result;
140
- }
141
-
142
- // src/resolver.ts
143
- var Resolver = class {
144
- constructor(fetcher) {
145
- this.fetcher = fetcher;
146
- this.globalAddresses = {};
147
- this.visited = /* @__PURE__ */ new Set();
148
- this.dependencyFiles = {};
149
- this.systemDepsLoaded = /* @__PURE__ */ new Set();
150
- }
151
- async resolve(rootMoveToml, rootFiles) {
152
- const parsedToml = parseToml(rootMoveToml);
153
- if (parsedToml.addresses) {
154
- this.mergeAddresses(parsedToml.addresses);
155
- }
156
- if (parsedToml.dependencies) {
157
- await this.resolveDeps(parsedToml.dependencies);
158
- await this.injectSystemDepsFromRoot(parsedToml.dependencies);
159
- }
160
- const finalMoveToml = this.reconstructMoveToml(parsedToml, this.globalAddresses);
161
- const finalFiles = { ...rootFiles, "Move.toml": finalMoveToml };
162
- return {
163
- files: JSON.stringify(finalFiles),
164
- dependencies: JSON.stringify(this.dependencyFiles)
165
- };
166
- }
167
- mergeAddresses(addresses) {
168
- for (const [name, val] of Object.entries(addresses)) {
169
- this.globalAddresses[name] = this.normalizeAddress(val);
170
- }
171
- }
172
- normalizeAddress(addr) {
173
- if (!addr) return addr;
174
- let clean = addr;
175
- if (clean.startsWith("0x")) clean = clean.slice(2);
176
- if (/^[0-9a-fA-F]+$/.test(clean)) {
177
- return "0x" + clean.padStart(64, "0");
178
- }
179
- return addr;
180
- }
181
- async resolveDeps(depsObj, parentContext = null) {
182
- for (const [name, depInfo] of Object.entries(depsObj)) {
183
- let gitUrl;
184
- let rev;
185
- let subdir;
186
- if (depInfo.git) {
187
- gitUrl = depInfo.git;
188
- rev = depInfo.rev;
189
- subdir = depInfo.subdir;
190
- } else if (depInfo.local) {
191
- if (!parentContext) continue;
192
- gitUrl = parentContext.git;
193
- rev = parentContext.rev;
194
- subdir = this.resolvePath(parentContext.subdir || "", depInfo.local);
195
- } else {
196
- continue;
197
- }
198
- const cacheKey = `${gitUrl}|${rev}|${subdir || ""}`;
199
- if (this.visited.has(cacheKey)) continue;
200
- this.visited.add(cacheKey);
201
- const files = await this.fetcher.fetch(gitUrl, rev, subdir);
202
- let pkgMoveToml = null;
203
- for (const [path, content] of Object.entries(files)) {
204
- if (path.endsWith("Move.toml")) {
205
- pkgMoveToml = content;
206
- break;
207
- }
208
- }
209
- if (pkgMoveToml) {
210
- const parsed = parseToml(pkgMoveToml);
211
- if (parsed.addresses) {
212
- this.mergeAddresses(parsed.addresses);
213
- }
214
- if (parsed.dependencies) {
215
- await this.resolveDeps(parsed.dependencies, { git: gitUrl, rev, subdir });
216
- }
217
- }
218
- for (const [path, content] of Object.entries(files)) {
219
- if (path.endsWith(".move") || path.endsWith("Move.toml")) {
220
- const targetPath = `dependencies/${name}/${path}`;
221
- this.dependencyFiles[targetPath] = content;
222
- }
223
- }
224
- }
225
- }
226
- resolvePath(base, relative) {
227
- const stack = base.split("/").filter((p) => p && p !== ".");
228
- const parts = relative.split("/").filter((p) => p && p !== ".");
229
- for (const part of parts) {
230
- if (part === "..") {
231
- stack.pop();
232
- } else {
233
- stack.push(part);
234
- }
235
- }
236
- return stack.join("/");
237
- }
238
- reconstructMoveToml(originalParsed, addresses) {
239
- let newToml = `[package]
240
- name = "${originalParsed.package.name}"
241
- version = "${originalParsed.package.version}"
242
- `;
243
- if (originalParsed.package.edition) {
244
- newToml += `edition = "${originalParsed.package.edition}"
245
- `;
246
- }
247
- newToml += `
1
+ "use strict";var j=Object.create;var v=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty;var A=(n,e)=>{for(var t in e)v(n,t,{get:e[t],enumerable:!0})},M=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of L(e))!B.call(n,i)&&i!==t&&v(n,i,{get:()=>e[i],enumerable:!(s=W(e,i))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?j(U(n)):{},M(e||!n||!n.__esModule?v(t,"default",{value:n,enumerable:!0}):t,n)),T=n=>M(v({},"__esModule",{value:!0}),n);var X={};A(X,{Fetcher:()=>g,GitHubFetcher:()=>p,Resolver:()=>y,buildMovePackage:()=>q,compileRaw:()=>Z,getSuiMoveVersion:()=>V,getSuiVersion:()=>K,getWasmBindings:()=>Q,initMoveCompiler:()=>J,parseToml:()=>h,resolve:()=>b});module.exports=T(X);var g=class{async fetch(e,t,s){throw new Error("Not implemented")}async fetchFile(e,t,s){throw new Error("Not implemented")}},p=class extends g{constructor(){super(),this.cache=new Map}async fetch(e,t,s){let{owner:i,repo:o}=this.parseGitUrl(e);if(!i||!o)throw new Error(`Invalid git URL: ${e}`);let c=`https://api.github.com/repos/${i}/${o}/git/trees/${t}?recursive=1`,l;try{let d=await fetch(c);if(!d.ok)throw d.status===403||d.status===429?new Error("GitHub API rate limit exceeded."):new Error(`Failed to fetch tree: ${d.statusText}`);l=await d.json()}catch{return{}}let r={},a=[];for(let d of l.tree){if(d.type!=="blob")continue;let u=d.path;if(s){if(!d.path.startsWith(s))continue;u=d.path.slice(s.length),u.startsWith("/")&&(u=u.slice(1))}if(!u.endsWith(".move")&&u!=="Move.toml")continue;let f=`https://raw.githubusercontent.com/${i}/${o}/${t}/${d.path}`,k=this.fetchContent(f).then(x=>{x&&(r[u]=x)});a.push(k)}return await Promise.all(a),r}async fetchFile(e,t,s){let{owner:i,repo:o}=this.parseGitUrl(e);if(!i||!o)throw new Error(`Invalid git URL: ${e}`);let c=`https://raw.githubusercontent.com/${i}/${o}/${t}/${s}`;return this.fetchContent(c)}async fetchContent(e){if(this.cache.has(e))return this.cache.get(e)??null;try{let t=await fetch(e);if(!t.ok)return null;let s=await t.text();return this.cache.set(e,s),s}catch{return null}}parseGitUrl(e){try{let s=new URL(e).pathname.split("/").filter(i=>i);if(s.length>=2){let i=s[1];return i.endsWith(".git")&&(i=i.slice(0,-4)),{owner:s[0],repo:i}}}catch{}return{owner:null,repo:null}}};function N(n){let e=!1,t="";for(let s=0;s<n.length;s++){let i=n[s];if((i==='"'||i==="'")&&(!e||i===t)&&(e=!e,t=i),!e&&i==="#")return n.slice(0,s)}return n}function w(n){let e=n.trim();if(!e)return"";if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e==="true")return!0;if(e==="false")return!1;let t=Number(e);return Number.isNaN(t)?e:t}function E(n){let e={},t=n.trim().replace(/^\{/,"").replace(/\}$/,""),s="",i=!1,o="",c=[];for(let l=0;l<t.length;l++){let r=t[l];if((r==='"'||r==="'")&&(!i||r===o)&&(i=!i,o=r),!i&&r===","){c.push(s),s="";continue}s+=r}s.trim()&&c.push(s);for(let l of c){let r=l.indexOf("=");if(r===-1)continue;let a=l.slice(0,r).trim(),d=l.slice(r+1).trim();e[a]=w(d)}return e}function h(n){let e={package:{},dependencies:{},addresses:{}},t=null,s=n.split(/\r?\n/);for(let i of s){let o=N(i).trim();if(!o)continue;let c=o.match(/^\[([^\]]+)\]$/);if(c){t=c[1].trim();continue}let l=o.indexOf("=");if(l===-1||!t)continue;let r=o.slice(0,l).trim(),a=o.slice(l+1).trim();t==="package"?e.package[r.replace(/-/g,"_")]=w(a):t==="dependencies"?a.startsWith("{")?e.dependencies[r]=E(a):e.dependencies[r]=w(a):t==="addresses"&&(e.addresses[r]=w(a))}return e}var y=class{constructor(e){this.fetcher=e,this.globalAddresses={},this.visited=new Set,this.dependencyFiles={},this.systemDepsLoaded=new Set}async resolve(e,t){let s=h(e);s.addresses&&this.mergeAddresses(s.addresses),s.dependencies&&await this.resolveDeps(s.dependencies),await this.injectSystemDeps(s.dependencies);let i=this.reconstructMoveToml(s,this.globalAddresses),o={...t,"Move.toml":i};return{files:JSON.stringify(o),dependencies:JSON.stringify(this.dependencyFiles)}}mergeAddresses(e){for(let[t,s]of Object.entries(e))this.globalAddresses[t]=this.normalizeAddress(s)}normalizeAddress(e){if(!e)return e;let t=e;return t.startsWith("0x")&&(t=t.slice(2)),/^[0-9a-fA-F]+$/.test(t)?"0x"+t.padStart(64,"0"):e}async resolveDeps(e,t=null){for(let[s,i]of Object.entries(e)){let o,c,l;if(i.git)o=i.git,c=i.rev,l=i.subdir;else if(i.local){if(!t)continue;o=t.git,c=t.rev,l=this.resolvePath(t.subdir||"",i.local)}else continue;let r=`${o}|${c}|${l||""}`;if(this.visited.has(r))continue;this.visited.add(r);let a=await this.fetcher.fetch(o,c,l),d=null;for(let[u,f]of Object.entries(a))if(u.endsWith("Move.toml")){d=f;break}if(d){let u=h(d);u.addresses&&this.mergeAddresses(u.addresses),u.dependencies&&await this.resolveDeps(u.dependencies,{git:o,rev:c,subdir:l})}for(let[u,f]of Object.entries(a))if(u.endsWith(".move")||u.endsWith("Move.toml")){let k=`dependencies/${s}/${u}`;this.dependencyFiles[k]=f}}}resolvePath(e,t){let s=e.split("/").filter(o=>o&&o!=="."),i=t.split("/").filter(o=>o&&o!==".");for(let o of i)o===".."?s.pop():s.push(o);return s.join("/")}reconstructMoveToml(e,t){let s=`[package]
2
+ name = "${e.package.name}"
3
+ version = "${e.package.version}"
4
+ `;if(e.package.edition&&(s+=`edition = "${e.package.edition}"
5
+ `),s+=`
248
6
  [dependencies]
249
- `;
250
- if (originalParsed.dependencies) {
251
- for (const [name, info] of Object.entries(originalParsed.dependencies)) {
252
- newToml += `${name} = { git = "${info.git}", rev = "${info.rev}" }
253
- `;
254
- }
255
- }
256
- newToml += `
7
+ `,e.dependencies)for(let[i,o]of Object.entries(e.dependencies))s+=`${i} = { git = "${o.git}", rev = "${o.rev}" }
8
+ `;s+=`
257
9
  [addresses]
258
- `;
259
- for (const [addrName, addrVal] of Object.entries(addresses)) {
260
- newToml += `${addrName} = "${addrVal}"
261
- `;
262
- }
263
- return newToml;
264
- }
265
- async injectSystemDepsFromRoot(depsObj) {
266
- for (const depInfo of Object.values(depsObj)) {
267
- if (!depInfo || !depInfo.git || !depInfo.rev) continue;
268
- if (!this.isSuiRepo(depInfo.git)) continue;
269
- await this.addImplicitSystemDepsForRepo(depInfo.git, depInfo.rev);
270
- return;
271
- }
272
- }
273
- async addImplicitSystemDepsForRepo(gitUrl, rev) {
274
- if (!this.isSuiRepo(gitUrl)) return;
275
- const cacheKey = `${gitUrl}|${rev}`;
276
- if (this.systemDepsLoaded.has(cacheKey)) return;
277
- this.systemDepsLoaded.add(cacheKey);
278
- const manifestPath = "crates/sui-framework-snapshot/manifest.json";
279
- if (!this.fetcher.fetchFile) return;
280
- let packages = null;
281
- try {
282
- const manifestText = await this.fetcher.fetchFile(gitUrl, rev, manifestPath);
283
- if (manifestText) {
284
- const manifest = JSON.parse(manifestText);
285
- const versions = Object.keys(manifest).map((v) => Number(v)).filter((v) => !Number.isNaN(v)).sort((a, b) => a - b);
286
- const latestVersion = versions[versions.length - 1];
287
- const latest = manifest[String(latestVersion)];
288
- if (latest && latest.packages) {
289
- packages = latest.packages;
290
- }
291
- }
292
- } catch (e) {
293
- }
294
- if (!packages) {
295
- packages = [
296
- { name: "MoveStdlib", id: "0x1" },
297
- { name: "Sui", id: "0x2" },
298
- { name: "SuiSystem", id: "0x3" },
299
- { name: "Bridge", id: "0xb" }
300
- ];
301
- }
302
- for (const pkg of packages) {
303
- if (!pkg || !pkg.name || !pkg.id) continue;
304
- if (pkg.name === "DeepBook") continue;
305
- const targetPath = `dependencies/${pkg.name}/Move.toml`;
306
- if (this.dependencyFiles[targetPath]) continue;
307
- const moveToml = [
308
- "[package]",
309
- `name = "${pkg.name}"`,
310
- 'version = "0.0.0"',
311
- `published-at = "${pkg.id}"`,
312
- ""
313
- ].join("\n");
314
- this.dependencyFiles[targetPath] = moveToml;
315
- }
316
- }
317
- isSuiRepo(gitUrl) {
318
- return gitUrl.includes("github.com/MystenLabs/sui");
319
- }
320
- };
321
- async function resolve(rootMoveTomlContent, rootSourceFiles, fetcher) {
322
- const resolver = new Resolver(fetcher);
323
- return resolver.resolve(rootMoveTomlContent, rootSourceFiles);
324
- }
325
-
326
- // src/fetcher.ts
327
- var Fetcher = class {
328
- /** Fetch a package. Return map of path -> content. */
329
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
330
- async fetch(_gitUrl, _rev, _subdir) {
331
- throw new Error("Not implemented");
332
- }
333
- /** Fetch a single file from a repository. */
334
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
335
- async fetchFile(_gitUrl, _rev, _path) {
336
- throw new Error("Not implemented");
337
- }
338
- };
339
- var GitHubFetcher = class extends Fetcher {
340
- constructor() {
341
- super();
342
- this.cache = /* @__PURE__ */ new Map();
343
- }
344
- async fetch(gitUrl, rev, subdir) {
345
- const { owner, repo } = this.parseGitUrl(gitUrl);
346
- if (!owner || !repo) {
347
- throw new Error(`Invalid git URL: ${gitUrl}`);
348
- }
349
- const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${rev}?recursive=1`;
350
- let treeData;
351
- try {
352
- const resp = await fetch(treeUrl);
353
- if (!resp.ok) {
354
- if (resp.status === 403 || resp.status === 429) {
355
- throw new Error("GitHub API rate limit exceeded.");
356
- }
357
- throw new Error(`Failed to fetch tree: ${resp.statusText}`);
358
- }
359
- treeData = await resp.json();
360
- } catch (e) {
361
- return {};
362
- }
363
- const files = {};
364
- const fetchPromises = [];
365
- for (const item of treeData.tree) {
366
- if (item.type !== "blob") continue;
367
- let relativePath = item.path;
368
- if (subdir) {
369
- if (!item.path.startsWith(subdir)) continue;
370
- relativePath = item.path.slice(subdir.length);
371
- if (relativePath.startsWith("/")) {
372
- relativePath = relativePath.slice(1);
373
- }
374
- }
375
- if (!relativePath.endsWith(".move") && relativePath !== "Move.toml") {
376
- continue;
377
- }
378
- const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${rev}/${item.path}`;
379
- const p = this.fetchContent(rawUrl).then((content) => {
380
- if (content) {
381
- files[relativePath] = content;
382
- }
383
- });
384
- fetchPromises.push(p);
385
- }
386
- await Promise.all(fetchPromises);
387
- return files;
388
- }
389
- async fetchFile(gitUrl, rev, path) {
390
- const { owner, repo } = this.parseGitUrl(gitUrl);
391
- if (!owner || !repo) {
392
- throw new Error(`Invalid git URL: ${gitUrl}`);
393
- }
394
- const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${rev}/${path}`;
395
- return this.fetchContent(rawUrl);
396
- }
397
- async fetchContent(url) {
398
- if (this.cache.has(url)) {
399
- return this.cache.get(url) ?? null;
400
- }
401
- try {
402
- const resp = await fetch(url);
403
- if (!resp.ok) return null;
404
- const text = await resp.text();
405
- this.cache.set(url, text);
406
- return text;
407
- } catch (e) {
408
- return null;
409
- }
410
- }
411
- parseGitUrl(url) {
412
- try {
413
- const urlObj = new URL(url);
414
- const parts = urlObj.pathname.split("/").filter((p) => p);
415
- if (parts.length >= 2) {
416
- let repo = parts[1];
417
- if (repo.endsWith(".git")) {
418
- repo = repo.slice(0, -4);
419
- }
420
- return { owner: parts[0], repo };
421
- }
422
- } catch (e) {
423
- }
424
- return { owner: null, repo: null };
425
- }
426
- };
427
-
428
- // src/index.ts
429
- var import_meta = {};
430
- var wasmUrl = (() => {
431
- try {
432
- return new URL("./sui_move_wasm_bg.wasm", import_meta.url);
433
- } catch {
434
- return "./sui_move_wasm_bg.wasm";
435
- }
436
- })();
437
- var wasmReady;
438
- async function loadWasm(customWasm) {
439
- if (!wasmReady) {
440
- wasmReady = import("./sui_move_wasm.js").then(async (mod) => {
441
- await mod.default(customWasm ?? wasmUrl);
442
- return mod;
443
- });
444
- }
445
- return wasmReady;
446
- }
447
- function toJson(value) {
448
- return JSON.stringify(value ?? {});
449
- }
450
- function asFailure(err) {
451
- const msg = err instanceof Error ? err.message : typeof err === "string" ? err : "Unknown error";
452
- return { success: false, error: msg };
453
- }
454
- function ensureCompileResult(result) {
455
- if (typeof result !== "object" || result === null) {
456
- throw new Error("Unexpected compile result shape from wasm");
457
- }
458
- const asAny = result;
459
- if (typeof asAny.success === "function" && typeof asAny.output === "function") {
460
- return asAny;
461
- }
462
- if (typeof asAny.success === "boolean" && typeof asAny.output === "string") {
463
- return {
464
- success: () => asAny.success,
465
- output: () => asAny.output
466
- };
467
- }
468
- throw new Error("Unexpected compile result shape from wasm");
469
- }
470
- function parseCompileResult(output) {
471
- const toHex = (bytes) => bytes.map((b) => b.toString(16).padStart(2, "0")).join("");
472
- try {
473
- const parsed = JSON.parse(output);
474
- if (!parsed.modules || !parsed.dependencies || !parsed.digest) {
475
- throw new Error("missing fields in compiler output");
476
- }
477
- const digestHex = typeof parsed.digest === "string" ? parsed.digest : toHex(parsed.digest);
478
- return {
479
- success: true,
480
- modules: parsed.modules,
481
- dependencies: parsed.dependencies,
482
- digest: digestHex
483
- };
484
- } catch (error) {
485
- return asFailure(error);
486
- }
487
- }
488
- async function initMoveCompiler(options) {
489
- await loadWasm(options?.wasm);
490
- }
491
- async function buildMovePackage(input) {
492
- try {
493
- const mod = await loadWasm(input.wasm);
494
- const raw = input.ansiColor && typeof mod.compile_with_color === "function" ? mod.compile_with_color(
495
- toJson(input.files),
496
- toJson(input.dependencies ?? {}),
497
- true
498
- ) : mod.compile(
499
- toJson(input.files),
500
- toJson(input.dependencies ?? {})
501
- );
502
- const result = ensureCompileResult(raw);
503
- const ok = result.success();
504
- const output = result.output();
505
- if (!ok) {
506
- return asFailure(output);
507
- }
508
- return parseCompileResult(output);
509
- } catch (error) {
510
- return asFailure(error);
511
- }
512
- }
513
- async function getSuiMoveVersion(options) {
514
- const mod = await loadWasm(options?.wasm);
515
- return mod.sui_move_version();
516
- }
517
- async function getSuiVersion(options) {
518
- const mod = await loadWasm(options?.wasm);
519
- return mod.sui_version();
520
- }
521
- async function getWasmBindings(options) {
522
- return loadWasm(options?.wasm);
523
- }
524
- async function compileRaw(filesJson, depsJson, options) {
525
- const mod = await loadWasm(options?.wasm);
526
- const raw = options?.ansiColor && typeof mod.compile_with_color === "function" ? mod.compile_with_color(filesJson, depsJson, true) : mod.compile(filesJson, depsJson);
527
- const result = ensureCompileResult(raw);
528
- return {
529
- success: result.success(),
530
- output: result.output()
531
- };
532
- }
533
- // Annotate the CommonJS export names for ESM import in node:
534
- 0 && (module.exports = {
535
- Fetcher,
536
- GitHubFetcher,
537
- Resolver,
538
- buildMovePackage,
539
- compileRaw,
540
- getSuiMoveVersion,
541
- getSuiVersion,
542
- getWasmBindings,
543
- initMoveCompiler,
544
- parseToml,
545
- resolve
546
- });
547
- //# sourceMappingURL=index.cjs.map
10
+ `;for(let[i,o]of Object.entries(t))s+=`${i} = "${o}"
11
+ `;return s}async injectSystemDeps(e){if(e){for(let s of Object.values(e))if(!(!s||!s.git||!s.rev)&&this.isSuiRepo(s.git)){await this.addImplicitSystemDepsForRepo(s.git,s.rev);break}}this.dependencyFiles["dependencies/MoveStdlib/Move.toml"]||this.addFallbackSystemDeps()}async addImplicitSystemDepsForRepo(e,t){if(!this.isSuiRepo(e))return;let s=`${e}|${t}`;if(this.systemDepsLoaded.has(s))return;this.systemDepsLoaded.add(s);let i="crates/sui-framework-snapshot/manifest.json";if(!this.fetcher.fetchFile)return;let o=null;try{let c=await this.fetcher.fetchFile(e,t,i);if(c){let l=JSON.parse(c),r=Object.keys(l).map(u=>Number(u)).filter(u=>!Number.isNaN(u)).sort((u,f)=>u-f),a=r[r.length-1],d=l[String(a)];d&&d.packages&&(o=d.packages)}}catch{}o||(o=this.fallbackSystemPackages());for(let c of o)!c||!c.name||!c.id||c.name!=="DeepBook"&&this.addSystemDep(c.name,c.id)}addFallbackSystemDeps(){for(let e of this.fallbackSystemPackages())!e||!e.name||!e.id||e.name!=="DeepBook"&&this.addSystemDep(e.name,e.id)}addSystemDep(e,t){let s=`dependencies/${e}/Move.toml`;if(this.dependencyFiles[s])return;let i=["[package]",`name = "${e}"`,'version = "0.0.0"',`published-at = "${this.normalizeAddress(t)}"`,""].join(`
12
+ `);this.dependencyFiles[s]=i}fallbackSystemPackages(){return[{name:"MoveStdlib",id:"0x1"},{name:"Sui",id:"0x2"},{name:"SuiSystem",id:"0x3"},{name:"Bridge",id:"0xb"}]}isSuiRepo(e){return e.includes("github.com/MystenLabs/sui")}};async function b(n,e,t){return new y(t).resolve(n,e)}var Y={},I=(()=>{try{return new URL("./sui_move_wasm_bg.wasm",Y.url)}catch{return"./sui_move_wasm_bg.wasm"}})(),R;async function m(n){return R||(R=import("./sui_move_wasm.js").then(async e=>(await e.default(n??I),e))),R}function S(n){return JSON.stringify(n??{})}function $(n){return{success:!1,error:n instanceof Error?n.message:typeof n=="string"?n:"Unknown error"}}function D(n){if(typeof n!="object"||n===null)throw new Error("Unexpected compile result shape from wasm");let e=n;if(typeof e.success=="function"&&typeof e.output=="function")return e;if(typeof e.success=="boolean"&&typeof e.output=="string")return{success:()=>e.success,output:()=>e.output};throw new Error("Unexpected compile result shape from wasm")}function C(n){let e=t=>t.map(s=>s.toString(16).padStart(2,"0")).join("");try{let t=JSON.parse(n);if(!t.modules||!t.dependencies||!t.digest)throw new Error("missing fields in compiler output");let s=typeof t.digest=="string"?t.digest:e(t.digest);return{success:!0,modules:t.modules,dependencies:t.dependencies,digest:s}}catch(t){return $(t)}}function P(n){if(!n)return n;let e=n;return e.startsWith("0x")&&(e=e.slice(2)),/^[0-9a-fA-F]+$/.test(e)?"0x"+e.padStart(64,"0"):n}function z(n){let e={std:"0x1",sui:"0x2",sui_system:"0x3",bridge:"0xb"},t=n.split(/\r?\n/),s=/^\s*\[[^\]]+\]\s*$/,i=-1,o=t.length;for(let r=0;r<t.length;r++)if(/^\s*\[addresses\]\s*$/.test(t[r])){i=r;for(let a=r+1;a<t.length;a++)if(s.test(t[a])){o=a;break}break}let c=new Set;if(i>=0)for(let r=i+1;r<o;r++){let a=t[r].trim();if(!a||a.startsWith("#"))continue;let d=a.match(/^([A-Za-z0-9_.-]+)\s*=/);d&&c.add(d[1])}let l=Object.entries(e).filter(([r])=>!c.has(r)).map(([r,a])=>`${r} = "${P(a)}"`);return l.length===0?n:(i>=0?t.splice(o,0,...l):t.push("","[addresses]",...l),t.join(`
13
+ `))}function H(n){let e=[{name:"Sui",git:"https://github.com/MystenLabs/sui.git",subdir:"crates/sui-framework/packages/sui-framework",rev:"framework/mainnet"},{name:"MoveStdlib",git:"https://github.com/MystenLabs/sui.git",subdir:"crates/sui-framework/packages/move-stdlib",rev:"framework/mainnet"}],t=n.split(/\r?\n/),s=/^\s*\[[^\]]+\]\s*$/,i=-1,o=t.length;for(let r=0;r<t.length;r++)if(/^\s*\[dependencies\]\s*$/.test(t[r])){i=r;for(let a=r+1;a<t.length;a++)if(s.test(t[a])){o=a;break}break}let c=new Set;if(i>=0)for(let r=i+1;r<o;r++){let a=t[r].trim();if(!a||a.startsWith("#"))continue;let d=a.match(/^([A-Za-z0-9_.-]+)\s*=/);d&&c.add(d[1])}let l=e.filter(r=>!c.has(r.name)).map(r=>`${r.name} = { git = "${r.git}", subdir = "${r.subdir}", rev = "${r.rev}" }`);return l.length===0?n:(i>=0?t.splice(o,0,...l):t.push("","[dependencies]",...l),t.join(`
14
+ `))}function G(n){let e={...n??{}};if(e["dependencies/MoveStdlib/Move.toml"])return e;let t=[{name:"MoveStdlib",id:"0x1"},{name:"Sui",id:"0x2"},{name:"SuiSystem",id:"0x3"},{name:"Bridge",id:"0xb"}];for(let s of t){let i=`dependencies/${s.name}/Move.toml`;e[i]||(e[i]=["[package]",`name = "${s.name}"`,'version = "0.0.0"',`published-at = "${P(s.id)}"`,""].join(`
15
+ `))}return e}function F(n){return!!(n?.["dependencies/MoveStdlib/Move.toml"]&&n?.["dependencies/Sui/Move.toml"])}function _(n){return typeof n=="string"?JSON.parse(n):n}async function J(n){await m(n?.wasm)}async function q(n){try{let e=n.dependencies??{},t={...n.files},s=typeof t["Move.toml"]=="string";if(n.autoSystemDeps&&s){let a=z(t["Move.toml"]);F(e)||(a=H(a)),t["Move.toml"]=a}if(n.autoSystemDeps&&!F(e)&&s){let a=await b(t["Move.toml"],t,new p);t=_(a.files),e=_(a.dependencies)}else n.autoSystemDeps&&(e=G(e));let i=await m(n.wasm),o=n.ansiColor&&typeof i.compile_with_color=="function"?i.compile_with_color(S(t),S(e),!0):i.compile(S(t),S(e)),c=D(o),l=c.success(),r=c.output();return l?C(r):$(r)}catch(e){return $(e)}}async function V(n){return(await m(n?.wasm)).sui_move_version()}async function K(n){return(await m(n?.wasm)).sui_version()}async function Q(n){return m(n?.wasm)}async function Z(n,e,t){let s=await m(t?.wasm),i=t?.ansiColor&&typeof s.compile_with_color=="function"?s.compile_with_color(n,e,!0):s.compile(n,e),o=D(i);return{success:o.success(),output:o.output()}}0&&(module.exports={Fetcher,GitHubFetcher,Resolver,buildMovePackage,compileRaw,getSuiMoveVersion,getSuiVersion,getWasmBindings,initMoveCompiler,parseToml,resolve});
package/dist/index.d.cts CHANGED
@@ -33,8 +33,11 @@ declare class Resolver {
33
33
  private resolveDeps;
34
34
  private resolvePath;
35
35
  private reconstructMoveToml;
36
- private injectSystemDepsFromRoot;
36
+ private injectSystemDeps;
37
37
  private addImplicitSystemDepsForRepo;
38
+ private addFallbackSystemDeps;
39
+ private addSystemDep;
40
+ private fallbackSystemPackages;
38
41
  private isSuiRepo;
39
42
  }
40
43
  declare function resolve(rootMoveTomlContent: string, rootSourceFiles: Record<string, string>, fetcher: Fetcher): Promise<{
@@ -57,6 +60,8 @@ interface BuildInput {
57
60
  wasm?: string | URL;
58
61
  /** Emit ANSI color codes in diagnostics when available. */
59
62
  ansiColor?: boolean;
63
+ /** Inject standard Sui system packages when missing (CLI-like behavior). */
64
+ autoSystemDeps?: boolean;
60
65
  }
61
66
  interface BuildSuccess {
62
67
  success: true;
package/dist/index.d.ts CHANGED
@@ -33,8 +33,11 @@ declare class Resolver {
33
33
  private resolveDeps;
34
34
  private resolvePath;
35
35
  private reconstructMoveToml;
36
- private injectSystemDepsFromRoot;
36
+ private injectSystemDeps;
37
37
  private addImplicitSystemDepsForRepo;
38
+ private addFallbackSystemDeps;
39
+ private addSystemDep;
40
+ private fallbackSystemPackages;
38
41
  private isSuiRepo;
39
42
  }
40
43
  declare function resolve(rootMoveTomlContent: string, rootSourceFiles: Record<string, string>, fetcher: Fetcher): Promise<{
@@ -57,6 +60,8 @@ interface BuildInput {
57
60
  wasm?: string | URL;
58
61
  /** Emit ANSI color codes in diagnostics when available. */
59
62
  ansiColor?: boolean;
63
+ /** Inject standard Sui system packages when missing (CLI-like behavior). */
64
+ autoSystemDeps?: boolean;
60
65
  }
61
66
  interface BuildSuccess {
62
67
  success: true;