@pipelex/create-method-app 0.71.0 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,36 +5,37 @@ Start an app that runs an [MTHDS](https://mthds.ai) method through the [Pipelex]
5
5
  ```bash
6
6
  export PIPELEX_API_KEY=… # from app.pipelex.com
7
7
  npm create @pipelex/method-app@latest my-app -- --method ./receipt_review.mthds
8
- make -C my-app serve
8
+ cd my-app
9
+ npm run serve
9
10
  ```
10
11
 
11
- The first command writes the [`webapp-js`](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps/webapp-js) template of the [method-app family](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps), the `method-apps/` directory of `Pipelex/pipelex-sdk`, into `my-app/`, commits it as it came, and runs the copy's own `make create`, which scaffolds the method, names the project after it and runs `make all`. The second starts the dev server in the background, proves that the page answers, and prints its URL; `make stop` stops it. `make dev` runs the same server in the foreground instead.
12
+ The first command writes the [`webapp-js`](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps/webapp-js) template of the [method-app family](https://github.com/Pipelex/pipelex-sdk/tree/main/method-apps), the `method-apps/` directory of `Pipelex/pipelex-sdk`, into `my-app/`, commits it as it came, and runs the copy's own `npm run create`, after the `npm install` it needs, which scaffolds the method, names the project after it and runs `npm run all`. The second starts the dev server in the background, proves that the page answers, and prints its URL; `npm run serve -- stop` stops it. `npm run dev` runs the same server in the foreground instead. None of it needs `make` or a POSIX shell, so the same commands run on macOS, Linux and Windows, in PowerShell and `cmd` as in any POSIX shell.
12
13
 
13
14
  `--method` takes a `.mthds` file or a directory of them, a method id from your organization's catalog (`mt_…`, or `mt_…@<version>` and `mt_…@draft` to pin a version or run the draft), or a published package address (`github.com/Pipelex/methods/text_stats@v0.2.0`). A path is read from where you typed the command.
14
15
 
15
16
  ## What it needs
16
17
 
17
- - **Node.js** at or above the template's floor (22.13 for `webapp-js`), `make`, and `git` unless you pass `--no-git`.
18
- - **`PIPELEX_API_KEY`** in the environment, since a fresh copy has no `.env.local` for `make create` to read it from. `make create` runs with it and never copies it into the project: the project's `.env.local` gets an empty `PIPELEX_API_KEY` line, where you put your own key before `make dev`. The initializer only checks that it is set, and never prints it.
18
+ - **Node.js** at or above the template's floor (22.13 for `webapp-js`) with its npm, and `git` unless you pass `--no-git`. The initializer runs npm itself, the one that ran it under `npm create`, or, on Windows, the one the Node installer puts beside `node.exe`; `make` is not needed.
19
+ - **A key**: `PIPELEX_API_KEY` in the environment, or else the one the Pipelex login saved. A fresh copy has no `.env.local` or `.env` for `npm run create` to read it from, so these are the two sources. The login, `npx -y @pipelex/mcp@latest login` (`npx.cmd` on Windows, which Windows PowerShell 5.1 runs whatever its execution policy), saves the key as `PIPELEX_API_KEY` in `~/.pipelex/.env`, or in the `.env` of the directory `PIPELEX_HOME` names, and the Pipelex plugin's tools read the same file, so one login serves both, including in an app such as Claude's desktop app, where a variable set in a terminal window never reaches the agent. The file is read only when the environment holds no key; `PIPELEX_HOME` must be absolute or start with `~/`, and a relative one is refused rather than read. `npm run create` runs with the key and never copies it into the project: the project's `.env.local` gets an empty `PIPELEX_API_KEY` line, where you put your own key before `npm run dev`, since the app itself does not read the login's file. When the login's key is the one it ran with, `npm run create` says so in a warning the initializer repeats at the end, so put your key in `.env.local`, or start `npm run serve` from a shell that exports it, before running a method. The initializer only checks that a key is there, and never prints it; when there is none, `refused: no-key` names the login first, with the file it looked in. `npm run create` reads the login's file again itself under the same rules, which both suites hold to one table of cases, the family's `initializers/login-key.json`.
19
20
  - **A directory that is missing, empty, or holds only `.git`.** Anything else, `.DS_Store` included, is refused, and nothing is written.
20
21
 
21
22
  The package has no dependency. It carries the template inside it, packed from the family's repository at the commit it was published from, so `@X.Y.Z` writes exactly the X.Y.Z template and nothing is fetched from GitHub.
22
23
 
23
24
  ## Options
24
25
 
25
- | Option | What it does |
26
- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
- | `--method <m>` | The method the app runs. Required unless `--no-create`. |
28
- | `--name`, `--title`, `--description` | The project's package name, title and description, which `make create` otherwise derives from the method. |
29
- | `--pipe`, `--method-name`, `--label` | The pipe to run, the method's directory name and its tab label, when the method does not settle them. |
30
- | `--author-name`, `--author-email`, `--repo-url`, `--license`, `--license-holder`, `--license-year` | What the project says about who made it. Nothing is invented. |
31
- | `--dry-run` | `make create` plans and prints the identity without changing a file. The copy and its commit stand, and the verdict names the real `make create` to run. |
32
- | `--no-create` | Write the template and commit it, then stop. The verdict names the `make create` to run, after writing `.env.local` yourself, for instance. |
33
- | `--no-git` | Make no repository and no commit. |
34
- | `--quiet` | Write `make create`'s output to a log and print its path, so the summary stays in view. |
35
- | `--template <name>` | The template to write. `webapp-js` is the default and the only one. |
26
+ | Option | What it does |
27
+ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
28
+ | `--method <m>` | The method the app runs. Required unless `--no-create`. |
29
+ | `--name`, `--title`, `--description` | The project's package name, title and description, which `npm run create` otherwise derives from the method. |
30
+ | `--pipe`, `--method-name`, `--label` | The pipe to run, the method's directory name and its tab label, when the method does not settle them. |
31
+ | `--author-name`, `--author-email`, `--repo-url`, `--license`, `--license-holder`, `--license-year` | What the project says about who made it. Nothing is invented. |
32
+ | `--dry-run` | `npm run create` plans and prints the identity without changing a file. The copy and its commit stand, and the verdict names the real `npm run create` to run. |
33
+ | `--no-create` | Write the template and commit it, then stop. The verdict names the `npm install` and `npm run create` to run, after writing `.env.local` yourself, for instance. |
34
+ | `--no-git` | Make no repository and no commit. |
35
+ | `--quiet` | Write the output of `npm install` and `npm run create` to a log and print its path, so the summary stays in view. |
36
+ | `--template <name>` | The template to write. `webapp-js` is the default and the only one. |
36
37
 
37
- Each create option is named after the `make create` variable it sets (`--author-email` is `AUTHOR_EMAIL`), and reaches `make create` as one argument, so no value needs quoting beyond what your shell needs. A blank value is not passed on. Nothing is ever asked: a missing value is a refusal naming the option.
38
+ Each create option is named after the variable of the family's create contract it sets (`--author-email` is `AUTHOR_EMAIL`), which is also the flag of the template's own `npm run create`, and reaches it as one argument, `--method` as the first, so no value needs quoting beyond what your shell needs. A blank value is not passed on. Nothing is ever asked: a missing value is a refusal naming the option.
38
39
 
39
40
  ## Git
40
41
 
@@ -54,27 +55,27 @@ A path the enclosing repository ignores, such as a `tmp/` its `.gitignore` lists
54
55
 
55
56
  A commit needs a git identity, and a missing one is refused before anything is written. When git shows none outside a repository, the initializer asks again inside a throwaway repository at the destination, which it removes before going on, so an identity given only by an `includeIf "gitdir:…"` section is found. At a path another repository ignores, it always asks inside that throwaway repository, since an identity set in the enclosing repository's own configuration does not reach the new one.
56
57
 
57
- The pristine commit reads `Start from Pipelex/pipelex-sdk/method-apps/webapp-js <version> (<sha>)`, so `make create`'s changes are a diff you can read before committing them. `make create` itself commits nothing.
58
+ The pristine commit reads `Start from Pipelex/pipelex-sdk/method-apps/webapp-js <version> (<sha>)`, so `npm run create`'s changes are a diff you can read before committing them. `npm run create` itself commits nothing.
58
59
 
59
60
  ## What it prints
60
61
 
61
62
  A run ends with one verdict line, the last line it prints on standard output, whose first word is stable:
62
63
 
63
- | Verdict | Meaning |
64
- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
65
- | `created <dir>; next: cd <dir> && make serve` | The copy, the git outcome, and a green `make create` |
66
- | `copied <dir>; next: …` | With `--no-create` or `--dry-run`: the copy and the git outcome, and the `make create` to run next |
67
- | `refused: not-empty` | The destination holds something other than a lone `.git`; nothing was written |
68
- | `refused: unusable-destination` | The destination cannot be read: a file stands where a directory of its path should be, or a directory on it cannot be read; nothing was written |
69
- | `refused: repository-has-history`, `refused: repository-has-staged-files`, `refused: inside-template-checkout` | The git reading above; nothing was written |
70
- | `refused: no-method`, `no-key`, `missing-tool`, `node-too-old`, `no-git-identity`, `unknown-option`, `unknown-template`, `other-ecosystem`, `usage` | The preflight; nothing was written, and the line names the fix |
71
- | `failed: write` | The copy failed or was interrupted, and everything the initializer had created was removed; nothing else was touched |
72
- | `failed: commit` | Git refused the pristine commit, for instance through a global hook; the copy stands, and the line says how to commit it and what to run next |
73
- | `failed: create` | `make create` did not succeed; the copy and its commit stand, and `make create`'s own message says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot |
74
-
75
- Before the verdict come the warnings `make create` printed, each once, and the git outcome. The exit code is 0 for `created` and `copied` and 1 otherwise, but the verdict is the line to read.
76
-
77
- Everything the initializer prints goes to standard output, `make create`'s output included when `--quiet` is not given. Under `npm create`, a run that exits 1 is followed by npm's own `npm error` lines on standard error, so read the verdict from standard output rather than from the last line of everything printed. `npm create --loglevel=silent @pipelex/method-app@latest …` removes npm's lines and leaves the initializer's alone.
64
+ | Verdict | Meaning |
65
+ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
66
+ | ``created <dir>; next: `cd <dir>`, then `npm run serve` `` | The copy, the git outcome, and a green `npm run create` |
67
+ | `copied <dir>; next: …` | With `--no-create` or `--dry-run`: the copy and the git outcome, and the `npm run create` to run next, after `npm install` when it has not run |
68
+ | `refused: not-empty` | The destination holds something other than a lone `.git`; nothing was written |
69
+ | `refused: unusable-destination` | The destination cannot be read: a file stands where a directory of its path should be, or a directory on it cannot be read; nothing was written |
70
+ | `refused: repository-has-history`, `refused: repository-has-staged-files`, `refused: inside-template-checkout` | The git reading above; nothing was written |
71
+ | `refused: no-method`, `no-key`, `missing-tool`, `node-too-old`, `no-git-identity`, `unknown-option`, `unknown-template`, `other-ecosystem`, `usage` | The preflight; nothing was written, and the line names the fix |
72
+ | `failed: write` | The copy failed or was interrupted, and everything the initializer had created was removed; nothing else was touched |
73
+ | `failed: commit` | Git refused the pristine commit, for instance through a global hook; the copy stands, and the line says how to commit it and what to run next |
74
+ | `failed: create` | `npm install` or `npm run create` did not succeed; the copy and its commit stand. After a failed install, the line names both commands to run once npm's message is dealt with; after a failed `npm run create`, its own message says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot |
75
+
76
+ Before the verdict come the warnings `npm run create` printed, each once, and the git outcome. A `next:` names its commands one after the other, each between backquotes, to run in turn: no separator reads the same in every shell, since Windows PowerShell 5.1 has no `&&` and `cmd` no `;`. Each word is quoted for the system the initializer ran on: in single quotes for a POSIX shell, and on Windows in double quotes, which PowerShell and `cmd` both read, or in PowerShell's single quotes for a word holding a `$` or a backquote. The exit code is 0 for `created` and `copied` and 1 otherwise, but the verdict is the line to read.
77
+
78
+ Everything the initializer prints goes to standard output, npm's output included when `--quiet` is not given. Under `npm create`, a run that exits 1 is followed by npm's own `npm error` lines on standard error, so read the verdict from standard output rather than from the last line of everything printed. `npm create --loglevel=silent @pipelex/method-app@latest …` removes npm's lines and leaves the initializer's alone.
78
79
 
79
80
  A Python template, such as `cli-python`, is refused with `refused: other-ecosystem`. No initializer serves the Python templates yet, so the line points at the template's README, which shows how to copy it out of a release of `Pipelex/pipelex-sdk` and run its `make create`.
80
81
 
package/lib/git.mjs CHANGED
@@ -280,7 +280,7 @@ export function commitPristine({ dest, init, paths, message, env }) {
280
280
 
281
281
  /**
282
282
  * The commands a person runs to make the pristine commit by hand, once the
283
- * copy stands, joined with `&&` for a shell. `quote` quotes one word.
283
+ * copy stands, in order. `quote` quotes one word.
284
284
  */
285
285
  export function pristineByHand({ dest, init, message, quote }) {
286
286
  const at = `git -C ${quote(dest)}`;
@@ -288,5 +288,5 @@ export function pristineByHand({ dest, init, message, quote }) {
288
288
  ...(init ? [`${at} init -q`, `${at} symbolic-ref HEAD refs/heads/main`] : []),
289
289
  `${at} add --force -A`,
290
290
  `${at} commit -m ${quote(message)}`,
291
- ].join(" && ");
291
+ ];
292
292
  }
package/lib/login.mjs ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The key the Pipelex login saved, read as the last source of the key.
3
+ *
4
+ * `npx -y @pipelex/mcp@latest login` saves its key as `PIPELEX_API_KEY` in
5
+ * `~/.pipelex/.env`, or in the `.env` of `PIPELEX_HOME` when that is set, and
6
+ * the Pipelex plugin's tools read that file on every call. The initializer's
7
+ * preflight reads it too, after the environment, so one login serves the tools
8
+ * and the method app. The copy's `npm run create` reads the same file under
9
+ * the same rules, which the template's `scripts/lib/create.mts` restates
10
+ * because a template may import nothing from outside its directory; both
11
+ * suites execute the family's `initializers/login-key.json` to keep the two
12
+ * readings identical, and both follow `pipelex-mcp`'s `src/credentials.ts`,
13
+ * which owns the file.
14
+ *
15
+ * The rules:
16
+ *
17
+ * - **The file is read only when the environment holds no key**, and the key
18
+ * is never copied anywhere, nor printed.
19
+ * - **Where it is**: `PIPELEX_HOME`, read from the environment alone, `~` or a
20
+ * leading `~/` (`~\` on Windows) expanded against the user's home directory;
21
+ * else `.pipelex` under the user's home directory. A `PIPELEX_HOME` that is
22
+ * neither absolute nor `~`-prefixed, `~user/…` included, is refused rather
23
+ * than resolved against the working directory, where a cloned repository
24
+ * could put a `.env` of its own.
25
+ * - **What counts as the file**: a regular file of at most
26
+ * {@link MAX_LOGIN_FILE_BYTES}, a symlink followed to its target, parsed
27
+ * with Node's own `.env` parser, a leading byte-order mark dropped.
28
+ * - **An empty value is no value**, for `PIPELEX_API_KEY`, `PIPELEX_BASE_URL`
29
+ * and `PIPELEX_HOME` alike.
30
+ * - **The file's `PIPELEX_BASE_URL` comes with the file's key, and with it
31
+ * alone**, so that a development key saved beside a development base URL is
32
+ * not sent to production. The initializer makes no request and reads it only
33
+ * for the shared cases; `npm run create` pairs it with the key.
34
+ */
35
+
36
+ import fs from "node:fs";
37
+ import os from "node:os";
38
+ import path from "node:path";
39
+ import process from "node:process";
40
+ // The module, not the named export: `parseEnv` arrived in Node 20.12, and a
41
+ // named import of it would fail to link on an older Node before the
42
+ // initializer could print its `refused: node-too-old`.
43
+ import util from "node:util";
44
+
45
+ /** The home directory's name under the user's home, when `PIPELEX_HOME` is not set. */
46
+ export const HOME_DIR_NAME = ".pipelex";
47
+
48
+ /** The file in the home directory that holds the saved key. */
49
+ export const LOGIN_FILENAME = ".env";
50
+
51
+ /** A file past this is not the credentials file, and counts as unreadable. */
52
+ export const MAX_LOGIN_FILE_BYTES = 1024 * 1024;
53
+
54
+ /**
55
+ * The command that saves a key, as the person types it on this system: on
56
+ * Windows, `npx.cmd`, which runs in Windows PowerShell 5.1 whatever its
57
+ * execution policy, where a typed `npx` may be refused.
58
+ */
59
+ export function loginCommand(platform = process.platform) {
60
+ return `${platform === "win32" ? "npx.cmd" : "npx"} -y @pipelex/mcp@latest login`;
61
+ }
62
+
63
+ /**
64
+ * The directory that holds the login's file, or `null` for a `PIPELEX_HOME`
65
+ * this reader refuses.
66
+ */
67
+ export function loginHome(env, homedir = os.homedir) {
68
+ const configured = env.PIPELEX_HOME;
69
+ if (!configured) return path.join(homedir(), HOME_DIR_NAME);
70
+ if (configured === "~") return path.normalize(homedir());
71
+ if (configured.startsWith("~/") || (path.sep === "\\" && configured.startsWith("~\\"))) {
72
+ return path.join(homedir(), configured.slice(2));
73
+ }
74
+ if (path.isAbsolute(configured)) return path.normalize(configured);
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * What reading the login's file found. Never throws.
80
+ *
81
+ * { status: "key", file, key, baseUrl } a key, with the file's base URL or undefined
82
+ * { status: "no-key", file } a readable file that holds no key
83
+ * { status: "missing", file } no file there
84
+ * { status: "unreadable", file } a file that cannot be read as the credentials file
85
+ * { status: "relative-home" } a PIPELEX_HOME this reader refuses
86
+ */
87
+ export function readLoginKey(env, { homedir = os.homedir } = {}) {
88
+ let home;
89
+ try {
90
+ home = loginHome(env, homedir);
91
+ } catch {
92
+ // `os.homedir()` throws only when the user has no home directory at all.
93
+ return { status: "unreadable", file: path.join("~", HOME_DIR_NAME, LOGIN_FILENAME) };
94
+ }
95
+ if (home === null) return { status: "relative-home" };
96
+ const file = path.join(home, LOGIN_FILENAME);
97
+ let text;
98
+ try {
99
+ const stats = fs.statSync(file);
100
+ if (!stats.isFile() || stats.size > MAX_LOGIN_FILE_BYTES) return { status: "unreadable", file };
101
+ text = fs.readFileSync(file, "utf8");
102
+ } catch (error) {
103
+ return { status: error?.code === "ENOENT" ? "missing" : "unreadable", file };
104
+ }
105
+ let values;
106
+ try {
107
+ values = util.parseEnv(text.replace(/^\uFEFF/, ""));
108
+ } catch {
109
+ return { status: "unreadable", file };
110
+ }
111
+ const key = values.PIPELEX_API_KEY || undefined;
112
+ if (key === undefined) return { status: "no-key", file };
113
+ return { status: "key", file, key, baseUrl: values.PIPELEX_BASE_URL || undefined };
114
+ }
115
+
116
+ /** A path as a message shows it: `~/…` under the user's home directory, absolute otherwise. */
117
+ export function displayPath(file, homedir = os.homedir) {
118
+ try {
119
+ const relative = path.relative(homedir(), file);
120
+ const outside = relative === ".." || relative.startsWith(`..${path.sep}`);
121
+ if (relative !== "" && !outside && !path.isAbsolute(relative)) return `~${path.sep}${relative}`;
122
+ } catch {
123
+ // No home directory to abbreviate against.
124
+ }
125
+ return file;
126
+ }
127
+
128
+ /**
129
+ * Why no key was found, for the `refused: no-key` verdict: the login first,
130
+ * then the shell, then writing `.env.local` by hand.
131
+ */
132
+ export function noKeyDetail(read, { homedir = os.homedir, platform = process.platform } = {}) {
133
+ const login = loginCommand(platform);
134
+ const rest =
135
+ "export PIPELEX_API_KEY in this shell, or pass --no-create and write .env.local yourself before running npm run create; npm run create never copies the key into the project";
136
+ if (read.status === "relative-home") {
137
+ return `PIPELEX_API_KEY is not set, and the login's saved key is not read because PIPELEX_HOME is neither an absolute path nor one starting with ~/: fix PIPELEX_HOME and run ${login}, ${rest}`;
138
+ }
139
+ const shown = displayPath(read.file, homedir);
140
+ if (read.status === "unreadable") {
141
+ return `PIPELEX_API_KEY is not set, and ${shown}, where the login saves it, cannot be read: make it a file you can read and run ${login}, ${rest}`;
142
+ }
143
+ return `PIPELEX_API_KEY is not set, and no key is saved in ${shown}: run ${login} to save one there, ${rest}`;
144
+ }
package/lib/main.mjs CHANGED
@@ -1,27 +1,30 @@
1
1
  /**
2
2
  * `create-method-app`: write a template of the family into a directory, make
3
3
  * the pristine commit where nothing of the user's is at stake, and run the
4
- * copy's own `make create`.
4
+ * copy's own gesture: `npm install`, then `npm run create`. Nothing it runs
5
+ * needs `make` or a POSIX shell, so it runs on Windows as elsewhere.
5
6
  *
6
7
  * The order is the safety story:
7
8
  *
8
9
  * 1. **A preflight that leaves nothing behind.** The arguments and the
9
- * template; Node at or above the template's `engines` floor; `make`, and
10
- * `git` unless `--no-git`; `--method` and `PIPELEX_API_KEY` unless
11
- * `--no-create`, the key tested for presence and never printed; the
12
- * destination rule; git's reading of the destination, and an identity when
13
- * a commit will be made. It writes nothing but a missing destination inside
14
- * another repository's work tree, made so that git reads it as the
15
- * directory it will be, and the throwaway repository in which a new
16
- * repository's identity is read when none shows outside one, or always
17
- * under a path another repository ignores, and removes each before going
18
- * on. Each failure is a `refused:` verdict naming the fix.
10
+ * template; Node at or above the template's `engines` floor; npm unless
11
+ * `--no-create`, and `git` unless `--no-git`; `--method` and a key
12
+ * unless `--no-create`, `PIPELEX_API_KEY` from the environment or else the
13
+ * one the Pipelex login saved (`login.mjs`), tested for presence and never
14
+ * printed; the destination rule; git's reading of the destination,
15
+ * and an identity when a commit will be made. It writes nothing but a
16
+ * missing destination inside another repository's work tree, made so that
17
+ * git reads it as the directory it will be, and the throwaway repository
18
+ * in which a new repository's identity is read when none shows outside
19
+ * one, or always under a path another repository ignores, and removes
20
+ * each before going on. Each failure is a `refused:` verdict naming the fix.
19
21
  * 2. **The write**, exclusive, removing what it created when it cannot finish.
20
22
  * 3. **Git**: a new repository on `main` outside any work tree or where the
21
23
  * enclosing repository ignores the destination, then the pristine commit;
22
24
  * the commit alone at the root of a repository with no commit yet; nothing
23
25
  * inside another repository's work tree, or with `--no-git`.
24
- * 4. **`make create`**, unless `--no-create`, streamed or logged.
26
+ * 4. **`npm install`, then `npm run create`**, unless `--no-create`, streamed
27
+ * or logged.
25
28
  * 5. **The report**: the gesture's warnings, the git outcome, and the verdict
26
29
  * line, last.
27
30
  *
@@ -45,10 +48,19 @@ import {
45
48
  readGit,
46
49
  templateOrigin,
47
50
  } from "./git.mjs";
48
- import { extractWarnings, makeArgs, runMake } from "./make.mjs";
51
+ import { noKeyDetail, readLoginKey } from "./login.mjs";
52
+ import {
53
+ createWords,
54
+ extractWarnings,
55
+ npmInvocation,
56
+ npmProblem,
57
+ onPath,
58
+ runCreate,
59
+ stampInstall,
60
+ } from "./npm.mjs";
49
61
  import { decodePack, PackError } from "./pack.mjs";
50
62
  import { loadTable, PACKAGE_ROOT } from "./templates.mjs";
51
- import { EXIT_OK, shellQuote, Verdict } from "./verdict.mjs";
63
+ import { EXIT_OK, inTurn, shellQuote, Verdict } from "./verdict.mjs";
52
64
  import { DestinationChanged, Interrupted, writeTree } from "./write.mjs";
53
65
 
54
66
  export const PACKS_DIR = path.join(PACKAGE_ROOT, "templates");
@@ -58,21 +70,6 @@ export function ownVersion() {
58
70
  return JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf8")).version;
59
71
  }
60
72
 
61
- /** Whether an executable named `tool` is on the `PATH` `env` carries. */
62
- export function onPath(tool, env) {
63
- for (const dir of (env.PATH ?? "").split(path.delimiter)) {
64
- if (dir === "") continue;
65
- const candidate = path.join(dir, tool);
66
- try {
67
- fs.accessSync(candidate, fs.constants.X_OK);
68
- if (fs.statSync(candidate).isFile()) return true;
69
- } catch {
70
- // not here
71
- }
72
- }
73
- return false;
74
- }
75
-
76
73
  /** Compare two `X.Y.Z` versions. */
77
74
  export function compareVersions(a, b) {
78
75
  const pa = a.split(".").map(Number);
@@ -121,11 +118,15 @@ function nodeFloor(pack) {
121
118
 
122
119
  /** Everything a run reads from outside, so a test can substitute each. */
123
120
  export function resolveDeps(deps = {}) {
121
+ const env = deps.env ?? process.env;
124
122
  return {
125
123
  cwd: deps.cwd ?? process.cwd(),
126
- env: deps.env ?? process.env,
124
+ env,
125
+ homedir: deps.homedir ?? os.homedir,
126
+ npm: deps.npm ?? npmInvocation(env),
127
127
  out: deps.out ?? process.stdout,
128
128
  packDir: deps.packDir ?? PACKS_DIR,
129
+ platform: deps.platform ?? process.platform,
129
130
  nodeVersion: deps.nodeVersion ?? process.versions.node,
130
131
  signal: deps.signal,
131
132
  tmpDir: deps.tmpDir ?? os.tmpdir(),
@@ -160,7 +161,7 @@ function chooseTemplate(args, table) {
160
161
  if (!takes.has(variable)) {
161
162
  throw Verdict.refused(
162
163
  "unknown-option",
163
- `${flag} is not an option of ${template}'s make create`,
164
+ `${flag} is not an option of ${template}'s npm run create`,
164
165
  );
165
166
  }
166
167
  }
@@ -248,13 +249,23 @@ function planGit(args, dest, found, env) {
248
249
  return plan;
249
250
  }
250
251
 
251
- /** The make create line to run next, without --dry-run, quoted for a shell. */
252
- function nextCreate(table, template, values) {
252
+ /**
253
+ * The commands to run next, without --dry-run, quoted for this system's shell
254
+ * and in order: `cd` into the copy, then `npm run create`, after the
255
+ * `npm install` it needs unless `installed`.
256
+ */
257
+ function nextCreate(dest, table, template, values, { installed = false } = {}) {
253
258
  const forwarded = { ...values };
254
259
  delete forwarded.DRY_RUN;
255
- const words = makeArgs(table.variablesOf(template), forwarded, table.switches).map(shellQuote);
256
- if (values[table.required] === undefined) words.splice(1, 0, `${table.required}=<method>`);
257
- return `make ${words.join(" ")}`;
260
+ const words = createWords(
261
+ table.variablesOf(template),
262
+ forwarded,
263
+ table.switches,
264
+ table.required,
265
+ ).map((word) => shellQuote(word));
266
+ if (values[table.required] === undefined) words.unshift("<method>");
267
+ const create = `npm run create -- ${words.join(" ")}`;
268
+ return inTurn([`cd ${shellQuote(dest)}`, ...(installed ? [] : ["npm install"]), create]);
258
269
  }
259
270
 
260
271
  async function create(argv, d, say, state) {
@@ -277,13 +288,15 @@ async function create(argv, d, say, state) {
277
288
  `${template} needs Node ${floor} or later, and this is Node ${d.nodeVersion}: switch to a newer Node, then run this again`,
278
289
  );
279
290
  }
280
- const missing = ["make", ...(args.noGit ? [] : ["git"])].filter((tool) => !onPath(tool, d.env));
281
- if (missing.length > 0) {
282
- throw Verdict.refused(
283
- "missing-tool",
284
- `${missing.join(" and ")} ${missing.length > 1 ? "are" : "is"} not on the PATH: install ${missing.length > 1 ? "them" : "it"}${missing.includes("git") ? ", or pass --no-git to make no repository" : ""}`,
285
- );
291
+ const missing = [];
292
+ if (!args.noCreate) {
293
+ const npmMissing = npmProblem(d.npm, d.env);
294
+ if (npmMissing !== null) missing.push(npmMissing);
286
295
  }
296
+ if (!args.noGit && !onPath("git", d.env)) {
297
+ missing.push("git is not on the PATH: install it, or pass --no-git to make no repository");
298
+ }
299
+ if (missing.length > 0) throw Verdict.refused("missing-tool", missing.join("; "));
287
300
  if (!args.noCreate && args.values[table.required] === undefined) {
288
301
  throw Verdict.refused(
289
302
  "no-method",
@@ -291,10 +304,16 @@ async function create(argv, d, say, state) {
291
304
  );
292
305
  }
293
306
  if (!args.noCreate && !d.env.PIPELEX_API_KEY?.trim()) {
294
- throw Verdict.refused(
295
- "no-key",
296
- "PIPELEX_API_KEY is not set: export it in this shell for make create, which never copies it into the project, or pass --no-create and write .env.local yourself before running make create",
297
- );
307
+ // The copy is new, so it has no .env.local or .env: after the environment,
308
+ // the login's file is the one source left, and npm run create reads it
309
+ // again itself, under the same rules.
310
+ const login = readLoginKey(d.env, { homedir: d.homedir });
311
+ if (login.status !== "key") {
312
+ throw Verdict.refused(
313
+ "no-key",
314
+ noKeyDetail(login, { homedir: d.homedir, platform: d.platform }),
315
+ );
316
+ }
298
317
  }
299
318
 
300
319
  const dest = path.resolve(d.cwd, args.dir);
@@ -374,39 +393,38 @@ async function create(argv, d, say, state) {
374
393
  for (const line of error.message.split("\n")) say(line);
375
394
  throw Verdict.failed(
376
395
  "commit",
377
- `git refused the pristine commit (above). The copy stands in ${dest}: commit it with ${pristineByHand({ dest, init: git.init, message, quote: shellQuote })}, then run cd ${shellQuote(dest)} && ${nextCreate(table, template, values)}`,
396
+ `git refused the pristine commit (above). The copy stands in ${dest}: commit it with ${inTurn(pristineByHand({ dest, init: git.init, message, quote: shellQuote }))}, then run ${nextCreate(dest, table, template, values)}`,
378
397
  );
379
398
  }
380
399
  }
381
400
 
382
- const where = shellQuote(dest);
383
401
  if (args.noCreate) {
384
402
  say(gitLine);
385
- return { line: `copied ${dest}; next: cd ${where} && ${nextCreate(table, template, values)}` };
403
+ return { line: `copied ${dest}; next: ${nextCreate(dest, table, template, values)}` };
386
404
  }
387
405
 
388
- // ── make create ──
406
+ // ── npm install, then npm run create ──
389
407
  state.phase = "create";
390
408
  const stands = git.commit ? "The copy and its commit stand" : "The copy stands";
391
409
  if (d.signal?.aborted) {
392
410
  say(gitLine);
393
411
  throw Verdict.failed(
394
412
  "create",
395
- `${d.signal.reason ?? "a signal"} interrupted the run before make create started. ${stands} in ${dest}; run cd ${where} && ${nextCreate(table, template, values)}`,
413
+ `${d.signal.reason ?? "a signal"} interrupted the run before npm install started. ${stands} in ${dest}; run ${nextCreate(dest, table, template, values)}`,
396
414
  );
397
415
  }
398
416
  let logFile;
399
417
  if (args.quiet) {
400
- logFile = path.join(
401
- fs.mkdtempSync(path.join(d.tmpDir, "create-method-app-")),
402
- "make-create.log",
418
+ logFile = path.join(fs.mkdtempSync(path.join(d.tmpDir, "create-method-app-")), "create.log");
419
+ say(
420
+ `create-method-app: running npm install and npm run create in ${dest}; their output goes to ${logFile}`,
403
421
  );
404
- say(`create-method-app: running make create in ${dest}; its output goes to ${logFile}`);
405
422
  } else {
406
- say(`create-method-app: running make create in ${dest}\n`);
423
+ say(`create-method-app: running npm install and npm run create in ${dest}\n`);
407
424
  }
408
- const argvMake = makeArgs(table.variablesOf(template), values, table.switches);
409
- const result = await runMake(argvMake, {
425
+ const words = createWords(table.variablesOf(template), values, table.switches, table.required);
426
+ const result = await runCreate(words, {
427
+ npm: d.npm,
410
428
  cwd: dest,
411
429
  env: d.env,
412
430
  out: d.out,
@@ -416,30 +434,54 @@ async function create(argv, d, say, state) {
416
434
 
417
435
  const warnings = extractWarnings(result.output);
418
436
  say("");
419
- say(warnings.length > 0 ? "warnings from make create:" : "warnings from make create: none");
437
+ say(warnings.length > 0 ? "warnings from npm run create:" : "warnings from npm run create: none");
420
438
  for (const warning of warnings) say(` ${warning}`);
421
439
  say(gitLine);
440
+ if (result.error?.stuck) {
441
+ throw Verdict.failed(
442
+ "create",
443
+ `${d.signal?.reason ?? "a signal"} interrupted npm ${result.step}, and ${result.error.message}: stop it yourself. ${stands} in ${dest}.`,
444
+ );
445
+ }
422
446
  if (result.error !== null) {
423
447
  throw Verdict.failed(
424
448
  "create",
425
- `make could not be run: ${result.error.message}. ${stands} in ${dest}.`,
449
+ `npm could not be run: ${result.error.message}. ${stands} in ${dest}.`,
426
450
  );
427
451
  }
452
+ const interrupted = d.signal?.aborted ? (d.signal.reason ?? "a signal") : null;
428
453
  if (result.status !== 0) {
429
- const how =
430
- result.status === null ? `was stopped by ${result.signal}` : `exited ${result.status}`;
454
+ // Elsewhere a stopped step ends by a signal; on Windows, which has none,
455
+ // it ends with a status, and the interruption is what stopped it.
456
+ let how = `exited ${result.status}`;
457
+ if (result.status === null) how = `was stopped by ${result.signal}`;
458
+ else if (interrupted !== null) how = `was stopped by ${interrupted}`;
431
459
  const said = args.quiet ? `the end of its log, ${logFile},` : "its own message above";
460
+ if (result.step === "install") {
461
+ throw Verdict.failed(
462
+ "create",
463
+ `npm install ${how}, so npm run create did not start. ${stands} in ${dest}, and ${said} says why; once that is fixed, run ${nextCreate(dest, table, template, values)}`,
464
+ );
465
+ }
466
+ throw Verdict.failed(
467
+ "create",
468
+ `npm run create ${how}. ${stands} in ${dest}, and ${said} says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot.`,
469
+ );
470
+ }
471
+ if (result.step === "install") {
472
+ // The install succeeded, and an interruption came before the gesture.
432
473
  throw Verdict.failed(
433
474
  "create",
434
- `make create ${how}. ${stands} in ${dest}, and ${said} says what to run next: a refusal before it wrote anything can be fixed and run again, and a failure after it cannot.`,
475
+ `${interrupted ?? "a signal"} interrupted the run before npm run create started. ${stands} in ${dest}, its dependencies installed; run ${nextCreate(dest, table, template, values, { installed: true })}`,
435
476
  );
436
477
  }
437
478
  if (values.DRY_RUN) {
438
479
  return {
439
- line: `copied ${dest} (make create --dry-run changed nothing); next: cd ${where} && ${nextCreate(table, template, values)}`,
480
+ line: `copied ${dest} (npm run create --dry-run changed nothing); next: ${nextCreate(dest, table, template, values, { installed: true })}`,
440
481
  };
441
482
  }
442
- return { line: `created ${dest}; next: cd ${where} && make serve` };
483
+ stampInstall(dest);
484
+ return { line: `created ${dest}; next: ${inTurn([`cd ${shellQuote(dest)}`, "npm run serve"])}` };
443
485
  }
444
486
 
445
487
  /**
package/lib/npm.mjs ADDED
@@ -0,0 +1,286 @@
1
+ /**
2
+ * The copy's own gesture, run with npm: `npm install`, since a fresh copy has
3
+ * no `node_modules` and the gesture's script needs its dependencies, then
4
+ * `npm run create -- <method> [--flag value …]`. Both run with an argument
5
+ * vector and no shell of the initializer's, so no value ever needs quoting
6
+ * here: each reaches npm as one argument, and npm hands it to the script.
7
+ * Nothing here needs `make`, so the same run works on Windows, where npm is a
8
+ * `.cmd` file that Node will not spawn without a shell: there npm is run as
9
+ * its own script, `npm-cli.js`, with this Node, as the template's
10
+ * `scripts/lib/npm.mts` does.
11
+ *
12
+ * The output of both steps is streamed, or, with `--quiet`, written to one log
13
+ * alone. Either way it is read for the gesture's warnings, which open with
14
+ * `! ` (the gesture's own) or `warning: ` (the bootstrap's), and are printed
15
+ * again at the end because `npm run all` fills the tail. The gesture runs its
16
+ * bootstrap twice, a dry run then the write, so each warning is kept once.
17
+ */
18
+
19
+ import { spawn } from "node:child_process";
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import process from "node:process";
23
+
24
+ import { gitEnv } from "./git.mjs";
25
+ import { flagOf } from "./templates.mjs";
26
+
27
+ /** npm's own script, which npm names in `npm_execpath` for whatever it runs. */
28
+ const NPM_SCRIPT = "npm-cli.js";
29
+
30
+ /**
31
+ * How to run npm: a command and the arguments that come before npm's own.
32
+ * Under `npm create`, npm names its own script in `npm_execpath`, and it is run
33
+ * with this Node, so the gesture runs under the npm that ran the initializer.
34
+ * Another package manager names its own script there, which is not npm's and
35
+ * is passed over. Elsewhere it is `npm` on the `PATH`, except on Windows, where
36
+ * `npm` is `npm.cmd`: there npm's script is the one the Node installer puts
37
+ * beside `node.exe`.
38
+ */
39
+ export function npmInvocation(env, platform = process.platform, execPath = process.execPath) {
40
+ const named = env.npm_execpath;
41
+ const pathOf = platform === "win32" ? path.win32 : path.posix;
42
+ if (named !== undefined && pathOf.basename(named) === NPM_SCRIPT) {
43
+ return { command: execPath, args: [named] };
44
+ }
45
+ if (platform !== "win32") return { command: "npm", args: [] };
46
+ return {
47
+ command: execPath,
48
+ args: [path.win32.join(path.win32.dirname(execPath), "node_modules", "npm", "bin", NPM_SCRIPT)],
49
+ };
50
+ }
51
+
52
+ /** The value of `name` in `env`, whose names Windows reads without regard to case. */
53
+ export function envValue(env, name, platform = process.platform) {
54
+ if (platform !== "win32") return env[name];
55
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
56
+ return key === undefined ? undefined : env[key];
57
+ }
58
+
59
+ /**
60
+ * Whether an executable named `tool` is on the `PATH` `env` carries. On
61
+ * Windows a command is a file named `tool` plus one of the extensions
62
+ * `PATHEXT` lists, such as `git.exe`.
63
+ */
64
+ export function onPath(tool, env, platform = process.platform) {
65
+ const pathOf = platform === "win32" ? path.win32 : path.posix;
66
+ const names =
67
+ platform === "win32"
68
+ ? (envValue(env, "PATHEXT", platform) ?? ".COM;.EXE;.BAT;.CMD")
69
+ .split(";")
70
+ .filter((ext) => ext !== "")
71
+ .map((ext) => `${tool}${ext}`)
72
+ : [tool];
73
+ for (const dir of (envValue(env, "PATH", platform) ?? "").split(pathOf.delimiter)) {
74
+ if (dir === "") continue;
75
+ for (const name of names) {
76
+ const candidate = pathOf.join(dir, name);
77
+ try {
78
+ fs.accessSync(candidate, fs.constants.X_OK);
79
+ if (fs.statSync(candidate).isFile()) return true;
80
+ } catch {
81
+ // not here
82
+ }
83
+ }
84
+ }
85
+ return false;
86
+ }
87
+
88
+ /**
89
+ * Why npm cannot be run as `invocation` says, or null: `npm` not on the
90
+ * `PATH`, or npm's script missing where it is named.
91
+ */
92
+ export function npmProblem(invocation, env, platform = process.platform) {
93
+ if (invocation.args.length === 0) {
94
+ return onPath(invocation.command, env, platform)
95
+ ? null
96
+ : "npm is not on the PATH: install Node.js with its npm, or pass --no-create to write the template alone";
97
+ }
98
+ const script = invocation.args[0];
99
+ return fs.existsSync(script)
100
+ ? null
101
+ : `npm is not where ${script} names it: reinstall Node.js with its npm, or pass --no-create to write the template alone`;
102
+ }
103
+
104
+ /**
105
+ * The words `npm run create` takes after `--`: the method, then each value
106
+ * given, in the contract's order, as its flag and the value as typed, and a
107
+ * switch given as its flag alone. A template's `make create` forwards each
108
+ * variable the same way, which the family's create contract holds it to.
109
+ */
110
+ export function createWords(order, values, switches, required) {
111
+ const words = values[required] === undefined ? [] : [values[required]];
112
+ for (const variable of order) {
113
+ if (variable === required) continue;
114
+ if (switches.has(variable)) {
115
+ if (values[variable]) words.push(flagOf(variable));
116
+ } else if (values[variable] !== undefined) {
117
+ words.push(flagOf(variable), values[variable]);
118
+ }
119
+ }
120
+ return words;
121
+ }
122
+
123
+ /**
124
+ * The stamp of the copy's last install, which its Makefile's install guard
125
+ * reads: `make install` leaves it, and `make create` leaves it after its
126
+ * install and again after the gesture, whose lock re-sync rewrites
127
+ * `package-lock.json` and changes nothing `node_modules` holds. Left the same
128
+ * way here, a project made by the initializer does not reinstall on its first
129
+ * `make` check what is already installed.
130
+ */
131
+ export const INSTALL_STAMP = path.join("node_modules", ".lock-installed");
132
+
133
+ /**
134
+ * Leave the stamp of an install in `dir`, now, when it holds `node_modules`.
135
+ * The stamp only spares a reinstall, so a stamp that cannot be written is let
136
+ * go: the guard then reads npm's own record of the install instead.
137
+ */
138
+ export function stampInstall(dir) {
139
+ if (!fs.existsSync(path.join(dir, "node_modules"))) return;
140
+ const stamp = path.join(dir, INSTALL_STAMP);
141
+ try {
142
+ fs.closeSync(fs.openSync(stamp, "a"));
143
+ const now = new Date();
144
+ fs.utimesSync(stamp, now, now);
145
+ } catch {
146
+ // best effort, as above
147
+ }
148
+ }
149
+
150
+ /** The warnings in a run's output, each once, in the order they first appeared. */
151
+ export function extractWarnings(output) {
152
+ const seen = new Set();
153
+ for (const line of output.split(/\r?\n/)) {
154
+ if ((line.startsWith("! ") || line.startsWith("warning: ")) && !seen.has(line)) seen.add(line);
155
+ }
156
+ return [...seen];
157
+ }
158
+
159
+ /** How long a step has to end once it is stopped, before the run stops waiting for it. */
160
+ export const STOP_GRACE_MS = 10_000;
161
+
162
+ /**
163
+ * Stop a child and everything it started. Elsewhere npm passes the signal on
164
+ * to the script it runs; on Windows there is no signal to pass, so the whole
165
+ * tree is ended with `taskkill`, which Windows ships. A `taskkill` that cannot
166
+ * run, or that ends with a failure, as when it is denied access, falls back
167
+ * to ending npm alone, which is all Node can do there.
168
+ */
169
+ function stop(child, platform, taskkill) {
170
+ if (platform !== "win32") {
171
+ child.kill("SIGTERM");
172
+ return;
173
+ }
174
+ if (child.pid === undefined) return;
175
+ const killer = spawn(taskkill, ["/pid", String(child.pid), "/T", "/F"], {
176
+ stdio: "ignore",
177
+ windowsHide: true,
178
+ });
179
+ let fellBack = false;
180
+ const fallBack = () => {
181
+ if (fellBack) return;
182
+ fellBack = true;
183
+ child.kill();
184
+ };
185
+ killer.on("error", fallBack);
186
+ killer.on("close", (code) => {
187
+ if (code !== 0) fallBack();
188
+ });
189
+ }
190
+
191
+ /** Run one npm command, sending its output to `take`. Resolves `{ status, signal, error }`. */
192
+ function runOne(invocation, args, { cwd, env, take, signal, platform, taskkill, graceMs }) {
193
+ return new Promise((resolve) => {
194
+ const child = spawn(invocation.command, [...invocation.args, ...args], {
195
+ cwd,
196
+ env,
197
+ stdio: ["ignore", "pipe", "pipe"],
198
+ windowsHide: true,
199
+ });
200
+ child.stdout.on("data", take);
201
+ child.stderr.on("data", take);
202
+ let failed = null;
203
+ let settled = false;
204
+ let bound;
205
+ // Stopped, the step gets a bounded time to end: a run whose step would
206
+ // not stop ends anyway, saying the step may still run, rather than wait
207
+ // for it as long as it takes.
208
+ const onAbort = () => {
209
+ stop(child, platform, taskkill);
210
+ bound = setTimeout(() => {
211
+ failed = new Error(
212
+ `npm (pid ${child.pid}) did not stop within ${Math.round(graceMs / 1000)}s of the interruption, and may still be running`,
213
+ );
214
+ failed.stuck = true;
215
+ // Let go of it, so the run can end while it runs on.
216
+ child.stdout.destroy();
217
+ child.stderr.destroy();
218
+ child.unref();
219
+ finish(null, null);
220
+ }, graceMs);
221
+ bound.unref?.();
222
+ };
223
+ signal?.addEventListener("abort", onAbort, { once: true });
224
+ const finish = (status, killedBy) => {
225
+ if (settled) return;
226
+ settled = true;
227
+ clearTimeout(bound);
228
+ signal?.removeEventListener("abort", onAbort);
229
+ resolve({ status, signal: killedBy, error: failed });
230
+ };
231
+ child.on("error", (error) => {
232
+ failed = error;
233
+ // A process that never started emits no close of its own.
234
+ if (child.pid === undefined) finish(null, null);
235
+ });
236
+ child.on("close", finish);
237
+ });
238
+ }
239
+
240
+ /**
241
+ * Run `npm install`, then, if it succeeded and nothing interrupted the run,
242
+ * `npm run create -- <words>`, in `cwd`. Resolves
243
+ * `{ step, status, signal, output, error }`, `step` being the one that ended
244
+ * the run, `install` or `create`; never rejects. `out` receives the stream
245
+ * unless `logFile` is given. An abort of `signal` stops the step running.
246
+ */
247
+ export async function runCreate(
248
+ words,
249
+ {
250
+ npm,
251
+ cwd,
252
+ env,
253
+ out,
254
+ logFile,
255
+ signal,
256
+ platform = process.platform,
257
+ taskkill = "taskkill",
258
+ graceMs = STOP_GRACE_MS,
259
+ },
260
+ ) {
261
+ const log = logFile ? fs.openSync(logFile, "w", 0o600) : null;
262
+ const chunks = [];
263
+ const take = (chunk) => {
264
+ chunks.push(chunk);
265
+ if (log !== null) fs.writeSync(log, chunk);
266
+ else out.write(chunk);
267
+ };
268
+ // Without the variables that point git elsewhere, which the initializer
269
+ // drops for its own git calls too: the copy's install wires its hooks with
270
+ // `git config`, which would otherwise write into the repository a caller's
271
+ // `GIT_DIR` names rather than the copy's.
272
+ const options = { cwd, env: gitEnv(env), take, signal, platform, taskkill, graceMs };
273
+ let step = "install";
274
+ let result;
275
+ try {
276
+ result = await runOne(npm, ["install"], options);
277
+ if (result.error === null && result.status === 0) stampInstall(cwd);
278
+ if (result.error === null && result.status === 0 && !signal?.aborted) {
279
+ step = "create";
280
+ result = await runOne(npm, ["run", "create", "--", ...words], options);
281
+ }
282
+ } finally {
283
+ if (log !== null) fs.closeSync(log);
284
+ }
285
+ return { step, ...result, output: Buffer.concat(chunks).toString("utf8") };
286
+ }
package/lib/verdict.mjs CHANGED
@@ -6,13 +6,14 @@
6
6
  * `npm error` lines on standard error after a run that exits 1. The exit code
7
7
  * is presentation: 0 for `created` and `copied`, 1 otherwise.
8
8
  *
9
- * created <dir> the copy, the git outcome, and a green make create
9
+ * created <dir> the copy, the git outcome, and a green npm run create
10
10
  * copied <dir> --no-create or --dry-run: the copy and the git outcome only
11
11
  * refused: <why> the preflight stopped, and nothing was written
12
12
  * failed: write the copy failed or was interrupted, and what it created was removed
13
13
  * failed: commit git refused the pristine commit; the copy stands
14
- * failed: create make create did not succeed; the copy and the commit stand, and its
15
- * own message says what to run next
14
+ * failed: create npm install or npm run create did not succeed; the copy and the
15
+ * commit stand, and npm's or the gesture's own message says what to
16
+ * run next
16
17
  */
17
18
 
18
19
  export const EXIT_OK = 0;
@@ -42,7 +43,33 @@ export class Verdict extends Error {
42
43
  }
43
44
  }
44
45
 
45
- /** Quote a word for a line a person may paste into a shell. */
46
- export function shellQuote(word) {
47
- return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
46
+ import process from "node:process";
47
+
48
+ /**
49
+ * Quote a word for a line a person may paste into this system's shell. A POSIX
50
+ * shell takes single quotes. Windows has two shells and no quoting they share
51
+ * entirely: double quotes are quotes in both PowerShell and `cmd`, where single
52
+ * quotes are not quotes to `cmd`, so a word is double-quoted there, unless it
53
+ * holds a `$` or a backquote, which PowerShell would expand inside double
54
+ * quotes, and then it is single-quoted as PowerShell reads it. A word left bare
55
+ * on Windows holds nothing either shell reads specially: no `@`, which
56
+ * PowerShell splats, no `,`, which it makes a list, and no `%`, though `cmd`
57
+ * expands a `%NAME%` even between quotes.
58
+ */
59
+ export function shellQuote(word, platform = process.platform) {
60
+ if (platform !== "win32") {
61
+ return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
62
+ }
63
+ if (/^[\w+=:./\\-]+$/.test(word)) return word;
64
+ if (/[$`]/.test(word)) return `'${word.replaceAll("'", "''")}'`;
65
+ return `"${word.replaceAll('"', '""')}"`;
66
+ }
67
+
68
+ /**
69
+ * Commands a person runs one after the other, each in backquotes, as npm names
70
+ * a command: no separator between two commands reads the same in every shell,
71
+ * since Windows PowerShell 5.1 has no `&&` and `cmd` no `;`.
72
+ */
73
+ export function inTurn(commands) {
74
+ return commands.map((command) => `\`${command}\``).join(", then ");
48
75
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pipelex/create-method-app",
3
- "version": "0.71.0",
3
+ "version": "0.74.0",
4
4
  "description": "Start a Pipelex method app: npm create @pipelex/method-app@latest my-app -- --method <bundle | mt_… | address>",
5
5
  "keywords": [
6
6
  "pipelex",
Binary file
package/lib/make.mjs DELETED
@@ -1,105 +0,0 @@
1
- /**
2
- * The copy's `make create`, run with an argument vector and no shell, so no
3
- * value ever needs quoting: each variable reaches make as one `NAME=value`
4
- * word, which the template's Makefile reads with `$(value …)` and hands to its
5
- * gesture exactly as typed.
6
- *
7
- * The output is streamed, or, with `--quiet`, written to a log alone. Either
8
- * way it is read for the gesture's warnings, which open with `! ` (the
9
- * gesture's own) or `warning: ` (the bootstrap's), and are printed again at the
10
- * end because `make all` fills the tail. The gesture runs its bootstrap twice,
11
- * a dry run then the write, so each warning is kept once.
12
- */
13
-
14
- import { spawn } from "node:child_process";
15
- import fs from "node:fs";
16
-
17
- import { gitEnv } from "./git.mjs";
18
-
19
- /**
20
- * Variables through which an enclosing make would reach this one as if they
21
- * had been typed on its command line. The Makefile trusts only command-line
22
- * values, so none may arrive any other way.
23
- */
24
- const MAKE_CHANNELS = ["MAKEFLAGS", "MFLAGS", "MAKELEVEL", "MAKEOVERRIDES"];
25
-
26
- /**
27
- * The environment `make create` runs in: without the make channels, and
28
- * without the variables that point git elsewhere, which the initializer drops
29
- * for its own git calls too. The copy's install wires its hooks with
30
- * `git config`, which would otherwise write into the repository a caller's
31
- * `GIT_DIR` names rather than the copy's.
32
- */
33
- export function makeEnv(env) {
34
- const clean = gitEnv(env);
35
- for (const name of MAKE_CHANNELS) delete clean[name];
36
- return clean;
37
- }
38
-
39
- /** `make create`'s arguments: `create`, then `NAME=value` for each value given, in the contract's order. */
40
- export function makeArgs(order, values, switches) {
41
- const args = ["create"];
42
- for (const variable of order) {
43
- if (switches.has(variable)) {
44
- if (values[variable]) args.push(`${variable}=1`);
45
- } else if (values[variable] !== undefined) {
46
- args.push(`${variable}=${values[variable]}`);
47
- }
48
- }
49
- return args;
50
- }
51
-
52
- /** The warnings in a run's output, each once, in the order they first appeared. */
53
- export function extractWarnings(output) {
54
- const seen = new Set();
55
- for (const line of output.split(/\r?\n/)) {
56
- if ((line.startsWith("! ") || line.startsWith("warning: ")) && !seen.has(line)) seen.add(line);
57
- }
58
- return [...seen];
59
- }
60
-
61
- /**
62
- * Run `make` in `cwd`. Resolves `{ status, signal, output, error }`; never
63
- * rejects. `out` receives the stream unless `logFile` is given. An abort of
64
- * `signal` passes SIGTERM on to make.
65
- */
66
- export function runMake(args, { cwd, env, out, logFile, signal }) {
67
- return new Promise((resolve) => {
68
- const log = logFile ? fs.openSync(logFile, "w", 0o600) : null;
69
- const chunks = [];
70
- const child = spawn("make", args, {
71
- cwd,
72
- env: makeEnv(env),
73
- stdio: ["ignore", "pipe", "pipe"],
74
- });
75
- const take = (chunk) => {
76
- chunks.push(chunk);
77
- if (log !== null) fs.writeSync(log, chunk);
78
- else out.write(chunk);
79
- };
80
- child.stdout.on("data", take);
81
- child.stderr.on("data", take);
82
- const onAbort = () => child.kill("SIGTERM");
83
- signal?.addEventListener("abort", onAbort, { once: true });
84
- let failed = null;
85
- let settled = false;
86
- const finish = (status, killedBy) => {
87
- if (settled) return;
88
- settled = true;
89
- signal?.removeEventListener("abort", onAbort);
90
- if (log !== null) fs.closeSync(log);
91
- resolve({
92
- status,
93
- signal: killedBy,
94
- output: Buffer.concat(chunks).toString("utf8"),
95
- error: failed,
96
- });
97
- };
98
- child.on("error", (error) => {
99
- failed = error;
100
- // A make that never started emits no close of its own.
101
- if (child.pid === undefined) finish(null, null);
102
- });
103
- child.on("close", finish);
104
- });
105
- }