create-typeser 2.0.0-rc.1 → 2.0.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/README.md CHANGED
@@ -1,46 +1,64 @@
1
- # create-typeser
2
-
3
- The wizard installs the matching TypeSer version as a normal dependency. The release-candidate command is `npm create typeser@next my-app -- --with-demo` after the `next` tag has been published. `--platform-version` accepts an exact version or npm tag. Use `--platform` for a local archive.
4
-
5
- ## Try the unpublished packages
6
-
7
- Run `npm run pack:create` in the TypeSer checkout. If you also need a platform archive, run `npm run pack:release`. Both archives land in `.local/npm-release/`.
8
-
9
- In a separate npm project, install the local initializer once. The following example assumes that this project and the TypeSer checkout are siblings.
10
-
11
- ~~~sh
12
- npm install --no-save ../TypeSer/.local/npm-release/create-typeser-2.0.0-rc.1.tgz
13
- npm create typeser ../my-typeser-app -- --with-demo --platform ../TypeSer/.local/npm-release/typeser-2.0.0-rc.1.tgz
14
- ~~~
15
-
16
- Use the unversioned initializer name for the local test. After public release, `npm create typeser@latest` will select the published initializer. Omit the directory to enter it at the prompt. Pass a local archive with `--platform`. Without that flag the wizard downloads the matching platform version from npm.
17
-
18
- On Windows PowerShell use `npm.cmd` to forward the arguments after `--`. Choose a configuration identifier and whether to connect the Warehouse demo, or supply `--with-demo` / `--no-demo`. The optional demo uses the copy in the platform dependency and its own PostgreSQL schema. QR and MCP modules are included with it.
19
-
20
- For QR graphics, pass `--with-qr` after `--`. For MCP tools, pass `--with-mcp`. The wizard also offers both choices in an interactive terminal. Each module defaults to off and takes its dependency versions from the selected platform archive.
21
-
22
- ## Local setup
23
-
24
- Choose the project directory, JDK 25/26 and PostgreSQL 18+ directories, database port, name, login and password. Press Enter to reuse a detected installation or enter **install** to install a project-local copy under `.local/toolchains/`. Automatic downloads support Windows x64 and Linux x64/arm64. Windows uses the checkout's checksummed OpenJDK and PostgreSQL distributions. Linux uses a checksummed micromamba release and conda-forge packages. Run the wizard as your own OS user.
25
-
26
- **new** creates an isolated loopback cluster under `.local/pgdata/`, bootstraps the database with the installed platform SQL and runs the first Save to PG through the development host. **existing** verifies the login and checks a prepared local TypeSer development database. Choose a database dedicated to this application with its infrastructure schema and runtime role already provisioned. Its first configuration save remains explicit.
27
-
28
- Edit your metadata, app entry, forms and SQL handlers in `solutions/<configuration>/`. The registry and optional `java/pom.xml` belong to your project. On macOS the wizard detects Homebrew and system JDKs. If needed, run `brew install openjdk@25 postgresql@18` and retry.
29
-
30
- The application owns `java/pom.xml`. When adding a Java extension, create its sources under `java/src/main/java/`. Run `mvn package` in `java/` and add the resulting JAR path to `typeser.javaModules.dev` in the application's `package.json`. The POM inherits from the installed platform Maven parent.
31
-
32
- ~~~sh
33
- cd ../my-typeser-app
34
- npm run dev
35
- ~~~
36
-
37
- The development command starts the project database, Java host and three Vite sites for your configuration (nine sites in total when the demo is included). Open the printed application or configurator URL. Press **q** and Enter or Ctrl+C to stop the processes started by that session. An existing database stays running.
38
-
39
- | Command | Result |
40
- | --- | --- |
41
- | `npm run save:ts` | Saves the canonical configuration and form sources. |
42
- | `npm run save:sites` | Generates the per-site configuration and forms under `sites/`. |
43
- | `npm run save:pg` | Publishes the configuration to the registered development schema. |
44
- | `npm run build` | Builds the browser application into the project's `dist/` directory. |
45
-
46
- Run the three save commands in a second terminal while the development host is running. The browser build works with the host stopped. For an interrupted setup, run the same local `npm create typeser` command again with the same project directory.
1
+ # create-typeser
2
+
3
+ The wizard installs the matching TypeSer version as a normal dependency. To create an application with the Warehouse demo from npm, run `npm create typeser my-app -- --with-demo`. `--platform-version` accepts an exact version or npm tag. Use `--platform` for a local archive.
4
+
5
+ ## Try the unpublished packages
6
+
7
+ Run `npm run pack:create` and `npm run pack:release` in the checkout. For binary mode also run `npm run pack:host`. Keep the matching `typeser-java-host-<version>.tgz` beside the local platform archive. Source mode only needs the initializer and platform archives.
8
+
9
+ In a separate npm project, install the local initializer once. The following example assumes that this project and the TypeSer checkout are siblings.
10
+
11
+ ~~~sh
12
+ npm install --no-save ../TypeSer/.local/npm-release/create-typeser-2.0.1.tgz
13
+ npm create typeser ../my-typeser-app -- --with-demo --platform ../TypeSer/.local/npm-release/typeser-2.0.1.tgz
14
+ ~~~
15
+
16
+ Use the unversioned initializer name for the local test. From npm, `npm create typeser` (or `npm create typeser@latest`) selects the published initializer. Omit the directory to enter it at the prompt. Pass a local archive with `--platform`. Without that flag the wizard downloads the matching platform version from npm.
17
+
18
+ On Windows PowerShell use `npm.cmd` to forward the arguments after `--`. Choose a configuration identifier and whether to connect the Warehouse demo, or supply `--with-demo` / `--no-demo`. The optional demo uses the copy in the platform dependency and its own PostgreSQL schema. QR and MCP modules are included with it.
19
+
20
+ For QR graphics, pass `--with-qr` after `--`. For MCP tools, pass `--with-mcp`. The wizard also offers both choices in an interactive terminal. Each module defaults to off and takes its dependency versions from the selected platform archive.
21
+
22
+ ## Java host
23
+
24
+ Choose `binary` (default) for the prebuilt `@typeser/java-host` or `source` to compile the platform and your own Java code. For a source installation with the Warehouse demo, run `npm create typeser@latest my-app -- --java-host source --with-demo`. The first Save to PG uses the selected host. `npm run dev` uses it again.
25
+
26
+ In source mode add classes to `java/src/main/java/` and resources to `java/src/main/resources/`. The project owns its Maven POM. Its Maven Wrapper verifies the Maven distribution with SHA-256. The first build downloads Maven and its dependencies. The launcher compiles into `.local/java-host/` and starts `p.App` from the classpath. Restart after Java changes.
27
+
28
+ ## Local setup
29
+
30
+ Choose the project directory, JDK 21–26 and PostgreSQL 18+ directories, database port, name, login and password. Press Enter to reuse a detected installation or enter **install** to install a project-local copy under `.local/toolchains/`. Automatic downloads support Windows x64 and Linux x64/arm64. Windows uses the checkout's checksummed OpenJDK and PostgreSQL distributions. Linux uses a checksummed micromamba release and conda-forge packages. Run the wizard as your own OS user.
31
+
32
+ When you select **install**, choose the download for each tool separately. **verified** uses the bundled pin. **latest** checks stable JDK 26 or PostgreSQL 18 builds and shows the exact version before download. If discovery is unavailable or finds no newer build, setup uses the verified version. The project saves the version, checksum and archive URL or exact conda build in `.local/create-typeser.json` for retries. Existing installations follow their selected directories.
33
+
34
+ | Database mode | When to choose it | First Save to PG |
35
+ | --- | --- | --- |
36
+ | `new` | Let the project initialize and manage a cluster under `.local/pgdata/`. | Automatic for the application and the selected demo. |
37
+ | `server` | Create a dedicated database on a running local PostgreSQL 18+ service. | Automatic for the application and the selected demo. |
38
+ | `existing` | Attach to a prepared TypeSer development database using its application login. | Run explicitly when needed. |
39
+
40
+ For **server** and **existing**, the selected directory only needs the PostgreSQL 18+ client (`psql`). In **server** mode, enter the loopback host, port (usually `5432`), an unused database name and the administrator login and password (press Enter for trust authentication). On macOS the default login is the OS user; elsewhere it is `postgres`. The wizard creates the database and a dedicated application login, provisions or verifies the shared `r1_runtime` role, and runs the bootstrap as the application login. The plan retains the administrator login for retries. The administrator password is discarded after provisioning. The PostgreSQL service keeps running when the wizard or development session exits.
41
+
42
+ If setup is interrupted, rerun the same command in the parent directory and supply the administrator password again. The wizard recognizes its own database and skips committed publications. A project already created in another database mode keeps that choice. To try `server` after an interrupted `new` setup, choose a fresh project directory.
43
+
44
+ Edit your metadata, app entry, forms and SQL handlers in `solutions/<configuration>/`. The registry and optional `java/pom.xml` belong to your project. On macOS the wizard detects Homebrew and system JDKs. If needed, run `brew install openjdk@21 postgresql@18` and retry.
45
+
46
+ In binary mode the application owns `java/pom.xml`. When adding a Java extension, create its sources under `java/src/main/java/`. Run `mvn package` in `java/` and add the resulting JAR path to `typeser.javaModules.dev` in the application's `package.json`. The POM inherits from the installed platform Maven parent.
47
+
48
+ ~~~sh
49
+ cd ../my-typeser-app
50
+ npm run dev
51
+ ~~~
52
+
53
+ The development command starts the project database, Java host and three Vite sites for your configuration (nine sites in total when the demo is included). Open the printed application or configurator URL. Press **q** and Enter or Ctrl+C to stop the processes started by that session. An existing database stays running.
54
+
55
+ | Command | Result |
56
+ | --- | --- |
57
+ | `npm run save:ts` | Saves the canonical configuration and form sources. |
58
+ | `npm run save:sites` | Generates the per-site configuration and forms under `sites/`. |
59
+ | `npm run save:pg` | Publishes the configuration to the registered development schema. |
60
+ | `npm run build` | Builds the browser application into the project's `dist/` directory. |
61
+
62
+ Run the three save commands in a second terminal while the development host is running. The browser build works with the host stopped. For an interrupted setup, run the same local `npm create typeser` command again with the same project directory.
63
+
64
+ Source builds on minimal Linux require `unzip` for the checksummed Maven distribution. On Windows choose a project path without apostrophes or closing parentheses. After stopping all project hosts and builds, run the wrapper’s `clean` goal from `java/` to clear cached builds and receipts.
@@ -1,169 +1,206 @@
1
- #!/usr/bin/env node
2
- import {execFileSync} from 'node:child_process';
3
- import {existsSync, renameSync} from 'node:fs';
4
- import {createServer} from 'node:net';
5
- import {createRequire} from 'node:module';
6
- import path from 'node:path';
7
- import {parseArgs} from 'node:util';
8
- import {assignedOffsets, registryPlatform, assertAvailable, freePort, inspectArchive, physicalPath, portBase, readJson, scaffold, writeJson} from '../lib/project.mjs';
9
- import {questions} from '../lib/questions.mjs';
10
- import {detectedBin, resolveTool, selectedBin} from '../lib/tools.mjs';
11
- import {prepareDatabase} from '../lib/prepare-database.mjs';
12
-
13
- function dbName(value) {
14
- if (!/^[a-z][a-z0-9_]{0,62}$/.test(value) || ['postgres', 'template0', 'template1'].includes(value))
15
- throw new Error('Use a lowercase application database name with letters, digits and underscores.');
16
- return value;
17
- }
18
-
19
- function dbPassword(value) {
20
- if (!value.trim() || /[\0\r\n]/.test(value) || /^<[^>]+>$/.test(value))
21
- throw new Error('Enter a nonblank database password on one line.');
22
- return value;
23
- }
24
-
25
- async function newProject(ui, root, archive, options) {
26
- const slug = path.basename(root).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
27
- const name = slug && slug !== 'typeser' ? slug : 'typeser-app';
28
- const reserved = new Set(["app", "public", "information_schema", "demo_typeser", "empty_template"]);
29
- let schema = name.replaceAll('-', '_');
30
- if (!/^[a-z]/.test(schema) || reserved.has(schema) || schema.startsWith('pg_')) schema = 'ts_' + schema;
31
- schema = await ui.ask('Configuration name (also the PostgreSQL schema)', schema.slice(0, 63), {check: value => {
32
- if (!/^[a-z][a-z0-9_]{0,62}$/.test(value) || reserved.has(value) || value.startsWith('pg_'))
33
- throw new Error('Use a unique lowercase identifier of 1–63 letters, digits and underscores, starting with a letter.');
34
- return value;
35
- }});
36
- const withDemo = options['with-demo'] || (!options['no-demo'] && await ui.confirm('the TypeSer demo (demo_typeser)'));
37
- const plan = {format: 1, name, schema, withDemo, base: await portBase(root, withDemo)};
38
- for (const [flag, label] of [['with-qr', 'QR codes in printed documents'], ['with-mcp', 'Model Context Protocol integrations']]) {
39
- plan[flag] = withDemo || (options[flag] ?? (process.stdin.isTTY ? await ui.confirm(label) : false));
40
- }
41
- for (const [tool, label] of [['java', 'JDK 25/26 directory'], ['postgresql', 'PostgreSQL 18+ bin directory']]) {
42
- const mac = process.platform === 'darwin';
43
- plan[tool] = await ui.ask(label + (mac ? ' (Homebrew or existing installation)' : ' (or install)'), detectedBin(tool) || (mac ? '' : 'install'), {check: value => selectedBin(tool, value)});
44
- }
45
- plan.mode = await ui.ask('Database mode (new project cluster / existing prepared database)', 'new', {check: value => {
46
- if (!['new', 'existing'].includes(value)) throw new Error('Enter new or existing.');
47
- return value;
48
- }});
49
- plan.host = plan.mode === 'new' ? '127.0.0.1' : await ui.ask('Local database host', '127.0.0.1', {check: value => {
50
- if (!['localhost', '127.0.0.1', '::1'].includes(value)) throw new Error('Use a loopback address for local development.');
51
- return value;
52
- }});
53
- plan.port = await ui.ask('PostgreSQL port', String(plan.mode === 'new' ? plan.base + 40 : 5432), {check: value => {
54
- if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw new Error('Enter a TCP port from 1 to 65535.');
55
- const port = Number(value);
56
- if (assignedOffsets(withDemo).includes(port - plan.base)) throw new Error('This port is reserved for TypeSer.');
57
- return port;
58
- }});
59
- if (plan.mode === 'new' && !await freePort(plan.port)) throw new Error('The PostgreSQL port is already in use: ' + plan.port);
60
- if (plan.mode === 'new' && process.getuid?.() === 0) throw new Error('Run as the desktop user. PostgreSQL cannot initialize a cluster as root.');
61
- plan.database = await ui.ask('Database name', ['postgres', 'template0', 'template1'].includes(plan.schema) ? 'typeser_app' : plan.schema, {check: dbName});
62
- plan.user = await ui.ask('Database user', plan.mode === 'new' ? 'typeser_owner' : 'postgres', {check: value => {
63
- if (value.includes('\0') || value.length > 63 || value === 'r1_runtime' || value.startsWith('pg_'))
64
- throw new Error('Enter a PostgreSQL login role.');
65
- return value;
66
- }});
67
- const password = await ui.ask(plan.mode === 'new' ? 'Set the password for the new database user (hidden)' : 'Existing database password (hidden)',
68
- '', {secret: true, check: dbPassword});
69
- ui.close();
70
- scaffold(root, archive, plan, password);
71
- }
72
-
73
- async function finishSetup(root, updatedPassword) {
74
- const state = path.join(root, '.local/create-typeser.json');
75
- const plan = readJson(state);
76
- if (plan.format !== 1 || !existsSync(path.join(root, 'node_modules/typeser/bin/typeser.mjs')))
77
- throw new Error('This directory is not an initialized TypeSer application.');
78
- if (plan.ready) return;
79
- const require = createRequire(path.join(root, 'package.json'));
80
- // A setup interrupted with the previous initializer already has these helpers in the application.
81
- const platform = readJson(path.join(root, 'node_modules/typeser/package.json'));
82
- const runtime = platform.exports?.['./local-runtime'] ? require('typeser/local-runtime') :
83
- {...require('./scripts/database.mjs'), ...require('./scripts/host.mjs')};
84
- // The OS releases the setup lock even if an npm process is interrupted.
85
- const lock = createServer(socket => socket.destroy());
86
- await new Promise((resolve, reject) => {
87
- lock.once('error', error => reject(error.code === 'EADDRINUSE'
88
- ? new Error('The project setup port is busy. Close the other setup and try again.') : error));
89
- lock.listen(plan.base + 39, '127.0.0.1', resolve);
90
- });
91
- let started, host;
92
- let cancelled = false;
93
- const cancel = () => { cancelled = true; };
94
- const checkCancelled = () => { if (cancelled) throw new Error('Setup interrupted. Run the same command to continue.'); };
95
- process.once('SIGINT', cancel);
96
- process.once('SIGTERM', cancel);
97
- try {
98
- if (updatedPassword && plan.mode === 'existing') {
99
- const file = physicalPath(path.join(root, 'secrets/dev-secrets.json'));
100
- const secret = readJson(file);
101
- secret.TYPESER_DATABASE_PASSWORD = updatedPassword;
102
- writeJson(file + '.next', secret);
103
- renameSync(file + '.next', file);
104
- }
105
- const javaBin = await resolveTool(root, 'java', plan.java);
106
- const pgBin = await resolveTool(root, 'postgresql', plan.postgresql);
107
- plan.javaHome = plan.java === 'install' && process.platform !== 'darwin' ? path.relative(root, path.dirname(javaBin)) : path.dirname(javaBin);
108
- plan.pgBin = plan.postgresql === 'install' && process.platform !== 'darwin' ? path.relative(root, pgBin) : pgBin;
109
- checkCancelled();
110
- console.log('Checking PostgreSQL at ' + plan.host + ':' + plan.port + '/' + plan.database + '...');
111
- started = prepareDatabase(root, plan, runtime);
112
- if (plan.mode === 'new') {
113
- console.log('Starting the Java host for the first Save to PG...');
114
- host = await runtime.startHost(root, plan, readJson(path.join(root, 'typeser-apps.json')));
115
- checkCancelled();
116
- for (const schema of plan.withDemo ? [plan.schema, 'demo_typeser'] : [plan.schema]) {
117
- if ((host.pgBySchema?.[schema] ?? host.pg) > 0) continue;
118
- const cli = path.join(root, 'node_modules/typeser/bin/typeser.mjs');
119
- const output = execFileSync(process.execPath, [cli, 'save-to-pg', 'dev', schema],
120
- {cwd: root, encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'inherit']});
121
- const outcome = JSON.parse(output);
122
- if (outcome.publication_outcome !== 'committed') throw new Error('First Save to PG returned ' + outcome.publication_outcome);
123
- console.log('First Save to PG committed for ' + schema + '.');
124
- }
125
- }
126
- plan.ready = true;
127
- writeJson(state + '.next', plan);
128
- renameSync(state + '.next', state);
129
- } finally {
130
- process.off('SIGINT', cancel);
131
- process.off('SIGTERM', cancel);
132
- try { await host?.stop(); } finally { try { if (started) runtime.stopDatabase(root, plan); } finally { lock.close(); } }
133
- }
134
- }
135
-
136
- async function main() {
137
- const {values, positionals} = parseArgs({allowPositionals: true, options: {help: {type: 'boolean', short: 'h'}, platform: {type: 'string'}, 'platform-version': {type: 'string'}, 'with-demo': {type: 'boolean'}, 'no-demo': {type: 'boolean'}, 'with-qr': {type: 'boolean'}, 'with-mcp': {type: 'boolean'}}});
138
- if (values.help) { console.log('npm create typeser [directory] -- [--platform <local-typeser.tgz> | --platform-version <version>] [--with-demo | --no-demo] [--with-qr] [--with-mcp]'); return; }
139
- if ((values['with-demo'] && values['no-demo']) || (values.platform && values['platform-version'])) throw new Error('Choose one source and one demo option.');
140
- if (positionals.length > 1) throw new Error('Expected one application directory. Use --help for the command.');
141
- let ui;
142
- let root, updatedPassword;
143
- try {
144
- if (!positionals[0]) ui = questions();
145
- root = physicalPath(positionals[0] || await ui.ask('Application directory', 'my-typeser-app'));
146
- const state = physicalPath(path.join(root, '.local/create-typeser.json'));
147
- if (existsSync(state)) {
148
- const plan = readJson(state);
149
- if (plan.format === 1 && !plan.ready && plan.mode === 'existing') {
150
- ui ??= questions();
151
- updatedPassword = await ui.ask('Existing database password (hidden)', '', {secret: true, check: dbPassword});
152
- }
153
- } else {
154
- assertAvailable(root);
155
- ui ??= questions();
156
- const archive = values.platform ? inspectArchive(values.platform) :
157
- registryPlatform(values['platform-version'] ?? readJson(new URL('../package.json', import.meta.url)).version);
158
- await newProject(ui, root, archive, values);
159
- }
160
- } finally { ui?.close(); }
161
- try { await finishSetup(root, updatedPassword); }
162
- catch (error) {
163
- console.error('After correcting the issue, run npm create typeser again with the same directory: ' + root);
164
- throw error;
165
- }
166
- console.log('\nApplication ready at ' + root + '\nOpen a terminal there and run npm run dev.');
167
- }
168
-
169
- main().catch(error => { console.error(error.message); process.exitCode = 1; });
1
+ #!/usr/bin/env node
2
+ import {execFileSync} from 'node:child_process';
3
+ import {randomBytes, randomUUID} from 'node:crypto';
4
+ import {existsSync, renameSync} from 'node:fs';
5
+ import {createServer} from 'node:net';
6
+ import {createRequire} from 'node:module';
7
+ import {userInfo} from 'node:os';
8
+ import path from 'node:path';
9
+ import {parseArgs} from 'node:util';
10
+ import {assignedOffsets, registryPlatform, assertAvailable, freePort, inspectArchive, physicalPath, portBase, readJson, scaffold, writeJson} from '../lib/project.mjs';
11
+ import {chooseArtifact} from '../lib/install-versions.mjs';
12
+ import {questions} from '../lib/questions.mjs';
13
+ import {detectedBin, resolveTool, selectedBin} from '../lib/tools.mjs';
14
+ import {prepareDatabase} from '../lib/prepare-database.mjs';
15
+
16
+ function dbName(value) {
17
+ if (!/^[a-z][a-z0-9_]{0,62}$/.test(value) || ['postgres', 'template0', 'template1'].includes(value))
18
+ throw new Error('Use a lowercase application database name with letters, digits and underscores.');
19
+ return value;
20
+ }
21
+
22
+ function dbPassword(value) {
23
+ if (!value.trim() || /[\0\r\n]/.test(value) || /^<[^>]+>$/.test(value))
24
+ throw new Error('Enter a nonblank database password on one line.');
25
+ return value;
26
+ }
27
+
28
+ function askPostgresPassword(ui, user = 'postgres') {
29
+ return ui.ask('Password for ' + user + ' (hidden, Enter for trust)', '', {secret: true, allowEmpty: true, check: value => {
30
+ if (/[\0\r\n]/.test(value)) throw new Error('Enter the postgres password on one line.');
31
+ return value;
32
+ }});
33
+ }
34
+
35
+ async function newProject(ui, root, archive, options) {
36
+ const slug = path.basename(root).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
37
+ const name = slug && slug !== 'typeser' ? slug : 'typeser-app';
38
+ const reserved = new Set(["app", "public", "information_schema", "demo_typeser", "empty_template"]);
39
+ let schema = name.replaceAll('-', '_');
40
+ if (!/^[a-z]/.test(schema) || reserved.has(schema) || schema.startsWith('pg_')) schema = 'ts_' + schema;
41
+ schema = await ui.ask('Configuration name (also the PostgreSQL schema)', schema.slice(0, 63), {check: value => {
42
+ if (!/^[a-z][a-z0-9_]{0,62}$/.test(value) || reserved.has(value) || value.startsWith('pg_'))
43
+ throw new Error('Use a unique lowercase identifier of 1–63 letters, digits and underscores, starting with a letter.');
44
+ return value;
45
+ }});
46
+ const withDemo = options['with-demo'] || (!options['no-demo'] && await ui.confirm('the TypeSer demo (demo_typeser)'));
47
+ const plan = {format: 1, name, schema, withDemo, base: await portBase(root, withDemo)};
48
+ const hostMode = value => {
49
+ if (!['binary', 'source'].includes(value)) throw new Error('Choose binary or source for the Java host.');
50
+ return value;
51
+ };
52
+ plan.javaHost = options['java-host'] ? hostMode(options['java-host']) : archive.typeserHost && process.stdin.isTTY
53
+ ? await ui.ask('Java host (binary = prebuilt / source = compile with Maven Wrapper)', 'binary', {check: hostMode}) : 'binary';
54
+ if (plan.javaHost === 'source' && !archive.typeserHost) throw new Error('Source mode requires a platform release with typeserHost.');
55
+ for (const [flag, label] of [['with-qr', 'QR codes in printed documents'], ['with-mcp', 'Model Context Protocol integrations']]) {
56
+ plan[flag] = withDemo || (options[flag] ?? (process.stdin.isTTY ? await ui.confirm(label) : false));
57
+ }
58
+ for (const [tool, label] of [['java', 'JDK 21–26 directory'], ['postgresql', 'PostgreSQL 18+ bin directory']]) {
59
+ const mac = process.platform === 'darwin';
60
+ plan[tool] = await ui.ask(label + (mac ? ' (Homebrew or existing installation)' : ' (or install)'), detectedBin(tool) || (mac ? '' : 'install'), {check: value => selectedBin(tool, value, tool === 'postgresql')});
61
+ if (plan[tool] === 'install') {
62
+ plan.toolArtifacts ??= {};
63
+ plan.toolArtifacts[tool] = await chooseArtifact(ui, tool);
64
+ }
65
+ }
66
+ const mode = await ui.ask('Database mode (new = project cluster / server = create a database on running PostgreSQL / existing = attach a prepared database)', 'new', {check: value => {
67
+ if (!['new', 'server', 'existing'].includes(value)) throw new Error('Enter new, server or existing.');
68
+ return value;
69
+ }});
70
+ // The installed application treats a provisioned database as externally managed, also on 2.0.0.
71
+ plan.mode = mode === 'server' ? 'existing' : mode;
72
+ if (mode === 'new') selectedBin('postgresql', plan.postgresql);
73
+ plan.host = plan.mode === 'new' ? '127.0.0.1' : await ui.ask('Local database host', '127.0.0.1', {check: value => {
74
+ if (!['localhost', '127.0.0.1', '::1'].includes(value)) throw new Error('Use a loopback address for local development.');
75
+ return value;
76
+ }});
77
+ plan.port = await ui.ask('PostgreSQL port', String(plan.mode === 'new' ? plan.base + 40 : 5432), {check: value => {
78
+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw new Error('Enter a TCP port from 1 to 65535.');
79
+ const port = Number(value);
80
+ if (assignedOffsets(withDemo).includes(port - plan.base)) throw new Error('This port is reserved for TypeSer.');
81
+ return port;
82
+ }});
83
+ if (plan.mode === 'new' && !await freePort(plan.port)) throw new Error('The PostgreSQL port is already in use: ' + plan.port);
84
+ if (plan.mode === 'new' && process.getuid?.() === 0) throw new Error('Run as the desktop user. PostgreSQL cannot initialize a cluster as root.');
85
+ plan.database = await ui.ask('Database name', ['postgres', 'template0', 'template1'].includes(plan.schema) ? 'typeser_app' : plan.schema, {check: dbName});
86
+ if (mode === 'server') {
87
+ plan.provisionId = randomUUID();
88
+ plan.user = 'ts_' + plan.database.slice(0, 32) + '_' + plan.provisionId.slice(0, 8);
89
+ plan.adminUser = await ui.ask('PostgreSQL administrator', process.platform === 'darwin' ? userInfo().username : 'postgres', {check: value => {
90
+ if (/[\0\r\n]/.test(value) || Buffer.byteLength(value) > 63) throw new Error('Enter a PostgreSQL login role.');
91
+ return value;
92
+ }});
93
+ const adminPassword = await askPostgresPassword(ui, plan.adminUser);
94
+ ui.close();
95
+ scaffold(root, archive, plan, randomBytes(32).toString('hex'));
96
+ return adminPassword;
97
+ }
98
+ plan.user = await ui.ask('Database user', plan.mode === 'new' ? 'typeser_owner' : 'postgres', {check: value => {
99
+ if (value.includes('\0') || value.length > 63 || value === 'r1_runtime' || value.startsWith('pg_'))
100
+ throw new Error('Enter a PostgreSQL login role.');
101
+ return value;
102
+ }});
103
+ const password = await ui.ask(plan.mode === 'new' ? 'Set the password for the new database user (hidden)' : 'Existing database password (hidden)',
104
+ '', {secret: true, check: dbPassword});
105
+ ui.close();
106
+ scaffold(root, archive, plan, password);
107
+ }
108
+
109
+ async function finishSetup(root, setupPassword) {
110
+ const state = path.join(root, '.local/create-typeser.json');
111
+ const plan = readJson(state);
112
+ if (plan.format !== 1 || !existsSync(path.join(root, 'node_modules/typeser/bin/typeser.mjs')))
113
+ throw new Error('This directory is not an initialized TypeSer application.');
114
+ if (plan.ready) return;
115
+ const require = createRequire(path.join(root, 'package.json'));
116
+ // A setup interrupted with the previous initializer already has these helpers in the application.
117
+ const platform = readJson(path.join(root, 'node_modules/typeser/package.json'));
118
+ const runtime = platform.exports?.['./local-runtime'] ? require('typeser/local-runtime') :
119
+ {...require('./scripts/database.mjs'), ...require('./scripts/host.mjs')};
120
+ // The OS releases the setup lock even if an npm process is interrupted.
121
+ const lock = createServer(socket => socket.destroy());
122
+ await new Promise((resolve, reject) => {
123
+ lock.once('error', error => reject(error.code === 'EADDRINUSE'
124
+ ? new Error('The project setup port is busy. Close the other setup and try again.') : error));
125
+ lock.listen(plan.base + 39, '127.0.0.1', resolve);
126
+ });
127
+ let started, host;
128
+ let cancelled = false;
129
+ const cancel = () => { cancelled = true; };
130
+ const checkCancelled = () => { if (cancelled) throw new Error('Setup interrupted. Run the same command to continue.'); };
131
+ process.once('SIGINT', cancel);
132
+ process.once('SIGTERM', cancel);
133
+ try {
134
+ if (setupPassword && plan.mode === 'existing' && !plan.provisionId) {
135
+ const file = physicalPath(path.join(root, 'secrets/dev-secrets.json'));
136
+ const secret = readJson(file);
137
+ secret.TYPESER_DATABASE_PASSWORD = setupPassword;
138
+ writeJson(file + '.next', secret);
139
+ renameSync(file + '.next', file);
140
+ }
141
+ const javaBin = await resolveTool(root, 'java', plan.java, false, plan.toolArtifacts?.java);
142
+ const pgBin = await resolveTool(root, 'postgresql', plan.postgresql, plan.mode !== 'new', plan.toolArtifacts?.postgresql);
143
+ plan.javaHome = plan.java === 'install' && process.platform !== 'darwin' ? path.relative(root, path.dirname(javaBin)) : path.dirname(javaBin);
144
+ plan.pgBin = plan.postgresql === 'install' && process.platform !== 'darwin' ? path.relative(root, pgBin) : pgBin;
145
+ checkCancelled();
146
+ console.log('Checking PostgreSQL at ' + plan.host + ':' + plan.port + '/' + plan.database + '...');
147
+ started = prepareDatabase(root, plan, runtime, setupPassword);
148
+ if (plan.mode === 'new' || plan.provisionId) {
149
+ console.log('Starting the Java host for the first Save to PG...');
150
+ host = await runtime.startHost(root, plan, readJson(path.join(root, 'typeser-apps.json')));
151
+ checkCancelled();
152
+ for (const schema of plan.withDemo ? [plan.schema, 'demo_typeser'] : [plan.schema]) {
153
+ if ((host.pgBySchema?.[schema] ?? host.pg) > 0) continue;
154
+ const cli = path.join(root, 'node_modules/typeser/bin/typeser.mjs');
155
+ const output = execFileSync(process.execPath, [cli, 'save-to-pg', 'dev', schema],
156
+ {cwd: root, encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'inherit']});
157
+ const outcome = JSON.parse(output);
158
+ if (outcome.publication_outcome !== 'committed') throw new Error('First Save to PG returned ' + outcome.publication_outcome);
159
+ console.log('First Save to PG committed for ' + schema + '.');
160
+ }
161
+ }
162
+ plan.ready = true;
163
+ writeJson(state + '.next', plan);
164
+ renameSync(state + '.next', state);
165
+ } finally {
166
+ process.off('SIGINT', cancel);
167
+ process.off('SIGTERM', cancel);
168
+ try { await host?.stop(); } finally { try { if (started) runtime.stopDatabase(root, plan); } finally { lock.close(); } }
169
+ }
170
+ }
171
+
172
+ async function main() {
173
+ const {values, positionals} = parseArgs({allowPositionals: true, options: {help: {type: 'boolean', short: 'h'}, platform: {type: 'string'}, 'platform-version': {type: 'string'}, 'java-host': {type: 'string'}, 'with-demo': {type: 'boolean'}, 'no-demo': {type: 'boolean'}, 'with-qr': {type: 'boolean'}, 'with-mcp': {type: 'boolean'}}});
174
+ if (values.help) { console.log('npm create typeser [directory] -- [--platform <local-typeser.tgz> | --platform-version <version>] [--java-host binary|source] [--with-demo | --no-demo] [--with-qr] [--with-mcp]'); return; }
175
+ if ((values['with-demo'] && values['no-demo']) || (values.platform && values['platform-version'])) throw new Error('Choose one source and one demo option.');
176
+ if (positionals.length > 1) throw new Error('Expected one application directory. Use --help for the command.');
177
+ let ui;
178
+ let root, setupPassword;
179
+ try {
180
+ if (!positionals[0]) ui = questions();
181
+ root = physicalPath(positionals[0] || await ui.ask('Application directory', 'my-typeser-app'));
182
+ const state = physicalPath(path.join(root, '.local/create-typeser.json'));
183
+ if (existsSync(state)) {
184
+ const plan = readJson(state);
185
+ if (plan.format === 1 && !plan.ready && plan.mode === 'existing') {
186
+ ui ??= questions();
187
+ setupPassword = plan.provisionId ? await askPostgresPassword(ui, plan.adminUser) :
188
+ await ui.ask('Existing database password (hidden)', '', {secret: true, check: dbPassword});
189
+ }
190
+ } else {
191
+ assertAvailable(root);
192
+ ui ??= questions();
193
+ const archive = values.platform ? inspectArchive(values.platform) :
194
+ registryPlatform(values['platform-version'] ?? readJson(new URL('../package.json', import.meta.url)).version);
195
+ setupPassword = await newProject(ui, root, archive, values);
196
+ }
197
+ } finally { ui?.close(); }
198
+ try { await finishSetup(root, setupPassword); }
199
+ catch (error) {
200
+ console.error('After correcting the issue, run npm create typeser again with the same directory: ' + root);
201
+ throw error;
202
+ }
203
+ console.log('\nApplication ready at ' + root + '\nOpen a terminal there and run npm run dev.');
204
+ }
205
+
206
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });