@pylair/cli 0.1.0-rc.16 → 0.1.0-rc.18

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 (42) hide show
  1. package/README.md +1 -1
  2. package/dist/build/bytecode.d.ts +29 -0
  3. package/dist/build/bytecode.d.ts.map +1 -0
  4. package/dist/build/bytecode.js +64 -0
  5. package/dist/build/bytecode.js.map +1 -0
  6. package/dist/build/download.d.ts +53 -0
  7. package/dist/build/download.d.ts.map +1 -0
  8. package/dist/build/download.js +326 -0
  9. package/dist/build/download.js.map +1 -0
  10. package/dist/build/notices.d.ts +10 -0
  11. package/dist/build/notices.d.ts.map +1 -0
  12. package/dist/build/notices.js +108 -0
  13. package/dist/build/notices.js.map +1 -0
  14. package/dist/build/pbs.d.ts +12 -0
  15. package/dist/build/pbs.d.ts.map +1 -0
  16. package/dist/build/pbs.js +36 -0
  17. package/dist/build/pbs.js.map +1 -0
  18. package/dist/build/python.d.ts +19 -0
  19. package/dist/build/python.d.ts.map +1 -0
  20. package/dist/build/python.js +109 -0
  21. package/dist/build/python.js.map +1 -0
  22. package/dist/build/sign.d.ts +4 -0
  23. package/dist/build/sign.d.ts.map +1 -0
  24. package/dist/build/sign.js +108 -0
  25. package/dist/build/sign.js.map +1 -0
  26. package/dist/build/source.d.ts +16 -0
  27. package/dist/build/source.d.ts.map +1 -0
  28. package/dist/build/source.js +85 -0
  29. package/dist/build/source.js.map +1 -0
  30. package/dist/build/util.d.ts +4 -0
  31. package/dist/build/util.d.ts.map +1 -0
  32. package/dist/build/util.js +12 -0
  33. package/dist/build/util.js.map +1 -0
  34. package/dist/build.d.ts +6 -77
  35. package/dist/build.d.ts.map +1 -1
  36. package/dist/build.js +34 -624
  37. package/dist/build.js.map +1 -1
  38. package/dist/cli.d.ts +5 -0
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +11 -4
  41. package/dist/cli.js.map +1 -1
  42. package/package.json +1 -1
package/dist/build.js CHANGED
@@ -3,634 +3,44 @@
3
3
  * interpreter (native wheels only — no cross-compile) → stage app
4
4
  * source → prune → tauri build → unsigned warning.
5
5
  */
6
- import { createHash } from "node:crypto";
7
- import { execFileSync, spawnSync } from "node:child_process";
8
- import { closeSync, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, writeFileSync, } from "node:fs";
9
- import { get } from "node:https";
6
+ /*
7
+ * Where each step lives. build() below calls into them; this file also
8
+ * re-exports the helpers other modules and the tests import from here.
9
+ *
10
+ * build/pbs.ts python-build-standalone release, versions, host
11
+ * triples, committed SHA-256 table, hostTriple()
12
+ * build/download.ts the interpreter download: retry, resume, progress,
13
+ * timeout, cache and SHA-256 check (ensureTarball)
14
+ * build/python.ts fetchPython (unpack CPython), uv export and
15
+ * `uv pip install` into site-packages (stageEnv)
16
+ * build/source.ts stageSource: copy the app source, refuse secrets
17
+ * build/notices.ts stageNotices: THIRD-PARTY-NOTICES for the bundle
18
+ * build/bytecode.ts compileBytecode: checked-hash pycs for the bundle
19
+ * build/sign.ts macOS ad-hoc signing of the built .app (adHocSign)
20
+ * build/util.ts isWin and run(), shared by build() and the modules
21
+ * ./prune.ts pruning the staged tree (DEFAULT_PRUNE, prune)
22
+ * ./config.ts [tool.pylair] and tauri.conf.json loading
23
+ */
24
+ import { spawnSync } from "node:child_process";
25
+ import { existsSync, rmSync } from "node:fs";
10
26
  import { arch, platform, tmpdir } from "node:os";
11
- import { basename, join, relative } from "node:path";
27
+ import { join } from "node:path";
12
28
  import { fileURLToPath } from "node:url";
13
29
  import { importRoot, loadConfig, loadTauriConfig, tauriCliEntry, windowsSigningConfigured, } from "./config.js";
14
- import { matchGlob } from "./glob.js";
15
30
  import { DEFAULT_PRUNE, prune } from "./prune.js";
