create-mimar 0.0.1-alpha.0 → 0.0.1-alpha.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Mimar authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,5 +1,58 @@
1
- # create-mimar
1
+ # Mimar installer
2
2
 
3
- A placeholder that reserves the name for the installer of Mimar, a batteries-included web framework for Node.js written in TypeScript, inspired by Laravel: `npx create-mimar@latest my-app`.
3
+ The installer for [Mimar](https://github.com/mimarjs/framework), published on npm as `create-mimar`. It creates a new application from the latest release of the starter, [mimarjs/mimar](https://github.com/mimarjs/mimar):
4
4
 
5
- The first alpha, `0.0.1-alpha.1`, is published from [github.com/mimarjs/installer](https://github.com/mimarjs/installer) and replaces this version. Do not install `0.0.1-alpha.0`: it contains nothing.
5
+ ```bash
6
+ npx create-mimar@latest my-app
7
+ ```
8
+
9
+ `npm create mimar@latest my-app` does the same. So do `pnpm create mimar my-app`, `yarn create mimar my-app` and `bun create mimar my-app`, and the application is installed with the package manager that ran the installer. It needs Node.js 26.14 or newer.
10
+
11
+ > **Status: alpha.** Releases are 0.0.x, like Mimar's, and the installer's flags may change between them.
12
+
13
+ ## What it does
14
+
15
+ 1. Asks for the folder and the database, unless the flags give them.
16
+ 2. Downloads the archive of the starter's latest GitHub release and unpacks it into the new folder, which must not exist or must be empty.
17
+ 3. Writes `.env` from `.env.example`: the application's name (from the folder: `my-app` is `My App`), a new `APP_KEY`, and for PostgreSQL, MySQL or MariaDB a `DATABASE_URL` for a server on this machine. `.env.example` gets the name and the database too.
18
+ 4. Installs the dependencies. With Yarn 2 or later the application gets `node_modules` (`nodeLinker: node-modules`).
19
+ 5. Runs the migrations: always for SQLite, and for a database server when asked (the database must exist).
20
+ 6. Makes a Git repository with a first commit, unless the folder is inside a repository already.
21
+ 7. Prints what to run next.
22
+
23
+ A step that fails on your machine (a package manager that is not installed, a database server that is not running, Git without your name) does not undo the others: the installer says what to run by hand.
24
+
25
+ ## Flags
26
+
27
+ | Flag | Does |
28
+ | --------------------------- | ---------------------------------------------------------------------------------------------------------- |
29
+ | `--db <name>` | `sqlite` (the default), `pgsql`, `mysql` or `mariadb` |
30
+ | `--pm <name>` | Install with `npm`, `pnpm`, `yarn` or `bun` instead of the package manager that ran the installer |
31
+ | `--starter <name>` | The starter: `react`, the only one for now |
32
+ | `--no-install` | Leave the dependencies uninstalled, and so the migrations unrun |
33
+ | `--migrate`, `--no-migrate` | Run the migrations, or not, whatever the database |
34
+ | `--no-git` | Make no Git repository |
35
+ | `--no-interaction` | Ask nothing: every question takes its default. Without a terminal nothing is asked either. |
36
+ | `--dev` | Start from the starter's main branch instead of its latest release |
37
+ | `--from <file>` | A starter archive on this machine, as `git archive --prefix=mimar/ --output starter.tar.gz HEAD` writes it |
38
+ | `--mimar <spec>` | The `mimarjs` dependency to install: a version, or a packed framework (`mimarjs-0.0.1.tgz`) |
39
+
40
+ Flags follow the folder: `npx create-mimar@latest my-app --db pgsql`. With `npm create` they go after `--`: `npm create mimar@latest my-app -- --db pgsql`.
41
+
42
+ The installer is versioned on its own, apart from the `mimarjs` package: it only copies the starter, and the application then depends on the version of `mimarjs` that the starter names. Once an application exists, its own `mimar` command does the rest.
43
+
44
+ ## Developing
45
+
46
+ ```bash
47
+ pnpm install
48
+ pnpm check
49
+ pnpm test
50
+ pnpm build
51
+ node bin/create-mimar.js my-app --from ../starter.tar.gz --mimar ../mimarjs-0.0.0.tgz
52
+ ```
53
+
54
+ CI makes an application with each package manager on Linux, macOS and Windows from the starter's and the framework's main branches, then checks, tests and builds it.
55
+
56
+ ## License
57
+
58
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ // Checks the Node version before loading the installer, which the new application needs anyway. Under bun the check
3
+ // asks the `node` on the PATH, since the application runs on Node.
4
+ import { execFileSync } from 'node:child_process'
5
+
6
+ const required = [26, 14]
7
+ let found = process.versions.node
8
+ if (process.versions.bun !== undefined) {
9
+ try {
10
+ found = execFileSync('node', ['--version'], { encoding: 'utf8' }).trim().replace(/^v/, '')
11
+ } catch {
12
+ found = undefined
13
+ }
14
+ }
15
+ const [major = 0, minor = 0] = (found ?? '').split('.').map(Number)
16
+ if (major < required[0] || (major === required[0] && minor < required[1])) {
17
+ console.error(
18
+ `Mimar needs Node.js ${required.join('.')} or newer, and ${found === undefined ? 'Node.js is not installed' : `this is ${found}`}. Install it from https://nodejs.org, then run this again.`,
19
+ )
20
+ process.exit(1)
21
+ }
22
+
23
+ const { main } = await import('../dist/main.js')
24
+ process.exitCode = await main(process.argv.slice(2))
@@ -0,0 +1,104 @@
1
+ // What makes the unpacked starter this application: its name, a key and its database in .env (and the name and the
2
+ // database in .env.example, which the team shares), the starter repository's own lines taken out of .gitignore, and,
3
+ // for testing an unreleased framework, another `mimarjs` in package.json.
4
+ import { randomBytes } from 'node:crypto';
5
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
6
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
7
+ export const databases = [
8
+ { name: 'sqlite', label: 'SQLite (no server needed)' },
9
+ { name: 'pgsql', label: 'PostgreSQL' },
10
+ { name: 'mysql', label: 'MySQL' },
11
+ { name: 'mariadb', label: 'MariaDB' },
12
+ ];
13
+ /** `my-shop` → `My Shop`, for APP_NAME. */
14
+ export function appName(folder) {
15
+ const words = folder.split(/[-_.\s]+/).filter((word) => word !== '');
16
+ return words.length === 0 ? 'Mimar' : words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
17
+ }
18
+ /** `my-shop` → `my_shop`, the database a server-based connection points at. */
19
+ export function databaseName(folder) {
20
+ const name = folder
21
+ .toLowerCase()
22
+ .replace(/[^a-z0-9]+/g, '_')
23
+ .replace(/^_+|_+$/g, '');
24
+ return name === '' ? 'mimar' : name;
25
+ }
26
+ /** The connection for a database server on this machine, with each driver's default user and no password. */
27
+ export function databaseUrl(database, name) {
28
+ if (database === 'pgsql')
29
+ return `postgres://postgres@127.0.0.1:5432/${name}`;
30
+ return `${database}://root@127.0.0.1:3306/${name}`;
31
+ }
32
+ /** A new APP_KEY, as `mimar key:generate` writes it: 32 random bytes. */
33
+ export function generateKey() {
34
+ return `base64:${randomBytes(32).toString('base64')}`;
35
+ }
36
+ /** Writes .env from .env.example, and puts the name and the database into .env.example as well. */
37
+ export function writeEnv(root, settings, key = generateKey()) {
38
+ const examplePath = join(root, '.env.example');
39
+ if (!existsSync(examplePath))
40
+ throw new Error('The starter has no .env.example.');
41
+ const example = configure(readFileSync(examplePath, 'utf8'), settings);
42
+ writeFileSync(examplePath, example);
43
+ writeFileSync(join(root, '.env'), setEnv(example, 'APP_KEY', key));
44
+ }
45
+ function configure(env, { folder, database }) {
46
+ let text = setEnv(env, 'APP_NAME', appName(folder));
47
+ if (database !== 'sqlite') {
48
+ text = setEnv(text, 'DB_CONNECTION', null, ['DATABASE_URL', databaseUrl(database, databaseName(folder))]);
49
+ text = setEnv(text, 'DB_DATABASE', null);
50
+ }
51
+ return text;
52
+ }
53
+ /**
54
+ * Sets `key` to `value` on its line, or removes the line when `value` is null. `replace` puts another key on the line
55
+ * instead. A key the file does not have is added at the end.
56
+ */
57
+ export function setEnv(env, key, value, replace) {
58
+ const lines = env.split('\n');
59
+ const index = lines.findIndex((line) => line.startsWith(`${key}=`));
60
+ const line = replace === undefined ? (value === null ? null : `${key}=${envValue(value)}`) : `${replace[0]}=${envValue(replace[1])}`;
61
+ if (index === -1) {
62
+ if (line === null)
63
+ return env;
64
+ const end = lines.at(-1) === '' ? lines.length - 1 : lines.length;
65
+ lines.splice(end, 0, line);
66
+ }
67
+ else if (line === null)
68
+ lines.splice(index, 1);
69
+ else
70
+ lines[index] = line;
71
+ return lines.join('\n');
72
+ }
73
+ /** A value as .env needs it: quoted when it holds spaces or characters .env reads specially. */
74
+ export function envValue(value) {
75
+ return /^[\w.:/@+=-]*$/.test(value) ? value : `"${value.replace(/["\\$]/g, (character) => `\\${character}`)}"`;
76
+ }
77
+ /** Removes the block of .gitignore that the starter marks as its own: its comment says "create-mimar removes" it. */
78
+ export function dropStarterIgnores(root) {
79
+ const path = join(root, '.gitignore');
80
+ if (!existsSync(path))
81
+ return;
82
+ const blocks = readFileSync(path, 'utf8')
83
+ .replace(/\n+$/, '')
84
+ .split(/\n{2,}/);
85
+ const kept = blocks.filter((block) => !(block.startsWith('#') && block.includes('create-mimar removes')));
86
+ writeFileSync(path, `${kept.join('\n\n')}\n`);
87
+ }
88
+ /**
89
+ * Points the `mimarjs` dependency at `spec`: a version range, or a packed framework (`../mimarjs-0.0.1.tgz`), which is
90
+ * written relative to the application so the path works on every system.
91
+ */
92
+ export function useMimar(root, spec, cwd = process.cwd()) {
93
+ const path = join(root, 'package.json');
94
+ const manifest = JSON.parse(readFileSync(path, 'utf8'));
95
+ const local = /\.(tgz|tar\.gz)$/.test(spec) || spec.startsWith('.') || isAbsolute(spec);
96
+ const value = local
97
+ ? `file:${relative(root, resolve(cwd, spec.replace(/^file:/, '')))
98
+ .split(sep)
99
+ .join('/')}`
100
+ : spec;
101
+ manifest.dependencies = { ...manifest.dependencies, mimarjs: value };
102
+ writeFileSync(path, `${JSON.stringify(manifest, null, 4)}\n`);
103
+ return value;
104
+ }
package/dist/main.js ADDED
@@ -0,0 +1,225 @@
1
+ // `create-mimar [folder] [flags]`: unpacks the starter into a new folder, writes .env, installs the dependencies, runs
2
+ // the migrations, makes a Git repository and says what to do next. Each step that can fail on the user's machine (the
3
+ // package manager, the database server, Git) says what to run by hand instead of leaving a half-made application.
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
5
+ import { basename, dirname, isAbsolute, relative, resolve } from 'node:path';
6
+ import { styleText } from 'node:util';
7
+ import { databaseName, databases, dropStarterIgnores, useMimar, writeEnv } from './application.js';
8
+ import { help, parseOptions, UsageError } from './options.js';
9
+ import { detect, prepareYarn, run, runBinary, runScript } from './package-manager.js';
10
+ import { defaults, terminal } from './prompt.js';
11
+ import { download, githubHosts, latestRelease, readArchive, StarterError, starters, unpack } from './starter.js';
12
+ import { ArchiveError } from './tar.js';
13
+ class CreateError extends Error {
14
+ name = 'CreateError';
15
+ }
16
+ /** Folders may hold these and still count as empty. */
17
+ const ignorable = new Set(['.DS_Store', 'Thumbs.db', '.git']);
18
+ /** Runs the installer and answers the exit code. */
19
+ export async function main(argv, environment = processEnvironment()) {
20
+ const out = (line = '') => environment.stdout.write(`${line}\n`);
21
+ let options;
22
+ try {
23
+ options = parseOptions(argv);
24
+ }
25
+ catch (error) {
26
+ if (!(error instanceof UsageError))
27
+ throw error;
28
+ environment.stderr.write(`${error.message}\n`);
29
+ return 2;
30
+ }
31
+ if (options.help) {
32
+ out(help);
33
+ return 0;
34
+ }
35
+ if (options.version) {
36
+ out(`create-mimar ${version()}`);
37
+ return 0;
38
+ }
39
+ const prompter = options.interaction && environment.interactive ? environment.prompter : defaults;
40
+ try {
41
+ return await create(options, prompter, environment);
42
+ }
43
+ catch (error) {
44
+ if (error instanceof CreateError || error instanceof StarterError || error instanceof ArchiveError) {
45
+ environment.stderr.write(`${styleText('red', 'Error:', { stream: environment.stderr })} ${error.message}\n`);
46
+ return 1;
47
+ }
48
+ throw error;
49
+ }
50
+ }
51
+ async function create(options, ask, environment) {
52
+ const out = (line = '') => environment.stdout.write(`${line}\n`);
53
+ const style = (format, text) => styleText(format, text, { stream: environment.stdout });
54
+ const step = (text) => out(`${style('cyan', '›')} ${text}`);
55
+ const note = (text) => out(`${style('yellow', '!')} ${text}`);
56
+ const answered = options.folder ?? (ask === defaults ? undefined : await ask.text('Where should the application go?', 'mimar-app'));
57
+ if (answered === undefined)
58
+ throw new CreateError('Name a folder for the application: npx create-mimar@latest my-app');
59
+ const root = resolve(environment.cwd, answered);
60
+ const folder = basename(root);
61
+ if (!/^[A-Za-z0-9][\w.-]*$/.test(folder)) {
62
+ throw new CreateError(`"${folder}" cannot name the application: use letters, digits, dashes, dots and underscores, starting with a letter or a digit.`);
63
+ }
64
+ const existed = checkEmpty(root, environment.cwd);
65
+ const starter = await chooseStarter(options, ask);
66
+ const database = options.database ??
67
+ (await ask.select('Which database will the application use?', databases.map((choice) => ({ value: choice.name, label: choice.label })), 'sqlite'));
68
+ const manager = options.packageManager ?? detect(environment.userAgent);
69
+ const shown = display(root, environment.cwd);
70
+ out();
71
+ out(`Creating a Mimar application in ${style('bold', shown)}`);
72
+ out();
73
+ let archive;
74
+ if (options.from !== undefined) {
75
+ step(`Unpacking ${options.from}`);
76
+ archive = readArchive(resolve(environment.cwd, options.from));
77
+ }
78
+ else if (options.dev) {
79
+ step(`Downloading ${starter.repository}, main branch`);
80
+ archive = await download(starter.repository, { branch: 'main' }, environment.hosts);
81
+ }
82
+ else {
83
+ const tag = await latestRelease(starter.repository, environment.hosts);
84
+ step(`Downloading ${starter.repository} ${tag}`);
85
+ archive = await download(starter.repository, { tag }, environment.hosts);
86
+ }
87
+ mkdirSync(root, { recursive: true });
88
+ try {
89
+ unpack(archive, root);
90
+ }
91
+ catch (error) {
92
+ if (!existed)
93
+ rmSync(root, { recursive: true, force: true });
94
+ throw error;
95
+ }
96
+ step(`Writing .env with a new APP_KEY${database === 'sqlite' ? '' : ` and a ${databases.find((choice) => choice.name === database).label} connection`}`);
97
+ writeEnv(root, { folder, database });
98
+ dropStarterIgnores(root);
99
+ if (options.mimar !== undefined)
100
+ step(`Using mimarjs ${useMimar(root, options.mimar, environment.cwd)}`);
101
+ const later = [];
102
+ let installed = false;
103
+ if (options.install) {
104
+ const flags = manager === 'yarn' ? await prepareYarn(root, environment.run) : [];
105
+ step(`Installing the dependencies with ${manager}`);
106
+ const result = await environment.run(manager, ['install', ...flags], { cwd: root });
107
+ installed = result.code === 0;
108
+ if (result.code === 127)
109
+ note(`${manager} is not installed, so the dependencies are not either.`);
110
+ else if (!installed)
111
+ note(`${manager} install failed (exit code ${result.code}); its output is above.`);
112
+ if (!installed)
113
+ later.push(`${manager} install`);
114
+ }
115
+ else
116
+ later.push(`${manager} install`);
117
+ const migrateLater = `${runBinary(manager, 'mimar')} migrate`;
118
+ if (installed) {
119
+ const migrate = options.migrate ??
120
+ (database === 'sqlite' ||
121
+ (await ask.confirm(`Run the migrations now? The database ${databaseName(folder)} must exist on the server.`, false)));
122
+ if (migrate) {
123
+ step('Running the migrations');
124
+ const result = await environment.run(nodeCommand(), ['main.ts', 'migrate', '--no-interaction'], { cwd: root, quiet: true });
125
+ if (result.code !== 0) {
126
+ note(`The migrations did not run:\n${indent(result.output.trim())}`);
127
+ later.push(migrateLater);
128
+ }
129
+ }
130
+ else
131
+ later.push(migrateLater);
132
+ }
133
+ else
134
+ later.push(migrateLater);
135
+ if (options.git)
136
+ await makeRepository(root, environment.run, step, note);
137
+ const before = database !== 'sqlite' && later.includes(migrateLater) ? `Create the database ${databaseName(folder)}, then:` : undefined;
138
+ out();
139
+ out(`${style('green', 'Done.')} Your application is in ${shown}. Next:`);
140
+ out();
141
+ if (shown !== '.')
142
+ out(` cd ${shown}`);
143
+ for (const command of later.filter((command) => command !== migrateLater))
144
+ out(` ${command}`);
145
+ if (before !== undefined) {
146
+ out();
147
+ out(`${before}`);
148
+ out();
149
+ }
150
+ if (later.includes(migrateLater))
151
+ out(` ${migrateLater}`);
152
+ out(` ${runScript(manager, 'dev')}`);
153
+ out();
154
+ out(`Then open http://localhost:8000. ${runBinary(manager, 'mimar')} docs lists the guides for this version.`);
155
+ out(`For an API with bearer tokens beside the pages: ${runBinary(manager, 'mimar')} install:api`);
156
+ return installed || !options.install ? 0 : 1;
157
+ }
158
+ async function chooseStarter(options, ask) {
159
+ const name = options.starter ??
160
+ (starters.length === 1
161
+ ? starters[0].name
162
+ : await ask.select('Which starter?', starters.map((starter) => ({ value: starter.name, label: starter.label })), starters[0].name));
163
+ return starters.find((starter) => starter.name === name);
164
+ }
165
+ /** Refuses a folder that holds files. Answers whether it existed. */
166
+ function checkEmpty(root, cwd) {
167
+ if (!existsSync(root))
168
+ return false;
169
+ if (!statSync(root).isDirectory())
170
+ throw new CreateError(`${display(root, cwd)} is a file, not a folder.`);
171
+ const files = readdirSync(root).filter((name) => !ignorable.has(name));
172
+ if (files.length > 0) {
173
+ throw new CreateError(`${display(root, cwd)} is not empty (it holds ${files.slice(0, 3).join(', ')}${files.length > 3 ? ', …' : ''}). Choose a new folder.`);
174
+ }
175
+ return true;
176
+ }
177
+ async function makeRepository(root, runCommand, step, note) {
178
+ const inside = await runCommand('git', ['rev-parse', '--is-inside-work-tree'], { cwd: dirname(root), quiet: true });
179
+ if (inside.code === 127)
180
+ return note('Git is not installed, so the application has no repository.');
181
+ if (inside.code === 0 && inside.output.trim() === 'true') {
182
+ return note('The folder is inside a Git repository already, so it was not made a repository of its own.');
183
+ }
184
+ step('Making a Git repository');
185
+ const quiet = { cwd: root, quiet: true };
186
+ if ((await runCommand('git', ['init', '--quiet'], quiet)).code !== 0)
187
+ return note('git init failed, so the application has no repository.');
188
+ await runCommand('git', ['add', '--all'], quiet);
189
+ const commit = await runCommand('git', ['commit', '--quiet', '--message', 'Create the application'], quiet);
190
+ if (commit.code !== 0) {
191
+ note('The first commit was not made: Git needs your name and email (git config --global user.name and user.email). The files are staged.');
192
+ }
193
+ }
194
+ /** The path as the user would type it: relative to where they are, unless that climbs out. */
195
+ function display(path, cwd) {
196
+ const shown = relative(cwd, path);
197
+ if (shown === '')
198
+ return '.';
199
+ return shown.startsWith('..') || isAbsolute(shown) ? path : shown;
200
+ }
201
+ function indent(text) {
202
+ return text
203
+ .split('\n')
204
+ .map((line) => ` ${line}`)
205
+ .join('\n');
206
+ }
207
+ /** The application runs on Node. Under bun, process.execPath is bun's, so Node is found on the PATH. */
208
+ function nodeCommand() {
209
+ return process.versions.bun === undefined ? process.execPath : 'node';
210
+ }
211
+ function version() {
212
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
213
+ }
214
+ function processEnvironment() {
215
+ return {
216
+ cwd: process.cwd(),
217
+ stdout: process.stdout,
218
+ stderr: process.stderr,
219
+ interactive: process.stdin.isTTY === true && process.stdout.isTTY === true,
220
+ prompter: terminal(),
221
+ run,
222
+ hosts: githubHosts,
223
+ userAgent: process.env.npm_config_user_agent,
224
+ };
225
+ }
@@ -0,0 +1,98 @@
1
+ // The command line: `create-mimar [folder] [flags]`.
2
+ import { parseArgs } from 'node:util';
3
+ import { databases } from './application.js';
4
+ import { packageManagers } from './package-manager.js';
5
+ import { starters } from './starter.js';
6
+ export class UsageError extends Error {
7
+ name = 'UsageError';
8
+ }
9
+ export const help = `Create a new Mimar application.
10
+
11
+ Usage: npx create-mimar@latest [folder] [flags]
12
+ npm create mimar@latest [folder] -- [flags]
13
+ pnpm create mimar [folder] [flags] (also yarn create, bun create)
14
+
15
+ --starter <name> The starter: ${starters.map((starter) => starter.name).join(', ')} (the default)
16
+ --db <name> The database: ${databases.map((database) => database.name).join(', ')} (sqlite is the default)
17
+ --pm <name> Install with ${packageManagers.join(', ')} (the default is the one running this)
18
+ --no-install Leave the dependencies uninstalled (and the migrations unrun)
19
+ --migrate Run the migrations, also against a database server
20
+ --no-migrate Leave the migrations unrun
21
+ --no-git Make no Git repository
22
+ --no-interaction Ask nothing: every question takes its default
23
+ --dev Start from the starter's main branch instead of its latest release
24
+
25
+ For testing the installer and unreleased versions:
26
+ --from <file> A starter archive on this machine, as git archive --prefix=mimar/ writes it
27
+ --mimar <spec> The mimarjs dependency to install: a version, or a packed framework (mimarjs-0.0.1.tgz)
28
+
29
+ -h, --help This text
30
+ -v, --version The installer's version`;
31
+ /** Reads the arguments after the command's name. */
32
+ export function parseOptions(argv) {
33
+ let parsed;
34
+ try {
35
+ parsed = parse(argv);
36
+ }
37
+ catch (error) {
38
+ throw new UsageError(`${error.message.replace(/\. To specify.*$/s, '.')} Run create-mimar --help for the flags.`);
39
+ }
40
+ const { values, positionals } = parsed;
41
+ if (positionals.length > 1)
42
+ throw new UsageError(`Give one folder, not ${positionals.length}: ${positionals.join(' ')}.`);
43
+ if (values.migrate && values['no-migrate'])
44
+ throw new UsageError('Pass --migrate or --no-migrate, not both.');
45
+ if (values.dev && values.from !== undefined)
46
+ throw new UsageError('Pass --dev or --from, not both.');
47
+ return {
48
+ folder: positionals[0],
49
+ starter: oneOf('--starter', values.starter, starters.map((starter) => starter.name)),
50
+ database: oneOf('--db', alias(values.db), databases.map((database) => database.name)),
51
+ packageManager: oneOf('--pm', values.pm, packageManagers),
52
+ git: !values['no-git'],
53
+ install: !values['no-install'],
54
+ migrate: values.migrate ? true : values['no-migrate'] ? false : undefined,
55
+ interaction: !values['no-interaction'],
56
+ dev: values.dev ?? false,
57
+ from: values.from,
58
+ mimar: values.mimar,
59
+ help: values.help ?? false,
60
+ version: values.version ?? false,
61
+ };
62
+ }
63
+ function parse(argv) {
64
+ return parseArgs({
65
+ args: [...argv],
66
+ allowPositionals: true,
67
+ strict: true,
68
+ options: {
69
+ starter: { type: 'string' },
70
+ db: { type: 'string' },
71
+ pm: { type: 'string' },
72
+ 'no-install': { type: 'boolean' },
73
+ migrate: { type: 'boolean' },
74
+ 'no-migrate': { type: 'boolean' },
75
+ 'no-git': { type: 'boolean' },
76
+ 'no-interaction': { type: 'boolean', short: 'n' },
77
+ dev: { type: 'boolean' },
78
+ from: { type: 'string' },
79
+ mimar: { type: 'string' },
80
+ help: { type: 'boolean', short: 'h' },
81
+ version: { type: 'boolean', short: 'v' },
82
+ },
83
+ });
84
+ }
85
+ /** The names people also use for the databases: postgres for pgsql. */
86
+ function alias(database) {
87
+ if (database === undefined)
88
+ return undefined;
89
+ const lower = database.toLowerCase();
90
+ return lower === 'postgres' || lower === 'postgresql' || lower === 'pg' ? 'pgsql' : lower;
91
+ }
92
+ function oneOf(flag, value, allowed) {
93
+ if (value === undefined)
94
+ return undefined;
95
+ if (allowed.includes(value))
96
+ return value;
97
+ throw new UsageError(`${flag} takes ${allowed.join(', ')}, not "${value}".`);
98
+ }
@@ -0,0 +1,73 @@
1
+ // The package manager that installs the application: the one that ran the installer (`pnpm create mimar` sets
2
+ // npm_config_user_agent to `pnpm/…`), or the one --pm names. How each installs, runs a script and runs a binary.
3
+ import { spawn } from 'node:child_process';
4
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ export const packageManagers = ['npm', 'pnpm', 'yarn', 'bun'];
7
+ /** The package manager in a user agent such as `pnpm/11.22.0 npm/? node/v26.14.0 darwin arm64`; npm when there is none. */
8
+ export function detect(userAgent) {
9
+ const name = userAgent?.split('/')[0];
10
+ return packageManagers.includes(name) ? name : 'npm';
11
+ }
12
+ /** How a script is run, as a person types it: `npm run dev`, `pnpm dev`, `yarn dev`, `bun run dev`. */
13
+ export function runScript(manager, script) {
14
+ if (manager === 'npm' || manager === 'bun')
15
+ return `${manager} run ${script}`;
16
+ return `${manager} ${script}`;
17
+ }
18
+ /** How the application's `mimar` command is run, as a person types it. */
19
+ export function runBinary(manager, binary) {
20
+ return { npm: `npx ${binary}`, pnpm: `pnpm ${binary}`, yarn: `yarn ${binary}`, bun: `bunx ${binary}` }[manager];
21
+ }
22
+ /**
23
+ * Yarn 2 and later install with Plug'n'Play unless told otherwise, and the application imports its own files through
24
+ * node_modules (`app/…`) and runs its TypeScript with Node, so it gets node_modules. The empty yarn.lock makes the folder
25
+ * a project of its own even inside another Yarn project. Yarn's own folder is ignored as Yarn recommends: its install
26
+ * state stays on each machine, while patches, plugins and releases are shared. Returns the flags for the first install:
27
+ * on a CI machine Yarn refuses to write the lockfile unless told it may.
28
+ */
29
+ export async function prepareYarn(root, run) {
30
+ const version = await run('yarn', ['--version'], { cwd: root, quiet: true });
31
+ const major = Number.parseInt(version.output, 10);
32
+ if (version.code !== 0 || !(major >= 2))
33
+ return [];
34
+ writeFileSync(join(root, '.yarnrc.yml'), 'nodeLinker: node-modules\n');
35
+ if (!existsSync(join(root, 'yarn.lock')))
36
+ writeFileSync(join(root, 'yarn.lock'), '');
37
+ const ignore = join(root, '.gitignore');
38
+ const ignored = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
39
+ if (!ignored.includes('.yarn/*')) {
40
+ const yarn = ['.yarn/*', '!.yarn/patches', '!.yarn/plugins', '!.yarn/releases', '!.yarn/versions'].join('\n');
41
+ writeFileSync(ignore, `${ignored.trim() === '' ? '' : `${ignored.replace(/\n*$/, '\n')}\n`}${yarn}\n`);
42
+ }
43
+ return ['--no-immutable'];
44
+ }
45
+ /**
46
+ * Runs a command, printing its output unless `quiet`. A command that is not found answers code 127. On Windows, npm,
47
+ * pnpm and yarn are .cmd files, which Node starts only through the shell, so the command line is built and quoted here,
48
+ * and a missing command is looked for on the PATH first: cmd.exe exits with 1 for it, as for any failure.
49
+ */
50
+ export const run = (command, args, { cwd, quiet = false }) => new Promise((resolve) => {
51
+ const windows = process.platform === 'win32' && command !== process.execPath;
52
+ if (windows && !onWindowsPath(command)) {
53
+ resolve({ code: 127, output: `${command} is not on the PATH.\n` });
54
+ return;
55
+ }
56
+ const child = windows
57
+ ? spawn([command, ...args].map(quoteForCmd).join(' '), { cwd, shell: true, stdio: quiet ? 'pipe' : 'inherit' })
58
+ : spawn(command, args, { cwd, stdio: quiet ? 'pipe' : 'inherit' });
59
+ let output = '';
60
+ child.stdout?.on('data', (chunk) => (output += chunk.toString()));
61
+ child.stderr?.on('data', (chunk) => (output += chunk.toString()));
62
+ child.on('error', (error) => resolve({ code: error.code === 'ENOENT' ? 127 : 1, output: error.message }));
63
+ child.on('close', (code) => resolve({ code: code ?? 1, output }));
64
+ });
65
+ /** Whether cmd.exe would find `command`: a folder on the PATH holds it with one of the PATHEXT extensions, or none. */
66
+ export function onWindowsPath(command, env = process.env) {
67
+ const extensions = ['', ...(env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter((extension) => extension !== '')];
68
+ const folders = /[\\/]/.test(command) ? [''] : (env.PATH ?? env.Path ?? '').split(';').filter((folder) => folder !== '');
69
+ return folders.some((folder) => extensions.some((extension) => existsSync(join(folder, command + extension))));
70
+ }
71
+ function quoteForCmd(argument) {
72
+ return /^[\w./:=@-]+$/.test(argument) ? argument : `"${argument.replace(/"/g, '""')}"`;
73
+ }
package/dist/prompt.js ADDED
@@ -0,0 +1,80 @@
1
+ // The installer's questions. Without a terminal, or with --no-interaction, nothing is asked and each answer is its
2
+ // default, so scripts never wait for input.
3
+ import { emitKeypressEvents } from 'node:readline';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { styleText } from 'node:util';
6
+ /** Answers every question with its default. */
7
+ export const defaults = {
8
+ text: async (_question, fallback) => fallback,
9
+ select: async (_question, _choices, fallback) => fallback,
10
+ confirm: async (_question, fallback) => fallback,
11
+ };
12
+ /** Asks in the terminal. */
13
+ export function terminal(input = process.stdin, output = process.stdout) {
14
+ const style = (format, text) => styleText(format, text, { stream: output });
15
+ const ask = async (question, hint) => {
16
+ const reader = createInterface({ input, output });
17
+ try {
18
+ return (await reader.question(`${style('green', '?')} ${question} ${style('dim', hint)} `)).trim();
19
+ }
20
+ finally {
21
+ reader.close();
22
+ }
23
+ };
24
+ return {
25
+ async text(question, fallback) {
26
+ const answer = await ask(question, `(${fallback})`);
27
+ return answer === '' ? fallback : answer;
28
+ },
29
+ select(question, choices, fallback) {
30
+ let selected = Math.max(0, choices.findIndex((choice) => choice.value === fallback));
31
+ const draw = (first) => {
32
+ if (!first)
33
+ output.write(`\x1b[${choices.length}A`);
34
+ for (const [index, choice] of choices.entries()) {
35
+ const line = index === selected ? style('cyan', `❯ ${choice.label}`) : ` ${choice.label}`;
36
+ output.write(`\x1b[2K${line}\n`);
37
+ }
38
+ };
39
+ output.write(`${style('green', '?')} ${question} ${style('dim', '(arrow keys, then Enter)')}\n`);
40
+ draw(true);
41
+ return new Promise((resolve) => {
42
+ emitKeypressEvents(input);
43
+ const raw = input.isRaw;
44
+ input.setRawMode(true);
45
+ input.resume();
46
+ const finish = (value) => {
47
+ input.off('keypress', onKey);
48
+ input.setRawMode(raw);
49
+ input.pause();
50
+ output.write(`\x1b[${choices.length}A\x1b[0J${style('dim', ` ${choices[selected].label}`)}\n`);
51
+ resolve(value);
52
+ };
53
+ const onKey = (sequence, key) => {
54
+ if (key?.ctrl && key.name === 'c') {
55
+ input.setRawMode(raw);
56
+ output.write('\n');
57
+ process.exit(130);
58
+ }
59
+ const number = Number.parseInt(sequence ?? '', 10);
60
+ if (number >= 1 && number <= choices.length)
61
+ selected = number - 1;
62
+ else if (key?.name === 'up' || key?.name === 'k')
63
+ selected = (selected + choices.length - 1) % choices.length;
64
+ else if (key?.name === 'down' || key?.name === 'j')
65
+ selected = (selected + 1) % choices.length;
66
+ else if (key?.name === 'return' || key?.name === 'enter')
67
+ return finish(choices[selected].value);
68
+ else
69
+ return;
70
+ draw(false);
71
+ };
72
+ input.on('keypress', onKey);
73
+ });
74
+ },
75
+ async confirm(question, fallback) {
76
+ const answer = await ask(question, fallback ? '(Y/n)' : '(y/N)');
77
+ return answer === '' ? fallback : /^y/i.test(answer);
78
+ },
79
+ };
80
+ }
@@ -0,0 +1,88 @@
1
+ // Where a new application's files come from: the GitHub archive of the starter's latest release (or of its main branch
2
+ // with --dev, or a local archive with --from), unpacked into the new folder. A release archive is what `git archive`
3
+ // writes for the tag, so `export-ignore` in the starter's .gitattributes keeps its own CI out.
4
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { gunzipSync } from 'node:zlib';
7
+ import { ArchiveError, readTar } from './tar.js';
8
+ export const starters = [{ name: 'react', label: 'React, with Inertia and Tailwind CSS', repository: 'mimarjs/mimar' }];
9
+ export const githubHosts = { github: 'https://github.com', codeload: 'https://codeload.github.com' };
10
+ export class StarterError extends Error {
11
+ name = 'StarterError';
12
+ }
13
+ /** The tag of the repository's latest release, read from the redirect GitHub answers, which needs no API token. */
14
+ export async function latestRelease(repository, hosts = githubHosts) {
15
+ const url = `${hosts.github}/${repository}/releases/latest`;
16
+ const response = await request(url, { method: 'HEAD', redirect: 'manual' });
17
+ const location = response.headers.get('location') ?? '';
18
+ const tag = /\/releases\/tag\/([^/?#]+)$/.exec(location)?.[1];
19
+ if (response.status >= 300 && response.status < 400 && tag !== undefined)
20
+ return decodeURIComponent(tag);
21
+ if (response.status >= 300 && response.status < 500) {
22
+ throw new StarterError(`${repository} has no release yet. Pass --dev to start from its main branch.`);
23
+ }
24
+ throw new StarterError(`GitHub answered ${url} with ${response.status}. Try again in a moment.`);
25
+ }
26
+ /** The gzipped archive of a tag (`v0.0.1`) or, with `branch`, of a branch. */
27
+ export async function download(repository, ref, hosts = githubHosts) {
28
+ const path = 'tag' in ref ? `refs/tags/${encodeURIComponent(ref.tag)}` : `refs/heads/${encodeURIComponent(ref.branch)}`;
29
+ const url = `${hosts.codeload}/${repository}/tar.gz/${path}`;
30
+ const response = await request(url);
31
+ if (!response.ok)
32
+ throw new StarterError(`GitHub answered ${url} with ${response.status}.`);
33
+ return new Uint8Array(await response.arrayBuffer());
34
+ }
35
+ /** A gzipped archive from this machine: `--from starter.tar.gz`. */
36
+ export function readArchive(path) {
37
+ try {
38
+ return readFileSync(path);
39
+ }
40
+ catch (error) {
41
+ throw new StarterError(`Cannot read ${path}: ${error.message}`);
42
+ }
43
+ }
44
+ /**
45
+ * Writes the archive's files into `target`, leaving out the archive's top folder (`mimar-0.0.1/`), as a release
46
+ * archive has one. Returns how many files it wrote.
47
+ */
48
+ export function unpack(gzipped, target) {
49
+ let archive;
50
+ try {
51
+ archive = gunzipSync(gzipped);
52
+ }
53
+ catch {
54
+ throw new ArchiveError('The starter archive is not a gzipped tar file.');
55
+ }
56
+ let files = 0;
57
+ for (const entry of readTar(archive)) {
58
+ const parts = entry.path.split('/').filter((part) => part !== '' && part !== '.');
59
+ parts.shift();
60
+ if (parts.length === 0 || entry.type === 'other')
61
+ continue;
62
+ if (parts.some((part) => part === '..' || /[\\:]/.test(part))) {
63
+ throw new ArchiveError(`The starter archive holds the path "${entry.path}", which would be written outside the new folder.`);
64
+ }
65
+ const path = join(target, ...parts);
66
+ if (entry.type === 'symlink')
67
+ throw new ArchiveError(`The starter archive holds a symbolic link, ${parts.join('/')}, which the installer does not create.`);
68
+ if (entry.type === 'directory') {
69
+ mkdirSync(path, { recursive: true });
70
+ continue;
71
+ }
72
+ mkdirSync(dirname(path), { recursive: true });
73
+ writeFileSync(path, entry.data, { mode: entry.mode & 0o111 ? 0o755 : 0o644 });
74
+ files++;
75
+ }
76
+ if (files === 0)
77
+ throw new ArchiveError('The starter archive holds no files.');
78
+ return files;
79
+ }
80
+ async function request(url, init = {}) {
81
+ try {
82
+ return await fetch(url, { ...init, headers: { 'user-agent': 'create-mimar' } });
83
+ }
84
+ catch (error) {
85
+ const cause = error.cause?.message;
86
+ throw new StarterError(`Cannot reach ${new URL(url).host}${cause ? ` (${cause})` : ''}. Check the connection; behind a proxy, set HTTPS_PROXY and NODE_USE_ENV_PROXY=1.`);
87
+ }
88
+ }
package/dist/tar.js ADDED
@@ -0,0 +1,93 @@
1
+ // Reads a tar archive as `git archive` writes it, and so as GitHub serves a release: ustar headers, with pax headers for
2
+ // long paths and a global pax header that holds the commit. GNU long-name headers are read too. Nothing else is needed,
3
+ // so nothing else is supported.
4
+ export class ArchiveError extends Error {
5
+ name = 'ArchiveError';
6
+ }
7
+ const block = 512;
8
+ const decoder = new TextDecoder();
9
+ /** The entries of an uncompressed tar archive, in order. */
10
+ export function* readTar(archive) {
11
+ let offset = 0;
12
+ let paxPath;
13
+ let longName;
14
+ while (offset + block <= archive.length) {
15
+ const header = archive.subarray(offset, offset + block);
16
+ if (header.every((byte) => byte === 0))
17
+ return;
18
+ if (checksum(header) !== octal(header, 148, 8)) {
19
+ throw new ArchiveError(`The archive is damaged: the header at byte ${offset} does not match its checksum.`);
20
+ }
21
+ const size = octal(header, 124, 12);
22
+ const flag = String.fromCharCode(header[156] ?? 0);
23
+ const start = offset + block;
24
+ if (start + size > archive.length)
25
+ throw new ArchiveError('The archive ends in the middle of a file: it was not downloaded whole.');
26
+ const data = archive.subarray(start, start + size);
27
+ offset = start + Math.ceil(size / block) * block;
28
+ if (flag === 'x') {
29
+ paxPath = pax(data).get('path') ?? paxPath;
30
+ continue;
31
+ }
32
+ if (flag === 'g')
33
+ continue;
34
+ if (flag === 'L') {
35
+ longName = text(data);
36
+ continue;
37
+ }
38
+ const prefix = text(header.subarray(345, 500));
39
+ const name = text(header.subarray(0, 100));
40
+ const path = longName ?? paxPath ?? (prefix === '' ? name : `${prefix}/${name}`);
41
+ longName = undefined;
42
+ paxPath = undefined;
43
+ yield { path, type: kind(flag), mode: octal(header, 100, 8) & 0o777, data };
44
+ }
45
+ }
46
+ function kind(flag) {
47
+ if (flag === '0' || flag === '\0' || flag === '7')
48
+ return 'file';
49
+ if (flag === '5')
50
+ return 'directory';
51
+ if (flag === '2')
52
+ return 'symlink';
53
+ return 'other';
54
+ }
55
+ /** The header's checksum: the sum of its bytes, with the checksum field itself counted as spaces. */
56
+ function checksum(header) {
57
+ let sum = 0;
58
+ for (let index = 0; index < block; index++)
59
+ sum += index >= 148 && index < 156 ? 32 : header[index];
60
+ return sum;
61
+ }
62
+ function octal(header, start, length) {
63
+ const field = text(header.subarray(start, start + length)).trim();
64
+ if (field === '')
65
+ return 0;
66
+ if (!/^[0-7]+$/.test(field))
67
+ throw new ArchiveError(`The archive is damaged: "${field}" is not a number.`);
68
+ return Number.parseInt(field, 8);
69
+ }
70
+ /** Text up to the first NUL byte. */
71
+ function text(bytes) {
72
+ const end = bytes.indexOf(0);
73
+ return decoder.decode(end === -1 ? bytes : bytes.subarray(0, end));
74
+ }
75
+ /** A pax header's records: `<length> <key>=<value>\n`, the length counting the whole record. */
76
+ function pax(data) {
77
+ const records = new Map();
78
+ let offset = 0;
79
+ while (offset < data.length) {
80
+ const space = data.indexOf(0x20, offset);
81
+ if (space === -1)
82
+ break;
83
+ const length = Number.parseInt(decoder.decode(data.subarray(offset, space)), 10);
84
+ if (!(length > 0))
85
+ break;
86
+ const record = decoder.decode(data.subarray(space + 1, offset + length - 1));
87
+ const equals = record.indexOf('=');
88
+ if (equals > 0)
89
+ records.set(record.slice(0, equals), record.slice(equals + 1));
90
+ offset += length;
91
+ }
92
+ return records;
93
+ }
package/package.json CHANGED
@@ -1,12 +1,34 @@
1
1
  {
2
- "name": "create-mimar",
3
- "version": "0.0.1-alpha.0",
4
- "description": "Reserved for create-mimar, the installer for Mimar (npx create-mimar@latest my-app). The first alpha, 0.0.1-alpha.1, replaces this placeholder.",
5
- "license": "MIT",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/mimarjs/installer.git"
9
- },
10
- "homepage": "https://github.com/mimarjs/installer",
11
- "files": ["README.md"]
12
- }
2
+ "name": "create-mimar",
3
+ "version": "0.0.1-alpha.1",
4
+ "description": "Create a new Mimar application: npx create-mimar@latest",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mimarjs/installer.git"
9
+ },
10
+ "type": "module",
11
+ "engines": {
12
+ "node": ">=26.14.0"
13
+ },
14
+ "bin": {
15
+ "create-mimar": "./bin/create-mimar.js"
16
+ },
17
+ "files": [
18
+ "bin",
19
+ "dist"
20
+ ],
21
+ "devDependencies": {
22
+ "@biomejs/biome": "^2.6.10",
23
+ "@changesets/cli": "^3.1.0",
24
+ "@types/node": "^26.6.11",
25
+ "typescript": "^7.0.2"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.build.json",
29
+ "check": "biome check . && tsc --noEmit -p tsconfig.json",
30
+ "test": "node --test \"tests/**/*.test.ts\"",
31
+ "format": "biome check --write .",
32
+ "changeset": "changeset"
33
+ }
34
+ }