@needmoretruth/nmts-cli 0.45.0 → 0.46.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.
Files changed (224) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +61 -0
  3. package/README.ko.md +6 -3
  4. package/README.md +15 -3
  5. package/dist/api-advice.js +17 -2
  6. package/dist/api.d.ts +22 -0
  7. package/dist/api.js +49 -1
  8. package/dist/arg-options.d.ts +8 -0
  9. package/dist/args.js +7 -1
  10. package/dist/artifact-about.d.ts +1 -1
  11. package/dist/collision.d.ts +20 -3
  12. package/dist/collision.js +21 -3
  13. package/dist/commands/erase.js +1 -0
  14. package/dist/commands/handover.d.ts +13 -0
  15. package/dist/commands/handover.js +328 -0
  16. package/dist/commands/heavy-run.d.ts +59 -0
  17. package/dist/commands/heavy-run.js +247 -0
  18. package/dist/commands/heavy.d.ts +7 -0
  19. package/dist/commands/heavy.js +123 -0
  20. package/dist/commands/ls.d.ts +5 -0
  21. package/dist/commands/ls.js +9 -1
  22. package/dist/commands/public-code.d.ts +6 -0
  23. package/dist/commands/public-code.js +46 -0
  24. package/dist/commands/push-heavy.d.ts +6 -0
  25. package/dist/commands/push-heavy.js +128 -0
  26. package/dist/commands/push-tree.d.ts +24 -0
  27. package/dist/commands/push-tree.js +91 -0
  28. package/dist/commands/push.d.ts +4 -13
  29. package/dist/commands/push.js +7 -77
  30. package/dist/commands/put-heavy.d.ts +9 -0
  31. package/dist/commands/put-heavy.js +120 -0
  32. package/dist/commands/put-payer.d.ts +21 -0
  33. package/dist/commands/put-payer.js +24 -0
  34. package/dist/commands/put.d.ts +2 -2
  35. package/dist/commands/put.js +8 -7
  36. package/dist/commands/receive.js +3 -3
  37. package/dist/commands/s3.js +44 -10
  38. package/dist/crypto-surface.d.ts +8 -0
  39. package/dist/crypto-surface.js +3 -0
  40. package/dist/crypto.d.ts +3 -0
  41. package/dist/crypto.js +3 -0
  42. package/dist/download-part.d.ts +32 -1
  43. package/dist/download-part.js +95 -6
  44. package/dist/download-range.d.ts +19 -0
  45. package/dist/download-range.js +108 -0
  46. package/dist/download-sink.d.ts +15 -0
  47. package/dist/download.d.ts +14 -0
  48. package/dist/download.js +19 -4
  49. package/dist/handover.d.ts +44 -0
  50. package/dist/handover.js +199 -0
  51. package/dist/heavy-api.d.ts +36 -0
  52. package/dist/heavy-api.js +107 -0
  53. package/dist/heavy-copy.d.ts +72 -0
  54. package/dist/heavy-copy.js +108 -0
  55. package/dist/heavy-evm.d.ts +20 -0
  56. package/dist/heavy-evm.js +106 -0
  57. package/dist/heavy-self-pay.d.ts +92 -0
  58. package/dist/heavy-self-pay.js +167 -0
  59. package/dist/heavy-upload.d.ts +87 -0
  60. package/dist/heavy-upload.js +154 -0
  61. package/dist/heavy-wallet-pay.d.ts +39 -0
  62. package/dist/heavy-wallet-pay.js +73 -0
  63. package/dist/help-options.js +4 -2
  64. package/dist/help.js +16 -3
  65. package/dist/list-tier.d.ts +7 -0
  66. package/dist/list-tier.js +47 -0
  67. package/dist/main.js +12 -10
  68. package/dist/manifest-write.d.ts +4 -3
  69. package/dist/platform-sign.d.ts +4 -4
  70. package/dist/platform-sign.js +3 -3
  71. package/dist/portable.d.ts +15 -0
  72. package/dist/portable.js +11 -0
  73. package/dist/product.d.ts +1 -1
  74. package/dist/product.js +1 -1
  75. package/dist/recovery-build.js +16 -0
  76. package/dist/recovery-map-part.d.ts +82 -0
  77. package/dist/recovery-map-part.js +83 -0
  78. package/dist/recovery-map.d.ts +5 -40
  79. package/dist/recovery-map.js +18 -1
  80. package/dist/recovery-source.d.ts +3 -0
  81. package/dist/recovery-source.js +9 -0
  82. package/dist/risk.d.ts +30 -0
  83. package/dist/risk.js +23 -2
  84. package/dist/run-log.d.ts +1 -1
  85. package/dist/run-log.js +7 -1
  86. package/dist/s3/address.d.ts +20 -0
  87. package/dist/s3/address.js +97 -0
  88. package/dist/s3/answer.d.ts +48 -0
  89. package/dist/s3/answer.js +330 -0
  90. package/dist/s3/body-deframe.d.ts +49 -0
  91. package/dist/s3/body-deframe.js +264 -0
  92. package/dist/s3/body-measure.d.ts +13 -0
  93. package/dist/s3/body-measure.js +48 -0
  94. package/dist/s3/body-plan.d.ts +31 -0
  95. package/dist/s3/body-plan.js +159 -0
  96. package/dist/s3/body.d.ts +46 -0
  97. package/dist/s3/body.js +117 -0
  98. package/dist/s3/call.d.ts +36 -0
  99. package/dist/s3/call.js +42 -0
  100. package/dist/s3/checksum.d.ts +26 -0
  101. package/dist/s3/checksum.js +176 -0
  102. package/dist/s3/content-type.d.ts +3 -0
  103. package/dist/s3/content-type.js +49 -0
  104. package/dist/s3/contract.d.ts +91 -14
  105. package/dist/s3/drive-conditions.d.ts +47 -0
  106. package/dist/s3/drive-conditions.js +134 -0
  107. package/dist/s3/drive-key.d.ts +11 -0
  108. package/dist/s3/drive-key.js +58 -0
  109. package/dist/s3/drive-limits.d.ts +33 -0
  110. package/dist/s3/drive-limits.js +53 -0
  111. package/dist/s3/drive-lock.d.ts +11 -0
  112. package/dist/s3/drive-lock.js +47 -0
  113. package/dist/s3/drive-trashed-name.d.ts +13 -0
  114. package/dist/s3/drive-trashed-name.js +59 -0
  115. package/dist/s3/drive-write.d.ts +38 -0
  116. package/dist/s3/drive-write.js +258 -0
  117. package/dist/s3/drive.d.ts +59 -25
  118. package/dist/s3/drive.js +46 -77
  119. package/dist/s3/listing.d.ts +27 -1
  120. package/dist/s3/listing.js +62 -20
  121. package/dist/s3/long-answer.d.ts +12 -0
  122. package/dist/s3/long-answer.js +104 -0
  123. package/dist/s3/multipart-assemble.d.ts +17 -0
  124. package/dist/s3/multipart-assemble.js +68 -0
  125. package/dist/s3/multipart-sweep.d.ts +15 -0
  126. package/dist/s3/multipart-sweep.js +87 -0
  127. package/dist/s3/multipart-view.d.ts +45 -0
  128. package/dist/s3/multipart-view.js +232 -0
  129. package/dist/s3/multipart.d.ts +26 -19
  130. package/dist/s3/multipart.js +193 -78
  131. package/dist/s3/object-read.d.ts +17 -0
  132. package/dist/s3/object-read.js +127 -0
  133. package/dist/s3/object-write.d.ts +35 -0
  134. package/dist/s3/object-write.js +198 -0
  135. package/dist/s3/range.d.ts +14 -0
  136. package/dist/s3/range.js +80 -0
  137. package/dist/s3/response-sink.d.ts +12 -2
  138. package/dist/s3/response-sink.js +71 -7
  139. package/dist/s3/routes.d.ts +0 -1
  140. package/dist/s3/routes.js +242 -217
  141. package/dist/s3/same-file.d.ts +4 -1
  142. package/dist/s3/same-file.js +12 -3
  143. package/dist/s3/server.d.ts +54 -4
  144. package/dist/s3/server.js +174 -14
  145. package/dist/s3/sigv4-canonical.d.ts +91 -0
  146. package/dist/s3/sigv4-canonical.js +148 -0
  147. package/dist/s3/sigv4-presigned.d.ts +13 -0
  148. package/dist/s3/sigv4-presigned.js +82 -0
  149. package/dist/s3/sigv4.d.ts +26 -27
  150. package/dist/s3/sigv4.js +137 -102
  151. package/dist/s3/spool.d.ts +37 -0
  152. package/dist/s3/spool.js +104 -0
  153. package/dist/s3/staging.d.ts +90 -7
  154. package/dist/s3/staging.js +97 -66
  155. package/dist/s3/xml-multipart.d.ts +38 -0
  156. package/dist/s3/xml-multipart.js +47 -0
  157. package/dist/s3/xml-read.d.ts +28 -0
  158. package/dist/s3/xml-read.js +235 -0
  159. package/dist/s3/xml.d.ts +45 -2
  160. package/dist/s3/xml.js +72 -13
  161. package/dist/s3-gateway.d.ts +11 -5
  162. package/dist/s3-gateway.js +5 -2
  163. package/dist/seal.d.ts +1 -1
  164. package/dist/share.d.ts +5 -0
  165. package/dist/share.js +1 -1
  166. package/dist/shared/lib/api/types-heavy.d.ts +167 -0
  167. package/dist/shared/lib/api/types-heavy.js +60 -0
  168. package/dist/shared/lib/drive/rebuild-verify.js +1 -0
  169. package/dist/shared/lib/filecoin/providers.d.ts +25 -0
  170. package/dist/shared/lib/filecoin/providers.js +58 -0
  171. package/dist/shared/lib/heavy/download.d.ts +48 -0
  172. package/dist/shared/lib/heavy/download.js +116 -0
  173. package/dist/shared/lib/heavy/order-plan.d.ts +77 -0
  174. package/dist/shared/lib/heavy/order-plan.js +83 -0
  175. package/dist/shared/lib/heavy/order-runner.d.ts +9 -0
  176. package/dist/shared/lib/heavy/order-runner.js +300 -0
  177. package/dist/shared/lib/heavy/order-types.d.ts +90 -0
  178. package/dist/shared/lib/heavy/order-types.js +6 -0
  179. package/dist/shared/lib/heavy/order-wire.d.ts +55 -0
  180. package/dist/shared/lib/heavy/order-wire.js +113 -0
  181. package/dist/shared/lib/heavy/piece-cid.d.ts +24 -0
  182. package/dist/shared/lib/heavy/piece-cid.js +55 -0
  183. package/dist/shared/lib/heavy/sp-upload.d.ts +37 -0
  184. package/dist/shared/lib/heavy/sp-upload.js +112 -0
  185. package/dist/shared/lib/heavy/synapse-piece.d.ts +1 -0
  186. package/dist/shared/lib/heavy/synapse-piece.js +8 -0
  187. package/dist/shared/lib/share/handover-format.d.ts +129 -0
  188. package/dist/shared/lib/share/handover-format.js +323 -0
  189. package/dist/shared/lib/share/shared-file-info.js +1 -0
  190. package/dist/shared/lib/storage-network.d.ts +4 -4
  191. package/dist/shared/lib/storage-network.js +7 -7
  192. package/dist/shared/lib/storage-tier.d.ts +28 -0
  193. package/dist/shared/lib/storage-tier.js +63 -0
  194. package/dist/shared/lib/wallet/send-rules.js +1 -0
  195. package/dist/upload-file.d.ts +8 -0
  196. package/dist/upload-file.js +57 -25
  197. package/dist/upload-price-node.d.ts +3 -0
  198. package/dist/upload-price-node.js +3 -6
  199. package/dist/upload-price.d.ts +10 -0
  200. package/dist/upload-price.js +13 -1
  201. package/dist/upload-run.d.ts +80 -0
  202. package/dist/upload-run.js +173 -0
  203. package/dist/upload-steps.js +15 -4
  204. package/dist/upload-store.d.ts +15 -6
  205. package/dist/upload-store.js +6 -0
  206. package/dist/upload-wallet-put.d.ts +9 -4
  207. package/dist/upload-wallet-put.js +16 -6
  208. package/dist/upload-wallet.js +4 -0
  209. package/dist/upload-wire.d.ts +25 -0
  210. package/dist/upload-wire.js +20 -1
  211. package/dist/upload.js +28 -13
  212. package/dist/wallet-sign.js +2 -2
  213. package/docs/commands/handover.md +38 -0
  214. package/docs/commands/heavy.md +35 -0
  215. package/docs/commands/public-code.md +7 -0
  216. package/docs/commands/push.md +4 -1
  217. package/docs/commands/put.md +15 -1
  218. package/docs/commands/share.md +3 -1
  219. package/package.json +5 -2
  220. package/server.json +2 -2
  221. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +17 -1
  222. package/vendor/nmts-crypto/nmts_crypto_wasm.js +28 -0
  223. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  224. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +2 -1