16
- import { x as untar } from "tar";
17
- const PBS_TAG = "20251120";
18
- const PBS_VERSIONS = { "3.12": "3.12.12", "3.13": "3.13.9" };
19
- const HOST_TRIPLES = {
20
- "darwin:arm64": "aarch64-apple-darwin",
21
- "darwin:x64": "x86_64-apple-darwin",
22
- "win32:x64": "x86_64-pc-windows-msvc",
23
- "linux:x64": "x86_64-unknown-linux-gnu",
24
- "linux:arm64": "aarch64-unknown-linux-gnu",
25
- };
26
- const isWin = platform() === "win32";
27
- /** Expected SHA256 per asset, committed in-repo — a hash fetched from the
28
- * same release as the tarball catches corruption but not a tampered
29
- * release. Bump together with PBS_TAG/PBS_VERSIONS; verify each value
30
- * against upstream SHA256SUMS before committing.
31
- */
32
- const PBS_SHA256 = {
33
- "3.12.12-aarch64-apple-darwin": "9955ac87eff0d561e64920dc46fd8625912d2c2be4a53c66ad80125d6d9fbdb7",
34
- "3.12.12-aarch64-unknown-linux-gnu": "4c4594cb38ddf6769f11f86818a4c6617652f4994e5a962eb4f8cf0ec977a1be",
35
- "3.12.12-x86_64-apple-darwin": "1b4d8eec597ff69a3b67946f30622a6c25c6612e6d15aa431b864ebff66ac8a1",
36
- "3.12.12-x86_64-pc-windows-msvc": "70ecfaf0bfc58298db11d6389be92c29ec4ef8cd93ebb6a7e54b41d9fc056b10",
37
- "3.12.12-x86_64-unknown-linux-gnu": "8d2cd1393c1aec9d701cebeccb83d1519951f71d3ecb42d5e70c70af4db9be34",
38
- "3.13.9-aarch64-apple-darwin": "29d38bd5fbe267b37cecac990015c662796edcf51c2f5e321d59ec06a1850816",
39
- "3.13.9-aarch64-unknown-linux-gnu": "fdc5d80488b64fcef3b99f297618f68e5374c13d89e888a66abeff4967afd308",
40
- "3.13.9-x86_64-apple-darwin": "9da51afb00480a8ccd4909bd302c80d9c104d633c5e865cf37dd5e587185e125",
41
- "3.13.9-x86_64-pc-windows-msvc": "f4c22b31ddbf8d7824cbcba2d8707621c2c8fab1fb6d2c1810c2bb0304d8e9a8",
42
- "3.13.9-x86_64-unknown-linux-gnu": "1bc9a94ab2425fb6ae58e45f69cab61647759b57895649701390822d976fa923",
43
- };
44
- export function hostTriple() {
45
- const t = HOST_TRIPLES[`${platform()}:${arch()}`];
46
- if (!t)
47
- throw new Error(`no standalone CPython build for ${platform()}/${arch()}`);
48
- return t;
49
- }
50
- const DOWNLOAD_IDLE_TIMEOUT_MS = 30_000;
51
- const MAX_REDIRECTS = 5;
52
- /** Download `url` to `to`, following up to `maxRedirects` redirects and
53
- * failing after `timeoutMs` with no bytes. The body lands in `to.part`
54
- * and is renamed into place only once it is complete — a dropped
55
- * connection must never leave a partial file at the cache path (the
56
- * SHA check would then refuse every later build until it is deleted by
57
- * hand). `get` is injectable so tests need no network. */
58
- export function download(url, to, opts) {
59
- const getImpl = opts?.get ?? get;
60
- const timeoutMs = opts?.timeoutMs ?? DOWNLOAD_IDLE_TIMEOUT_MS;
61
- const maxRedirects = opts?.maxRedirects ?? MAX_REDIRECTS;
62
- const part = `${to}.part`;
63
- return new Promise((res, rej) => {
64
- let settled = false;
65
- let out;
66
- const fail = (e) => {
67
- if (settled)
68
- return;
69
- settled = true;
70
- if (out === undefined) {
71
- rmSync(part, { force: true });
72
- rej(e);
73
- return;
74
- }
75
- // The stream owns the fd. destroy() waits for in-flight writes
76
- // before closing it — closing early (closeSync) or twice lets a
77
- // reused fd number absorb the stale op: the write lands in some
78
- // other file, or the close kills it. .part is removed only once
79
- // 'close' says the fd is really gone, keeping the rejection
80
- // ordered after cleanup.
81
- const s = out;
82
- out = undefined;
83
- s.once("close", () => {
84
- rmSync(part, { force: true });
85
- rej(e);
86
- });
87
- s.destroy();
88
- };
89
- const onErr = (e) => fail(e instanceof Error ? e : new Error(String(e)));
90
- const follow = (u, redirects) => {
91
- try {
92
- if (redirects > maxRedirects)
93
- return fail(new Error(`GET ${url}: too many redirects (cap ${maxRedirects})`));
94
- const req = getImpl(u, (r) => {
95
- try {
96
- if (r.statusCode >= 300 && r.statusCode < 400 && r.headers.location) {
97
- // Location may be relative, and only https targets are
98
- // fetchable — resolve first, refuse anything else.
99
- const target = new URL(r.headers.location, u);
100
- if (target.protocol !== "https:")
101
- return fail(new Error(`GET ${u}: refusing non-https redirect to ${target.origin}`));
102
- return follow(target.href, redirects + 1);
103
- }
104
- if (r.statusCode !== 200)
105
- return fail(new Error(`GET ${u} -> ${r.statusCode}`));
106
- const want = Number(r.headers["content-length"]);
107
- let got = 0;
108
- let ended = false;
109
- r.on("data", (c) => {
110
- got += c.length;
111
- });
112
- r.on("end", () => {
113
- ended = true;
114
- });
115
- r.on("error", fail);
116
- r.on("close", () => {
117
- if (!ended)
118
- fail(new Error(`GET ${u}: connection dropped mid-body`));
119
- });
120
- // Open eagerly — <part>'s existence is synchronous, so no
121
- // deferred fs.open can land after fail()'s rmSync and recreate
122
- // the file. autoClose: false keeps fd closing on our explicit
123
- // destroy() calls only (see fail()).
124
- const stream = createWriteStream(part, {
125
- fd: openSync(part, "w"),
126
- autoClose: false,
127
- });
128
- out = stream;
129
- r.pipe(stream);
130
- stream.on("finish", () => {
131
- if (settled)
132
- return;
133
- out = undefined;
134
- stream.once("close", () => {
135
- if (!Number.isNaN(want) && got !== want)
136
- return fail(new Error(`GET ${u}: incomplete body — ${got} of ${want} bytes`));
137
- settled = true;
138
- renameSync(part, to);
139
- res();
140
- });
141
- stream.destroy();
142
- });
143
- stream.on("error", fail);
144
- }
145
- catch (e) {
146
- onErr(e);
147
- }
148
- });
149
- req.setTimeout(timeoutMs, () => req.destroy(new Error(`GET ${u}: timed out — no data for ${timeoutMs / 1000}s`)));
150
- req.on("error", fail);
151
- }
152
- catch (e) {
153
- onErr(e);
154
- }
155
- };
156
- follow(url, 0);
157
- });
158
- }
159
- const sha256File = (p) => createHash("sha256").update(readFileSync(p)).digest("hex");
160
- /** Cache + integrity for a downloaded asset: a cached file that fails
161
- * its SHA is deleted and re-downloaded ONCE — a second mismatch still
162
- * refuses, naming the cache so it is fixable by hand. `dl` injectable
163
- * for tests. */
164
- export async function ensureTarball(url, tarball, want, dl = download) {
165
- const cached = existsSync(tarball);
166
- if (!cached) {
167
- console.log(`fetching ${basename(tarball)}`);
168
- await dl(url, tarball);
169
- }
170
- else {
171
- console.log(`using cached ${basename(tarball)}`);
172
- }
173
- if (sha256File(tarball) === want)
174
- return;
175
- if (!cached)
176
- throw new Error(`SHA256 mismatch for ${basename(tarball)}: got ${sha256File(tarball)}, ` +
177
- `want ${want} — refusing to bundle`);
178
- // A cached-but-corrupt file is the dropped-partial failure mode: one
179
- // retry, then refuse.
180
- console.warn(`cached ${basename(tarball)} failed its SHA256 — ` +
181
- `deleting ${tarball} and re-downloading once`);
182
- rmSync(tarball, { force: true });
183
- await dl(url, tarball);
184
- const got = sha256File(tarball);
185
- if (got !== want)
186
- throw new Error(`SHA256 mismatch for ${basename(tarball)} after re-download: got ${got}, ` +
187
- `want ${want} — refusing to bundle (cache file: ${tarball})`);
188
- }
189
- async function fetchPython(resources, cacheDir, versionClass) {
190
- const ver = PBS_VERSIONS[versionClass];
191
- if (!ver)
192
- throw new Error(`python-version "${versionClass}" not available — supported: ${Object.keys(PBS_VERSIONS).join(", ")}`);
193
- const triple = hostTriple();
194
- const asset = `cpython-${ver}+${PBS_TAG}-${triple}-install_only_stripped.tar.gz`;
195
- const base = `https://github.com/astral-sh/python-build-standalone/releases/download/${PBS_TAG}`;
196
- mkdirSync(resources, { recursive: true });
197
- mkdirSync(cacheDir, { recursive: true });
198
- const tarball = join(cacheDir, asset);
199
- // The interpreter ships to end users — verify against hashes committed
200
- // in-repo (see PBS_SHA256), not a checksum file from the same release.
201
- const want = PBS_SHA256[`${ver}-${triple}`];
202
- if (!want)
203
- throw new Error(`no committed SHA256 for ${ver}/${triple}`);
204
- await ensureTarball(`${base}/${asset}`, tarball, want);
205
- const dest = join(resources, "python");
206
- rmSync(dest, { recursive: true, force: true });
207
- mkdirSync(dest, { recursive: true });
208
- // Extract in-process — same lesson as the tomllib probe: whichever
209
- // `tar` PATH resolves to can differ (System32 bsdtar vs Git Bash GNU
210
- // tar, which dies on drive-letter paths). The `tar` package handles
211
- // pax long names (>100 chars) and the bin/python3 -> python3.12
212
- // symlinks the POSIX builds carry.
213
- await untar({ file: tarball, cwd: dest, strip: 1 });
214
- const py = join(dest, isWin ? "python.exe" : "bin/python3");
215
- if (!existsSync(py))
216
- throw new Error(`expected interpreter at ${py}`);
217
- return py;
218
- }
219
- /** uv export args: the lock's production set only. --no-emit-project
220
- * drops the scaffold's own project entry — its source is staged by
221
- * stageSource(), not installed as a package. */
222
- export function uvExportArgs(exported) {
223
- return [
224
- "export",
225
- "--frozen",
226
- "--format",
227
- "requirements-txt",
228
- "--no-dev",
229
- "--no-emit-project",
230
- "-o",
231
- exported,
232
- ];
233
- }
234
- /** True when a requirements file carries any `--hash` entries.
235
- * `\s` before `--hash` excludes a trailing comment mention. */
236
- export function requirementsHaveHashes(reqsText) {
237
- return /\s--hash=/.test(reqsText);
238
- }
239
- /** `uv pip install` args. `--require-hashes` is passed ONLY for the
240
- * requirements.txt fallback: an exported lock legitimately mixes hashed
241
- * registry deps with hash-less `file://` path deps, which the flag
242
- * would reject — and individual `--hash` entries are verified without
243
- * it anyway. */
244
- export function uvPipInstallArgs(python, target, reqsFile, requireHashes) {
245
- const args = [
246
- "pip",
247
- "install",
248
- "--python",
249
- python,
250
- "--target",
251
- target,
252
- "-r",
253
- reqsFile,
254
- ];
255
- if (requireHashes)
256
- args.push("--require-hashes");
257
- return args;
258
- }
259
- function stageEnv(resources, python, appDir, reqs, cacheDir) {
260
- const target = join(resources, "site-packages");
261
- rmSync(target, { recursive: true, force: true });
262
- // dev uses `uv sync` (uv.lock) — build must install the SAME locked set,
263
- // hashed, or dev/prod parity is a fiction. requirements.txt is the
264
- // fallback for projects that don't lock.
265
- const lock = join(appDir, "uv.lock");
266
- let reqsFile = reqs;
267
- let requireHashes = false;
268
- if (existsSync(lock)) {
269
- const exported = join(cacheDir, "requirements.exported.txt");
270
- execFileSync("uv", uvExportArgs(exported), {
271
- cwd: appDir,
272
- stdio: "inherit",
273
- });
274
- reqsFile = exported;
275
- }
276
- else if (!existsSync(reqs)) {
277
- console.log(`no uv.lock and no ${reqs} — bundling stdlib only`);
278
- return;
279
- }
280
- else {
281
- console.warn("warning: no uv.lock — building from requirements.txt; " +
282
- "the bundled env may drift from `pylair dev`'s env");
283
- requireHashes = requirementsHaveHashes(readFileSync(reqs, "utf-8"));
284
- }
285
- execFileSync("uv", uvPipInstallArgs(python, target, reqsFile, requireHashes), { cwd: appDir, stdio: "inherit" });
286
- }
287
- function run(cmd, args, cwd) {
288
- const r = spawnSync(cmd, args, { cwd, stdio: "inherit" });
289
- if (r.error)
290
- throw new Error(`${cmd} ${args.join(" ")} failed to start: ${r.error.message}`);
291
- if (r.status !== 0)
292
- throw new Error(`${cmd} ${args.join(" ")} exited ${r.status}`);
293
- }
294
- /** pyc invalidation mode shipped in installers — see docs/build.md.
295
- * checked-hash: installers rewrite mtimes, so timestamp pycs silently
296
- * invalidate; hash-based headers survive repackaging. checked (not
297
- * unchecked) re-validates the source hash per import — ~10ms slower on
298
- * a numpy-sized tree but a post-install source edit recompiles instead
299
- * of running stale bytecode. Measured (Windows, numpy tree):
300
- * ~665ms no-pyc / ~267ms checked / ~256ms unchecked per cold import.
301
- */
302
- export const PYC_INVALIDATION_MODE = "checked-hash";
303
- /** Precompile the staged .py tree with the BUNDLED interpreter — same
304
- * CPython and magic number as the runtime that will load the pycs.
305
- * An installed app (possibly read-only) must not compile its Python on
306
- * every launch. Runs post-prune so denied dirs stay uncompiled, and
307
- * relative args + cwd keep co_filename bundle-relative: identical pycs
308
- * regardless of build path, tracebacks show `site-packages/…`.
309
- * `-s`/`-d` would also work; relative args are the smallest version of
310
- * the same thing.
311
- *
312
- * Exit 1 from compileall means "some files failed to compile" — a
313
- * dependency may ship a py2-only file or invalid fixture that nothing
314
- * imports. That warns (paths returned) instead of failing the build;
315
- * the files are left uncompiled and will compile — or fail to import —
316
- * as normal at runtime. Real failures still throw: the interpreter
317
- * not starting, a signal, or any other exit code. Returns the failed
318
- * paths (empty on full success). */
319
- export function compileBytecode(resources, python, dirs) {
320
- const existing = dirs.filter((d) => existsSync(join(resources, d)));
321
- if (!existing.length)
322
- return [];
323
- const r = spawnSync(python, [
324
- "-m",
325
- "compileall",
326
- "-q",
327
- "-f",
328
- "-j",
329
- "0",
330
- "--invalidation-mode",
331
- PYC_INVALIDATION_MODE,
332
- ...existing,
333
- ], { cwd: resources, encoding: "utf-8" });
334
- if (r.error)
335
- throw new Error(`${python} -m compileall failed to start: ${r.error.message}`);
336
- if (r.signal || (r.status !== 0 && r.status !== 1)) {
337
- throw new Error(`${python} -m compileall ${r.signal ? `died on ${r.signal}` : `exited ${r.status}`}`);
338
- }
339
- if (r.status === 0)
340
- return [];
341
- // Quiet mode still prints `*** Error compiling '<path>'...` per file.
342
- const failed = [
343
- ...String(r.stderr).matchAll(/^\*\*\* Error compiling '([^']+)'/gm),
344
- ...String(r.stdout).matchAll(/^\*\*\* Error compiling '([^']+)'/gm),
345
- ].map((m) => m[1].replace(/\\\\/g, "\\")); // repr-escaped on Windows
346
- const shown = failed.slice(0, 10).join("\n ");
347
- console.warn(`warning: ${failed.length} file(s) failed to byte-compile and are left` +
348
- ` uncompiled — they will compile (or fail to import) as normal at` +
349
- ` runtime:\n ${shown}${failed.length > 10 ? `\n …and ${failed.length - 10} more` : ""}`);
350
- return failed;
351
- }
352
- // ── macOS ad-hoc signing ──────────────────────────────────────────────
353
- // Mach-O magic numbers, read as the first BE u32 — includes the
354
- // byte-swapped forms and both fat headers.
355
- const MACHO_MAGIC = new Set([
356
- 0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe,
357
- 0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca,
358
- ]);
359
- function isMachO(p) {
360
- const fd = openSync(p, "r");
361
- try {
362
- const b = Buffer.alloc(4);
363
- return readSync(fd, b, 0, 4, 0) === 4 && MACHO_MAGIC.has(b.readUInt32BE(0));
364
- }
365
- finally {
366
- closeSync(fd);
367
- }
368
- }
369
- /** Re-sign a built .app ad-hoc and REQUIRE it to verify. With no signing
370
- * identity Tauri ships only the linker's ad-hoc stub on the main binary —
371
- * a signature that doesn't cover the bundle is the worst state for
372
- * Gatekeeper ("is damaged"), worse than none at all. Signs every Mach-O
373
- * nested-first rather than `codesign --deep`, which is documented to miss
374
- * binaries in layouts it doesn't model — a vendored CPython tree is
375
- * exactly that. Verify with --deep --strict; if it fails, the build
376
- * fails — a broken signature must not ship silently.
377
- */
378
- function codesignVerify(path) {
379
- const v = spawnSync("codesign", ["--verify", "--deep", "--strict", path], {
380
- encoding: "utf-8",
381
- });
382
- return v.status === 0 ? null : (v.stderr ?? "").trim();
383
- }
384
- function adHocSign(tauriDir, productName) {
385
- const bundleDir = join(tauriDir, "target", "release", "bundle", "macos");
386
- if (!existsSync(bundleDir))
387
- return; // --bundles skipped app — nothing to sign
388
- const app = readdirSync(bundleDir).find((n) => n.endsWith(".app"));
389
- if (!app)
390
- return;
391
- const appPath = join(bundleDir, app);
392
- const machos = [];
393
- const walk = (dir) => {
394
- for (const e of readdirSync(dir, { withFileTypes: true })) {
395
- const p = join(dir, e.name);
396
- // Dirent types describe the link, not the target — symlinked files
397
- // and dirs are skipped; the real binary is signed in place.
398
- if (e.isDirectory())
399
- walk(p);
400
- else if (e.isFile() && isMachO(p))
401
- machos.push(p);
402
- }
403
- };
404
- walk(appPath);
405
- // Deepest first — a parent's signature seals its children, so children
406
- // must be final when the parent is written.
407
- machos.sort((a, b) => b.split("/").length - a.split("/").length);
408
- for (const p of machos)
409
- run("codesign", ["--force", "--sign", "-", p], appPath);
410
- run("codesign", ["--force", "--sign", "-", appPath], bundleDir);
411
- const err = codesignVerify(appPath);
412
- if (err)
413
- throw new Error(`ad-hoc signing produced an invalid bundle:\n${err}`);
414
- console.log(`ad-hoc signed ${app} — ${machos.length} nested binaries, codesign --verify clean`);
415
- // A dmg built in the same `tauri build` already captured the
416
- // PRE-signing .app — signing after bundling can't reach inside a
417
- // compressed image. Repackage each dmg from the signed app and verify
418
- // the shipped artifact itself, not just the staged copy. The rebuilt
419
- // image is plain (app + /Applications link) — Tauri's cosmetic layout
420
- // returns once real signing is configured and repackaging stops.
421
- const dmgDir = join(tauriDir, "target", "release", "bundle", "dmg");
422
- if (!existsSync(dmgDir))
423
- return;
424
- for (const dmg of readdirSync(dmgDir).filter((n) => n.endsWith(".dmg"))) {
425
- const dmgPath = join(dmgDir, dmg);
426
- const staging = mkdtempSync(join(tmpdir(), "pylair-dmg-"));
427
- try {
428
- run("ditto", [appPath, join(staging, app)], tauriDir);
429
- run("ln", ["-s", "/Applications", join(staging, "Applications")], tauriDir);
430
- run("hdiutil", ["create", "-volname", productName, "-srcfolder", staging, "-ov", "-format", "UDZO", dmgPath], tauriDir);
431
- }
432
- finally {
433
- rmSync(staging, { recursive: true, force: true });
434
- }
435
- // Verify the app INSIDE the shipped dmg — mount read-only at a fixed
436
- // point, verify, always detach, then judge.
437
- const mount = mkdtempSync(join(tmpdir(), "pylair-mnt-"));
438
- run("hdiutil", ["attach", "-nobrowse", "-readonly", "-mountpoint", mount, dmgPath], tauriDir);
439
- let inDmg = null;
440
- try {
441
- inDmg = codesignVerify(join(mount, app));
442
- }
443
- finally {
444
- spawnSync("hdiutil", ["detach", mount, "-quiet"], { stdio: "inherit" });
445
- rmSync(mount, { recursive: true, force: true });
446
- }
447
- if (inDmg)
448
- throw new Error(`${dmg} contains an invalidly-signed app:\n${inDmg}`);
449
- console.log(`repackaged ${dmg} with the signed app — verified inside the image`);
450
- }
451
- }
452
- /** Shipped bundles must carry the licenses of what they embed. Collects:
453
- * pylair's own dual license, the interpreter's license tree (PSF license
454
- * requires LICENSE text with redistributed CPython), and each wheel's
455
- * dist-info license files. Runs before prune so nothing collected is
456
- * deleted afterwards. Returns the notice dir.
457
- */
458
- export function stageNotices(resources, pylairDir) {
459
- const out = join(resources, "THIRD-PARTY-NOTICES");
460
- rmSync(out, { recursive: true, force: true });
461
- mkdirSync(out, { recursive: true });
462
- const index = [];
463
- const copyInto = (subdir, src, dest) => {
464
- mkdirSync(join(out, subdir), { recursive: true });
465
- cpSync(src, join(out, subdir, dest));
466
- };
467
- const LICENSEISH = /^(licen[cs]e|copying|notice|authors|copyright)/i;
468
- for (const f of ["LICENSE-MIT", "LICENSE-APACHE"]) {
469
- const src = join(pylairDir, f);
470
- if (existsSync(src))
471
- copyInto("pylair", src, f);
472
- }
473
- index.push("pylair/ — pylair itself (MIT OR Apache-2.0)");
474
- // The interpreter: python-build-standalone ships a licenses/ dir holding
475
- // CPython's license plus every statically-linked dep (OpenSSL, libffi…).
476
- const pyRoot = join(resources, "python");
477
- let found = 0;
478
- const walkPy = (dir) => {
479
- for (const e of readdirSync(dir, { withFileTypes: true })) {
480
- const p = join(dir, e.name);
481
- if (e.isDirectory()) {
482
- if (e.name.toLowerCase() === "licenses") {
483
- cpSync(p, join(out, "python", "licenses"), { recursive: true });
484
- found++;
485
- }
486
- else
487
- walkPy(p);
488
- }
489
- else if (LICENSEISH.test(e.name)) {
490
- copyInto("python", p, e.name);
491
- found++;
492
- }
493
- }
494
- };
495
- if (existsSync(pyRoot))
496
- walkPy(pyRoot);
497
- if (!found) {
498
- mkdirSync(join(out, "python"), { recursive: true });
499
- writeFileSync(join(out, "python", "NOTICE.txt"), "This app bundles CPython (PSF-2.0 license) via python-build-standalone.\n" +
500
- "License texts were not located in the interpreter tree at build time;\n" +
501
- "they ship upstream in the python/licenses directory of each\n" +
502
- "python-build-standalone release.\n");
503
- console.warn("warning: no license files found under resources/python — wrote placeholder NOTICE");
504
- }
505
- index.push("python/ — bundled CPython interpreter (PSF-2.0) and its vendored deps");
506
- // Wheels: every installed dist-info/egg-info carries license files or
507
- // license metadata. Copy whichever exists.
508
- const sp = join(resources, "site-packages");
509
- let wheels = 0;
510
- if (existsSync(sp)) {
511
- for (const e of readdirSync(sp, { withFileTypes: true })) {
512
- if (!e.isDirectory())
513
- continue;
514
- const m = /^(.*?)-[\d.]+.*\.(dist-info|egg-info)$/.exec(e.name);
515
- if (!m)
516
- continue;
517
- const pkg = m[1].replace(/[^\w.-]/g, "_");
518
- const d = join(sp, e.name);
519
- let kept = false;
520
- for (const f of readdirSync(d, { withFileTypes: true })) {
521
- if (f.isDirectory() && f.name.toLowerCase() === "licenses") {
522
- cpSync(join(d, f.name), join(out, pkg, "licenses"), { recursive: true });
523
- kept = true;
524
- }
525
- else if (f.isFile() && LICENSEISH.test(f.name)) {
526
- copyInto(pkg, join(d, f.name), f.name);
527
- kept = true;
528
- }
529
- }
530
- const meta = join(d, "METADATA");
531
- if (existsSync(meta)) {
532
- const lines = readFileSync(meta, "utf-8")
533
- .split("\n")
534
- .filter((l) => /^(License|Classifier: License)/i.test(l));
535
- // Copyleft is legal to ship but app authors deserve to know they
536
- // bundled it — warn, never block.
537
- if (/\b(a?lgpl|gpl)[ -]?v?\d/i.test(lines.join(" ")))
538
- console.warn(`warning: bundled wheel ${e.name} declares a copyleft license`);
539
- if (lines.length) {
540
- mkdirSync(join(out, pkg), { recursive: true });
541
- writeFileSync(join(out, pkg, "METADATA-LICENSE.txt"), lines.join("\n") + "\n");
542
- kept = true;
543
- }
544
- }
545
- if (kept) {
546
- wheels++;
547
- index.push(`${pkg}/ — from ${e.name}`);
548
- }
549
- }
550
- }
551
- writeFileSync(join(out, "INDEX.txt"), index.join("\n") + "\n");
552
- console.log(`third-party notices: pylair, python interpreter, ${wheels} wheel(s)`);
553
- return out;
554
- }
555
- /** Basename globs for files that look like secrets or credentials —
556
- * staged source must never carry them into an installer. */
557
- const SECRET_PATTERNS = [
558
- "*.pem",
559
- "*.key",
560
- "*.p12",
561
- "*.pfx",
562
- "id_rsa*",
563
- "id_ed25519*",
564
- "credentials*.json",
565
- "service-account*.json",
566
- ];
567
- /** True when a `/`-separated relative path looks like it holds secrets:
568
- * any dot-segment (.env, .git, .venv, .DS_Store) or a basename matching
569
- * the credential patterns. */
570
- function secretish(rel) {
571
- const segs = rel.split("/");
572
- if (segs.some((s) => s.startsWith(".")))
573
- return true;
574
- return SECRET_PATTERNS.some((g) => matchGlob(g, segs[segs.length - 1]));
575
- }
576
- /** Could `pattern` match something beneath `dir`? Refusing a denied dir
577
- * would otherwise hide an included descendant from cpSync's walk. */
578
- function couldMatchUnder(pattern, dir) {
579
- const d = dir.split("/");
580
- const p = pattern.split("/");
581
- for (let i = 0; i < d.length; i++) {
582
- if (i >= p.length)
583
- return false; // pattern ends above the dir
584
- if (p[i] === "**")
585
- return true; // ** crosses any depth
586
- if (/[*?]/.test(p[i])) {
587
- if (!matchGlob(p[i], d[i]))
588
- return false;
589
- }
590
- else if (p[i] !== d[i])
591
- return false;
592
- }
593
- return true;
594
- }
595
- /**
596
- * Copy the app source tree into the bundle, minus anything that looks
597
- * like a secret. A path is skipped when any segment starts with "." or
598
- * its basename matches SECRET_PATTERNS, UNLESS an `include` glob
599
- * (relative to srcDir, same shape as `prune` entries) names it — an
600
- * include wins even inside a denied directory, which stays walkable so
601
- * the descent can reach it. Skips are reported, not fatal: `warn` gets
602
- * the count, the first 10 names, and how to opt a path back in; nothing
603
- * is printed when nothing was skipped.
604
- *
605
- * Returns the `/`-separated relative paths that were refused.
606
- */
607
- export function stageSource(srcDir, dest, include = [], warn = console.warn) {
608
- const pats = include.map((g) => g.replace(/\\/g, "/").replace(/^\.\//, ""));
609
- const skipped = [];
610
- cpSync(srcDir, dest, {
611
- recursive: true,
612
- filter: (src) => {
613
- const rel = relative(srcDir, src).replace(/\\/g, "/");
614
- if (!rel)
615
- return true; // the root itself
616
- if (pats.some((g) => matchGlob(g, rel)))
617
- return true;
618
- if (!secretish(rel))
619
- return true;
620
- if (pats.some((g) => couldMatchUnder(g, rel)))
621
- return true; // descend only
622
- skipped.push(rel);
623
- return false;
624
- },
625
- });
626
- if (skipped.length) {
627
- warn(`warning: skipped ${skipped.length} secret-looking path(s) under ${srcDir}: ` +
628
- skipped.slice(0, 10).join(", ") +
629
- (skipped.length > 10 ? ", …" : ""));
630
- warn(` to ship one deliberately, list it in [tool.pylair] include = ["path/under/source"]`);
631
- }
632
- return skipped;
633
- }
31
+ import { compileBytecode } from "./build/bytecode.js";
32
+ import { stageNotices } from "./build/notices.js";
33
+ import { hostTriple } from "./build/pbs.js";
34
+ import { fetchPython, stageEnv } from "./build/python.js";
35
+ import { adHocSign } from "./build/sign.js";
36
+ import { stageSource } from "./build/source.js";
37
+ import { isWin, run } from "./build/util.js";
38
+ export { compileBytecode, PYC_INVALIDATION_MODE } from "./build/bytecode.js";
39
+ export { DownloadError, backoffMs, download, downloadTimeoutMs, downloadWithRetry, ensureTarball, } from "./build/download.js";
40
+ export { stageNotices } from "./build/notices.js";
41
+ export { hostTriple } from "./build/pbs.js";
42
+ export { stageSource } from "./build/source.js";
43
+ export { requirementsHaveHashes, uvExportArgs, uvPipInstallArgs } from "./build/python.js";
634
44
  export async function build(opts) {
635
45
  const { appDir } = opts;
636
46
  const tauriDir = join(appDir, "src-tauri");