@@ -0,0 +1,123 @@
1
+ // `nmts heavy wallet` and `nmts heavy fund <USDFC>` — the EVM wallet this NMTS key derives for NMTS
2
+ // Heavy's self-paid road (developer mode): what it holds, and filling its Filecoin Pay deposit.
3
+ //
4
+ // ⛔ `wallet` READS AND NEVER SIGNS. The address is computed offline from the key (`heavy-evm.ts`);
5
+ // the balances are read from the chain with the address alone, so no key is even derived.
6
+ //
7
+ // ⛔ `fund` SIGNS AND SPENDS, with `wallet send`'s rules: the review first, nothing without `--yes`,
8
+ // the wallet agreement at scope `all`, and Calibration only — refused before anything is read
9
+ // where no storage company is listed. The deposit and the operator approval are one call of the
10
+ // Synapse SDK (`payments.fundSync`, which is what `storage.prepare(…).transaction.execute` runs),
11
+ // given the amount that was typed instead of one it works out from piece sizes.
12
+ import { requireAccountCode } from "../code-access.js";
13
+ import { readCredentialsFile } from "../credentials.js";
14
+ import { NmtsError } from "../errors.js";
15
+ import { HEAVY_COPY } from "../heavy-copy.js";
16
+ import { evmAddressFor, evmIndexOf, evmKeyOf, hexKey } from "../heavy-evm.js";
17
+ import { selfPayChain, synapseFor } from "../heavy-self-pay.js";
18
+ import { resolveNetwork } from "../network.js";
19
+ import { resolveServer } from "../server.js";
20
+ import { FILECOIN_CHAIN_FOR_NETWORK } from "../shared/lib/filecoin/providers.js";
21
+ import { requireWalletGrant } from "../wallet-grant.js";
22
+ /** USDFC and FIL both count in 18 decimals. */
23
+ const DECIMALS = 18;
24
+ export async function heavy(verb, args, io = {}) {
25
+ if (verb === "wallet")
26
+ return heavyWallet(args, io);
27
+ if (verb === "fund")
28
+ return heavyFund(args.operands[1], args, io);
29
+ throw new NmtsError(HEAVY_COPY.heavyVerb, { exitCode: 2 });
30
+ }
31
+ async function where(args) {
32
+ const resolved = await requireAccountCode();
33
+ const stored = resolved.source === "file" || resolved.source === "file-locked" ? readCredentialsFile() : null;
34
+ const server = resolveServer(args.server ?? stored?.server);
35
+ const network = resolveNetwork(server, args.network ?? stored?.network);
36
+ return { code: resolved.code, chain: FILECOIN_CHAIN_FOR_NETWORK[network], network };
37
+ }
38
+ async function readPurse(address, chain) {
39
+ const synapse = await synapseFor(address, chain);
40
+ const [fil, usdfc, summary] = await Promise.all([
41
+ synapse.payments.walletBalance(),
42
+ synapse.payments.walletBalance({ token: "USDFC" }),
43
+ synapse.payments.accountSummary(),
44
+ ]);
45
+ return { fil, usdfc, summary };
46
+ }
47
+ async function heavyWallet(args, io) {
48
+ const say = io.write ?? ((line) => process.stdout.write(`${line}\n`));
49
+ const index = evmIndexOf(args.index);
50
+ const { code, chain } = await where(args);
51
+ const address = await evmAddressFor(code, index);
52
+ const { formatUnits } = await import("viem");
53
+ const purse = await readPurse(address, chain);
54
+ const coins = (value) => formatUnits(value, DECIMALS);
55
+ const facts = {
56
+ index,
57
+ address,
58
+ chain,
59
+ fil: coins(purse.fil),
60
+ usdfc: coins(purse.usdfc),
61
+ deposit: coins(purse.summary.funds),
62
+ available: coins(purse.summary.availableFunds),
63
+ lockupPerEpoch: coins(purse.summary.lockupRatePerEpoch),
64
+ epoch: purse.summary.epoch.toString(),
65
+ runwayEpochs: purse.summary.runwayInEpochs.toString(),
66
+ };
67
+ if (args.json) {
68
+ say(JSON.stringify(facts));
69
+ return 0;
70
+ }
71
+ say(`${HEAVY_COPY.walletAddress} ${address}`);
72
+ say(`${HEAVY_COPY.walletFil} ${facts.fil}`);
73
+ say(`${HEAVY_COPY.walletUsdfc} ${facts.usdfc}`);
74
+ say(`${HEAVY_COPY.walletDeposit} ${facts.deposit} (${facts.available})`);
75
+ say(`${HEAVY_COPY.walletRunway} ${facts.epoch} + ${facts.runwayEpochs}`);
76
+ return 0;
77
+ }
78
+ async function heavyFund(amountRaw, args, io) {
79
+ const say = io.write ?? ((line) => process.stdout.write(`${line}\n`));
80
+ const index = evmIndexOf(args.index);
81
+ const { code, network } = await where(args);
82
+ // ⛔ BEFORE ANYTHING IS READ: no listed company on this chain means nothing to fund for.
83
+ const chain = selfPayChain(network);
84
+ const { formatUnits, parseUnits } = await import("viem");
85
+ let amount;
86
+ try {
87
+ amount = parseUnits((amountRaw ?? "").trim(), DECIMALS);
88
+ }
89
+ catch {
90
+ // viem refuses what is not a decimal number; the words are this tool's.
91
+ amount = 0n;
92
+ }
93
+ if (amountRaw === undefined || amount <= 0n)
94
+ throw new NmtsError(HEAVY_COPY.fundBadAmount(amountRaw ?? ""), { exitCode: 2 });
95
+ const address = await evmAddressFor(code, index);
96
+ const purse = await readPurse(address, chain);
97
+ const facts = { index, address, chain, amount: formatUnits(amount, DECIMALS), usdfc: formatUnits(purse.usdfc, DECIMALS), deposit: formatUnits(purse.summary.funds, DECIMALS) };
98
+ if (!args.json) {
99
+ say(HEAVY_COPY.fundReview(facts.amount, address));
100
+ say(`${HEAVY_COPY.walletUsdfc} ${facts.usdfc}`);
101
+ say(`${HEAVY_COPY.walletDeposit} ${facts.deposit}`);
102
+ }
103
+ if (args.dryRun || !args.yes) {
104
+ if (args.json)
105
+ say(JSON.stringify({ ...facts, signed: false, dryRun: args.dryRun }));
106
+ if (args.dryRun)
107
+ return 0;
108
+ throw new NmtsError(HEAVY_COPY.fundNeedsYes, { exitCode: 4 });
109
+ }
110
+ requireWalletGrant("send", { walFrost: 0n, suiMist: 0n }, new Date(io.now ?? Date.now()));
111
+ const key = await evmKeyOf(code, index);
112
+ const { privateKeyToAccount } = await import("viem/accounts");
113
+ const account = privateKeyToAccount(hexKey(key));
114
+ key.fill(0);
115
+ const synapse = await synapseFor(account, chain);
116
+ const done = await synapse.payments.fundSync({ amount });
117
+ if (args.json) {
118
+ say(JSON.stringify({ ...facts, signed: true, hash: done.hash }));
119
+ return 0;
120
+ }
121
+ say(HEAVY_COPY.fundDone(done.hash));
122
+ return 0;
123
+ }
@@ -1,3 +1,4 @@
1
+ import type { StorageTier } from "../shared/lib/storage-tier.ts";
1
2
  export interface LsOptions {
2
3
  server?: string | undefined;
3
4
  network?: string | undefined;
@@ -18,6 +19,10 @@ export interface LsOptions {
18
19
  sort?: string | undefined;
19
20
  /** Reverse whichever order is in effect. */
20
21
  desc?: boolean;
22
+ /** Add the tier each file is stored on — one more read of the server per file (`list-tier.ts`). */
23
+ long?: boolean;
24
+ /** ⚠ A SEAM, NOT AN OPTION: where the tiers are read from. */
25
+ readTiers?: (ids: readonly string[]) => Promise<Map<string, StorageTier | null>>;
21
26
  write?: (line: string) => void;
22
27
  /** The instant the trash countdown is measured against. Passed in so one listing means one moment. */
23
28
  now?: number;
@@ -27,6 +27,7 @@ import { readFileList } from "../manifest.js";
27
27
  import { openSession } from "../session.js";
28
28
  import { daysLeftInTrash, TRASH_RETENTION_DAYS } from "../trash-sweep.js";
29
29
  import { humanSize } from "../units.js";
30
+ import { tierLabel, tiersOf } from "../list-tier.js";
30
31
  /**
31
32
  * How much of a trashed entry's thirty days is left, in the words beside its row.
32
33
  *
@@ -119,6 +120,11 @@ export async function ls(options = {}) {
119
120
  ...(e.pinned === true ? { pinned: true } : {}),
120
121
  }));
121
122
  const rows = sort === null ? byPath(mapped, dir) : orderRows(mapped, sort, dir);
123
+ const fileIds = options.long === true ? rows.filter((r) => r.kind !== KIND_FOLDER).map((r) => r.id) : [];
124
+ const tiers = options.long === true
125
+ ? await (options.readTiers ?? ((ids) => tiersOf(session.server, session.apiKey, ids)))(fileIds)
126
+ : null;
127
+ const tierOfRow = (row) => (row.kind === KIND_FOLDER ? "" : tierLabel(tiers?.get(row.id) ?? null));
122
128
  if (options.json) {
123
129
  say(JSON.stringify({
124
130
  state: "present",
@@ -141,6 +147,7 @@ export async function ls(options = {}) {
141
147
  trashed: row.trashed,
142
148
  trashedAt: row.trashedAt,
143
149
  marks: row.marks,
150
+ ...(tiers === null ? {} : { tier: row.kind === KIND_FOLDER ? null : (tiers.get(row.id) ?? null) }),
144
151
  })),
145
152
  }));
146
153
  return 0;
@@ -162,7 +169,8 @@ export async function ls(options = {}) {
162
169
  const mark = row.trashed
163
170
  ? ` [trash${row.trashedAt === null ? "" : `, ${trashWindow(row.trashedAt, now)}`}]`
164
171
  : "";
165
- say(`${row.path.padEnd(width)} ${size.padStart(9)}${mark}${markSuffix(row.marks)}`);
172
+ const tier = tiers === null ? "" : ` ${tierOfRow(row).padEnd(8)}`;
173
+ say(`${row.path.padEnd(width)} ${size.padStart(9)}${tier}${mark}${markSuffix(row.marks)}`);
166
174
  }
167
175
  say(``);
168
176
  const files = rows.filter((r) => r.kind !== KIND_FOLDER).length;
@@ -3,6 +3,12 @@ export interface PublicCodeOptions {
3
3
  network?: string | undefined;
4
4
  /** Publish it, so other accounts can send to it. Permanent. */
5
5
  publish?: boolean;
6
+ /** `--save [file]`: write this account's public code file (NCF-3 §5.7). Asks the server nothing. */
7
+ save?: boolean;
8
+ /** The file `--save` writes; by default `nmts-public-code-<code>.nmtscode` here. */
9
+ file?: string | undefined;
10
+ /** Replace that file if it exists. */
11
+ force?: boolean;
6
12
  json?: boolean;
7
13
  write?: (line: string) => void;
8
14
  }
@@ -22,7 +22,12 @@
22
22
  //
23
23
  // ⚠ IT IS NOT THE NMTS KEY. That one opens every file in the account and must never be given
24
24
  // to anybody; this one is meant to be given away, and on its own it opens nothing.
25
+ import { writeFileSync } from "node:fs";
26
+ import { resolve } from "node:path";
25
27
  import { request } from "../api.js";
28
+ import { requireAccountCode } from "../code-access.js";
29
+ import { publicCodeFileText } from "../handover.js";
30
+ import { publicCodeFileName } from "../shared/lib/share/handover-format.js";
26
31
  import { NmtsError } from "../errors.js";
27
32
  import { isRecord } from "../guards.js";
28
33
  import { loadCrypto } from "../crypto.js";
@@ -34,6 +39,12 @@ function b64(bytes) {
34
39
  }
35
40
  export async function publicCode(options = {}) {
36
41
  const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
42
+ if (options.save === true) {
43
+ if (options.publish === true) {
44
+ throw new NmtsError("--save and --publish are two different things; run them one at a time.", { exitCode: 2 });
45
+ }
46
+ return await savePublicCodeFile(options.file, options.force === true, say, options.json === true);
47
+ }
37
48
  const session = await openSession({ server: options.server, network: options.network });
38
49
  const crypt = await loadCrypto();
39
50
  const keys = shareKeysOf(crypt, session.code);
@@ -87,3 +98,38 @@ export async function publicCode(options = {}) {
87
98
  say(` ${BINARY_NAME} public-code --publish`);
88
99
  return 0;
89
100
  }
101
+ /**
102
+ * `nmts public-code --save [file]` — this account's public code file (NCF-3 §5.7).
103
+ *
104
+ * ⛔ NOTHING IN IT IS SECRET and nothing is asked of the server: the identity is derived from the
105
+ * NMTS key on this machine, exactly the bytes `--publish` would put on the server. Whoever holds
106
+ * the file can seal a handover to this account without looking the code up — which is the point:
107
+ * that lookup is the one thing that tells NMTS who is sending to whom.
108
+ */
109
+ async function savePublicCodeFile(file, force, say, json) {
110
+ const { code } = await requireAccountCode();
111
+ const crypt = await loadCrypto();
112
+ const keys = shareKeysOf(crypt, code);
113
+ const out = resolve(file === undefined || file === "" ? publicCodeFileName(keys.display) : file);
114
+ try {
115
+ writeFileSync(out, publicCodeFileText(keys), { flag: force ? "w" : "wx" });
116
+ }
117
+ catch {
118
+ throw new NmtsError(`Could not write ${out}.`, {
119
+ exitCode: 4,
120
+ nextStep: "If it already exists, name another file or replace it with --force.",
121
+ });
122
+ }
123
+ finally {
124
+ keys.wipe();
125
+ }
126
+ if (json) {
127
+ say(JSON.stringify({ code: keys.display, out }));
128
+ return 0;
129
+ }
130
+ say(`public code file ${out}`);
131
+ say(` for public code ${keys.display}`);
132
+ say(``);
133
+ say(`Whoever has this file can hand files over to you without asking NMTS.`);
134
+ return 0;
135
+ }
@@ -0,0 +1,6 @@
1
+ import { type PushOptions } from "./push.ts";
2
+ /** Cut the files into runs of at most one order's parts, in order. */
3
+ export declare function batchesOf<T extends {
4
+ size: number;
5
+ }>(files: readonly T[], partsOf: (one: T) => number): T[][];
6
+ export declare function pushHeavy(target: string, options: PushOptions): Promise<number>;
@@ -0,0 +1,128 @@
1
+ // `nmts push <directory> --tier heavy` — a whole directory into NMTS Heavy, keeping its shape.
2
+ //
3
+ // ⛔ ONE ORDER FOR THE DIRECTORY, not one per file: fifty small files are one order and — when the
4
+ // wallet pays — one signature. An order holds at most 256 parts, so a larger tree is sent as
5
+ // several orders one after another, each committed before the next begins.
6
+ //
7
+ // ⛔ WHAT IS ALREADY THERE IS SKIPPED, as on Standard, which is what makes running it again safe.
8
+ // And it stops at the first failure, saying what is already uploaded — the rule `push.ts` gives.
9
+ import { parseAsked } from "../collision.js";
10
+ import { loadCrypto } from "../crypto.js";
11
+ import { NmtsError } from "../errors.js";
12
+ import { planHeavyFile } from "../heavy-upload.js";
13
+ import { paddingRuleOf, readFileList } from "../manifest.js";
14
+ import { resolveNetwork } from "../network.js";
15
+ import { Progress, silentSink } from "../progress.js";
16
+ import { stderrSink } from "../progress-node.js";
17
+ import { openSession } from "../session.js";
18
+ import { HEAVY_MAX_SLOTS } from "../shared/lib/heavy/order-runner.js";
19
+ import { fileSource } from "../upload-file-node.js";
20
+ import { heavyDryRun, heavyPayerOf, recordHeavy, refuseHeavyClashes, runHeavy } from "./heavy-run.js";
21
+ import { payerAddressOf, sayDryRun } from "./put-heavy.js";
22
+ import { folderFor } from "./push.js";
23
+ import { localTree, splitAlready } from "./push-tree.js";
24
+ /** Cut the files into runs of at most one order's parts, in order. */
25
+ export function batchesOf(files, partsOf) {
26
+ const out = [];
27
+ let current = [];
28
+ let slots = 0;
29
+ for (const one of files) {
30
+ const parts = partsOf(one);
31
+ if (current.length > 0 && slots + parts > HEAVY_MAX_SLOTS) {
32
+ out.push(current);
33
+ current = [];
34
+ slots = 0;
35
+ }
36
+ current.push(one);
37
+ slots += parts;
38
+ }
39
+ if (current.length > 0)
40
+ out.push(current);
41
+ return out;
42
+ }
43
+ export async function pushHeavy(target, options) {
44
+ const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
45
+ const payer = heavyPayerOf(options.pay);
46
+ refuseHeavyClashes(options, payer);
47
+ const { root, found } = localTree(target, options.to, options.hidden === true);
48
+ if (found.length === 0) {
49
+ if (options.json) {
50
+ say(JSON.stringify({ files: 0, uploaded: 0, skipped: 0 }));
51
+ return 0;
52
+ }
53
+ say(`${root} holds no files to send.`);
54
+ return 0;
55
+ }
56
+ const session = await openSession({ server: options.server, network: options.network });
57
+ const network = resolveNetwork(session.server, session.network);
58
+ const asked = parseAsked(options.onCollision);
59
+ const list = await readFileList(session.server, session.apiKey, session.code, session.accountId);
60
+ const rule = paddingRuleOf(list.manifest?.settings);
61
+ const { folderIds, already, todo } = splitAlready(list.manifest?.entries ?? [], found);
62
+ const heavyFile = (one, parentId) => ({
63
+ source: fileSource(one.local, one.size),
64
+ name: one.name,
65
+ parentId,
66
+ destination: one.folder,
67
+ });
68
+ if (options.dryRun === true) {
69
+ const facts = {
70
+ files: found.length,
71
+ toSend: todo.length,
72
+ skipped: already.length,
73
+ ...(todo.length === 0 ? {} : heavyDryRun(todo.map((one) => heavyFile(one, null)), rule, payer)),
74
+ ...(await payerAddressOf(session, payer, options, list.manifest?.settings)),
75
+ };
76
+ if (options.json)
77
+ say(JSON.stringify(facts));
78
+ else {
79
+ sayDryRun(say, `${todo.length} file${todo.length === 1 ? "" : "s"}`, facts);
80
+ if (already.length > 0)
81
+ say(` ${already.length} already in the drive, which this would not send again`);
82
+ }
83
+ return 0;
84
+ }
85
+ const json = options.json === true;
86
+ const progress = new Progress(json ? silentSink() : stderrSink(), "uploading");
87
+ const crypt = await loadCrypto();
88
+ const uploaded = [];
89
+ const reports = [];
90
+ try {
91
+ for (const batch of batchesOf(todo, (one) => planHeavyFile(one.size, rule).length)) {
92
+ const files = [];
93
+ for (const one of batch)
94
+ files.push(heavyFile(one, await folderFor(session, folderIds, one.folder)));
95
+ const ctx = { session, network, crypt, rule, settings: list.manifest?.settings, say, json, progress };
96
+ const report = await runHeavy(ctx, files, payer, options);
97
+ reports.push(report.facts);
98
+ for (const done of report.files) {
99
+ const added = await recordHeavy(session, done, asked);
100
+ uploaded.push(`${done.destination}/${added.name}`);
101
+ }
102
+ }
103
+ }
104
+ catch (error) {
105
+ progress.done();
106
+ // ⛔ WHAT IS UPLOADED IS REAL AND PAID FOR — the same words `push.ts` uses, for the same reason.
107
+ const because = error instanceof Error ? error.message : String(error);
108
+ throw new NmtsError(because, {
109
+ exitCode: error instanceof NmtsError ? error.exitCode : 1,
110
+ nextStep: uploaded.length === 0
111
+ ? error instanceof NmtsError && error.nextStep !== null
112
+ ? error.nextStep
113
+ : "Nothing was uploaded."
114
+ : `${uploaded.length} file${uploaded.length === 1 ? " is" : "s are"} uploaded and paid ` +
115
+ `for. Running the same command again sends only what is missing.`,
116
+ });
117
+ }
118
+ finally {
119
+ progress.done();
120
+ }
121
+ if (json) {
122
+ say(JSON.stringify({ files: found.length, uploaded: uploaded.length, skipped: already.length, tier: "heavy", orders: reports }));
123
+ return 0;
124
+ }
125
+ say(``);
126
+ say(`${uploaded.length} sent · ${already.length} already there`);
127
+ return 0;
128
+ }
@@ -0,0 +1,24 @@
1
+ import type { ManifestEntry } from "../shared/lib/drive/manifest-codec.ts";
2
+ /** One local file, and where it goes in the drive. */
3
+ export interface PlannedFile {
4
+ /** Absolute path on this machine. */
5
+ local: string;
6
+ /** Folder path inside the drive. */
7
+ folder: string;
8
+ name: string;
9
+ size: number;
10
+ }
11
+ /** The directory as typed: refused when it is missing or a file, then walked. */
12
+ export declare function localTree(target: string, to: string | undefined, hidden: boolean): {
13
+ root: string;
14
+ found: PlannedFile[];
15
+ };
16
+ /** Which found files the drive already holds, which to send, and the folders already known. */
17
+ export declare function splitAlready(entries: readonly ManifestEntry[], found: readonly PlannedFile[]): {
18
+ folderIds: Map<string, string | null>;
19
+ already: PlannedFile[];
20
+ todo: PlannedFile[];
21
+ };
22
+ export { walk as filesUnderDirectory };
23
+ /** Every file under a local directory, with the drive folder each one belongs in. */
24
+ declare function walk(dir: string, driveFolder: string, hidden: boolean): PlannedFile[];
@@ -0,0 +1,91 @@
1
+ // The directory side of `nmts push`: what is on this machine, and what the drive already holds.
2
+ //
3
+ // ⚠ MOVED OUT OF `push.ts` UNCHANGED (2026-09-24) so both tiers read one tree the same way — that
4
+ // file had reached the length gate the day NMTS Heavy needed the same walk and the same
5
+ // "already there" rule. The rules are the ones `push.ts` states in its header: dot-files stay
6
+ // unless asked for, symbolic links are not followed, and a name already in its folder is skipped.
7
+ import { readdirSync, statSync } from "node:fs";
8
+ import { basename, join, resolve } from "node:path";
9
+ import { normaliseName, normalisePath } from "../drive-paths.js";
10
+ import { NmtsError } from "../errors.js";
11
+ import { BINARY_NAME } from "../product.js";
12
+ /** The directory as typed: refused when it is missing or a file, then walked. */
13
+ export function localTree(target, to, hidden) {
14
+ const root = resolve(target);
15
+ let rootStat;
16
+ try {
17
+ rootStat = statSync(root);
18
+ }
19
+ catch {
20
+ throw new NmtsError(`There is nothing at ${root}.`, { exitCode: 4 });
21
+ }
22
+ if (!rootStat.isDirectory()) {
23
+ throw new NmtsError(`${root} is a file.`, {
24
+ exitCode: 4,
25
+ nextStep: `Nothing was sent. \`${BINARY_NAME} put\` uploads one file.`,
26
+ });
27
+ }
28
+ const under = normalisePath(to ?? "");
29
+ const base = under === "" ? basename(root) : `${under}/${basename(root)}`;
30
+ return { root, found: walk(root, base, hidden) };
31
+ }
32
+ /** Which found files the drive already holds, which to send, and the folders already known. */
33
+ export function splitAlready(entries, found) {
34
+ const taken = new Set(entries
35
+ .filter((e) => e.deletedAt === undefined)
36
+ .map((e) => `${e.parentId ?? ""} ${normaliseName(e.name)}`));
37
+ const folderIds = new Map();
38
+ const already = [];
39
+ const todo = [];
40
+ for (const one of found) {
41
+ const parentId = knownFolderId(entries, one.folder);
42
+ if (parentId !== undefined)
43
+ folderIds.set(one.folder, parentId);
44
+ const there = parentId !== undefined && taken.has(`${parentId ?? ""} ${normaliseName(one.name)}`);
45
+ (there ? already : todo).push(one);
46
+ }
47
+ return { folderIds, already, todo };
48
+ }
49
+ export { walk as filesUnderDirectory };
50
+ /** Every file under a local directory, with the drive folder each one belongs in. */
51
+ function walk(dir, driveFolder, hidden) {
52
+ const out = [];
53
+ const items = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
54
+ for (const item of items) {
55
+ if (!hidden && item.name.startsWith("."))
56
+ continue;
57
+ const local = join(dir, item.name);
58
+ // ⛔ SYMBOLIC LINKS ARE NOT FOLLOWED. One pointing at a parent directory would walk forever,
59
+ // and one pointing outside would upload a file nobody meant to send.
60
+ if (item.isSymbolicLink())
61
+ continue;
62
+ if (item.isDirectory()) {
63
+ out.push(...walk(local, `${driveFolder}/${item.name}`, hidden));
64
+ continue;
65
+ }
66
+ if (!item.isFile())
67
+ continue;
68
+ const size = statSync(local).size;
69
+ // An empty file has nothing to store, and the storage network would refuse the reservation.
70
+ if (size === 0)
71
+ continue;
72
+ out.push({ local, folder: driveFolder, name: item.name, size });
73
+ }
74
+ return out;
75
+ }
76
+ /** The id of a drive folder path that ALREADY exists, or undefined when it does not. */
77
+ function knownFolderId(entries, folder) {
78
+ if (folder === "")
79
+ return null;
80
+ let parentId = null;
81
+ for (const name of folder.split("/")) {
82
+ const there = entries.find((e) => e.parentId === parentId &&
83
+ e.kind === 0 &&
84
+ e.deletedAt === undefined &&
85
+ normaliseName(e.name) === normaliseName(name));
86
+ if (there === undefined)
87
+ return undefined;
88
+ parentId = there.id;
89
+ }
90
+ return parentId;
91
+ }
@@ -1,5 +1,7 @@
1
1
  import { openSession } from "../session.ts";
2
- export interface PushOptions {
2
+ import { type HeavyFlags } from "./put-payer.ts";
3
+ import { filesUnderDirectory, localTree, splitAlready, type PlannedFile } from "./push-tree.ts";
4
+ export interface PushOptions extends HeavyFlags {
3
5
  server?: string | undefined;
4
6
  network?: string | undefined;
5
7
  /** Where the tree goes in the drive. The top of the drive when absent. */
@@ -35,18 +37,7 @@ export interface PushOptions {
35
37
  */
36
38
  send?: (one: PlannedFile, parentId: string | null) => Promise<string>;
37
39
  }
38
- /** One local file, and where it goes in the drive. */
39
- export interface PlannedFile {
40
- /** Absolute path on this machine. */
41
- local: string;
42
- /** Folder path inside the drive. */
43
- folder: string;
44
- name: string;
45
- size: number;
46
- }
47
40
  export declare function push(target: string | undefined, options?: PushOptions): Promise<number>;
48
41
  /** The folder id for a drive path, made if it is not there yet. Remembered for the next file. */
49
42
  export declare function folderFor(session: Awaited<ReturnType<typeof openSession>>, known: Map<string, string | null>, folder: string): Promise<string | null>;
50
- export { walk as filesUnderDirectory };
51
- /** Every file under a local directory, with the drive folder each one belongs in. */
52
- declare function walk(dir: string, driveFolder: string, hidden: boolean): PlannedFile[];
43
+ export { filesUnderDirectory, localTree, splitAlready, type PlannedFile };
@@ -16,10 +16,7 @@
16
16
  // ⛔ NOTHING HIDDEN IS SENT. Entries whose name begins with a dot are left alone unless they are
17
17
  // asked for: a directory of source code carries credentials in exactly those files, and an
18
18
  // upload goes to a public storage network. `--hidden` includes them.
19
- import { readdirSync, statSync } from "node:fs";
20
- import { basename, join, resolve } from "node:path";
21
19
  import { DERIVED, loadCrypto } from "../crypto.js";
22
- import { normaliseName, normalisePath } from "../drive-paths.js";
23
20
  import { NmtsError } from "../errors.js";
24
21
  import { addEntry } from "../manifest-write.js";
25
22
  import { parseAsked } from "../collision.js";
@@ -38,6 +35,8 @@ import { CREDIT_BYTES, partSizeFor, planAndPrice, UPLOAD_EPOCHS } from "../uploa
38
35
  import { createBlobProtocol, readCurrentEpoch } from "../walrus-write.js";
39
36
  import { ensureFolderPath } from "../drive-edit.js";
40
37
  import { payerOf, refuseWalletOnlyOptions } from "./put.js";
38
+ import { tierOf } from "./put-payer.js";
39
+ import { filesUnderDirectory, localTree, splitAlready } from "./push-tree.js";
41
40
  export async function push(target, options = {}) {
42
41
  const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
43
42
  if (target === undefined || target === "") {
@@ -46,6 +45,8 @@ export async function push(target, options = {}) {
46
45
  nextStep: `\`${BINARY_NAME} push <directory>\` — a directory on this machine.`,
47
46
  });
48
47
  }
48
+ if (tierOf(options) === "heavy")
49
+ return (await import("./push-heavy.js")).pushHeavy(target, options);
49
50
  const payer = payerOf(options.pay);
50
51
  if (payer === "wallet")
51
52
  refuseDepositWithWallet(options.deposit);
@@ -59,23 +60,7 @@ export async function push(target, options = {}) {
59
60
  nextStep: `Nothing was sent. Leave --storage off to buy new storage for each file.`,
60
61
  });
61
62
  }
62
- const root = resolve(target);
63
- let rootStat;
64
- try {
65
- rootStat = statSync(root);
66
- }
67
- catch {
68
- throw new NmtsError(`There is nothing at ${root}.`, { exitCode: 4 });
69
- }
70
- if (!rootStat.isDirectory()) {
71
- throw new NmtsError(`${root} is a file.`, {
72
- exitCode: 4,
73
- nextStep: `Nothing was sent. \`${BINARY_NAME} put\` uploads one file.`,
74
- });
75
- }
76
- const under = normalisePath(options.to ?? "");
77
- const base = under === "" ? basename(root) : `${under}/${basename(root)}`;
78
- const found = walk(root, base, options.hidden === true);
63
+ const { root, found } = localTree(target, options.to, options.hidden === true);
79
64
  if (found.length === 0) {
80
65
  if (options.json) {
81
66
  say(JSON.stringify({ files: 0, uploaded: 0, skipped: 0, credits: 0 }));
@@ -92,20 +77,7 @@ export async function push(target, options = {}) {
92
77
  const rule = paddingRuleOf(list.manifest?.settings);
93
78
  // ⛔ WHAT IS ALREADY THERE IS DECIDED BEFORE ANYTHING IS PRICED, so the number printed is what
94
79
  // this run will actually spend rather than what a first run would have.
95
- const entries = list.manifest?.entries ?? [];
96
- const taken = new Set(entries
97
- .filter((e) => e.deletedAt === undefined)
98
- .map((e) => `${e.parentId ?? ""} ${normaliseName(e.name)}`));
99
- const folderIds = new Map();
100
- const already = [];
101
- const todo = [];
102
- for (const one of found) {
103
- const parentId = knownFolderId(entries, one.folder);
104
- if (parentId !== undefined)
105
- folderIds.set(one.folder, parentId);
106
- const there = parentId !== undefined && taken.has(`${parentId ?? ""} ${normaliseName(one.name)}`);
107
- (there ? already : todo).push(one);
108
- }
80
+ const { folderIds, already, todo } = splitAlready(list.manifest?.entries ?? [], found);
109
81
  const credits = todo.reduce((sum, one) => sum + planAndPrice(one.size, partSize, rule).credits, 0);
110
82
  const bytes = todo.reduce((sum, one) => sum + one.size, 0);
111
83
  // Per FILE, not per run: every file in the tree sets the same amount aside.
@@ -265,46 +237,4 @@ export async function folderFor(session, known, folder) {
265
237
  known.set(folder, parentId);
266
238
  return parentId;
267
239
  }
268
- /** The id of a drive folder path that ALREADY exists, or undefined when it does not. */
269
- function knownFolderId(entries, folder) {
270
- if (folder === "")
271
- return null;
272
- let parentId = null;
273
- for (const name of folder.split("/")) {
274
- const there = entries.find((e) => e.parentId === parentId &&
275
- e.kind === 0 &&
276
- e.deletedAt === undefined &&
277
- normaliseName(e.name) === normaliseName(name));
278
- if (there === undefined)
279
- return undefined;
280
- parentId = there.id;
281
- }
282
- return parentId;
283
- }
284
- export { walk as filesUnderDirectory };
285
- /** Every file under a local directory, with the drive folder each one belongs in. */
286
- function walk(dir, driveFolder, hidden) {
287
- const out = [];
288
- const items = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
289
- for (const item of items) {
290
- if (!hidden && item.name.startsWith("."))
291
- continue;
292
- const local = join(dir, item.name);
293
- // ⛔ SYMBOLIC LINKS ARE NOT FOLLOWED. One pointing at a parent directory would walk forever,
294
- // and one pointing outside would upload a file nobody meant to send.
295
- if (item.isSymbolicLink())
296
- continue;
297
- if (item.isDirectory()) {
298
- out.push(...walk(local, `${driveFolder}/${item.name}`, hidden));
299
- continue;
300
- }
301
- if (!item.isFile())
302
- continue;
303
- const size = statSync(local).size;
304
- // An empty file has nothing to store, and the storage network would refuse the reservation.
305
- if (size === 0)
306
- continue;
307
- out.push({ local, folder: driveFolder, name: item.name, size });
308
- }
309
- return out;
310
- }
240
+ export { filesUnderDirectory, localTree, splitAlready };