create-shopnex 0.0.0-edge.c8ad7df → 0.0.0-edge.e014713

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +36 -16
  2. package/dist/main.mjs +117 -32
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -3,6 +3,9 @@
3
3
  Try ShopNex on your machine with one command. It starts the admin (with the API and hosted checkout) and the
4
4
  storefront on an embedded database ([PGlite](https://pglite.dev)): no PostgreSQL, no Docker, no clone.
5
5
 
6
+ New here? Read [Getting started](getting-started/README.md) first: a short walk-through from the first command to a
7
+ running shop. This page is the full reference.
8
+
6
9
  ## Run it
7
10
 
8
11
  ```sh
@@ -23,6 +26,18 @@ The first run downloads ShopNex (one file, about 15 MB) into `~/.shopnex/app/<ve
23
26
  runs start straight away. It prints where to open the shop and the admin and opens the admin's setup wizard (use
24
27
  `--no-open` to skip that). Ctrl+C stops everything. Nothing is installed globally.
25
28
 
29
+ ## Run it again
30
+
31
+ The shop folder has a `package.json`, so from inside it:
32
+
33
+ ```sh
34
+ cd shopnex
35
+ npm start # or: npm run dev
36
+ ```
37
+
38
+ No `npm install` first: both scripts run `npx --yes create-shopnex@<version> .`, the version that made the folder, and
39
+ npx fetches it into its cache the first time. The same works from the folder above: `npx create-shopnex@latest shopnex`.
40
+
26
41
  ## What it does, and why you can trust it
27
42
 
28
43
  - **It runs on your machine only.** Both servers listen on `127.0.0.1`, and the data stays in the shop folder (`shopnex/data` by default).
@@ -41,24 +56,29 @@ runs start straight away. It prints where to open the shop and the admin and ope
41
56
 
42
57
  ## Options
43
58
 
44
- | Option | What it does |
45
- | ----------------------- | --------------------------------------------------------------------------------------------------------- |
46
- | `[name]` | The shop's folder, created if needed. `shopnex` when left out; the same folder is the same shop |
47
- | `--port <n>` | Admin, API and checkout. Default `3000` |
48
- | `--storefront-port <n>` | Storefront. Default `4321` |
49
- | `--no-open` | Do not open the browser |
50
- | `--with <apps>` | Also start optional apps next to the shop: `stripe`, `cj`, `shippo` (comma separated, or repeat the flag) |
51
- | `--app <name>` | What to start. Only `shop` today; a picker appears once there is more than one |
52
- | `--verbose` | Show the servers' output while they start (otherwise only if one fails) |
53
- | `--dry-run` | Show what would run, and exit |
59
+ | Option | What it does |
60
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
61
+ | `[name]` | The shop's folder, created if needed. `shopnex` when left out; the same folder is the same shop |
62
+ | `--port <n>` | Admin, API and checkout. Default `3000` |
63
+ | `--storefront-port <n>` | Storefront. Default `4321` |
64
+ | `--no-open` | Do not open the browser |
65
+ | `--with <apps>` | Start only these apps: `stripe`, `cj`, `shippo`, `reviews` (comma separated, or repeat the flag). All four start by default |
66
+ | `--no-apps` | Start the shop alone, without the bundled apps |
67
+ | `--from <store>` | Bring a Shopify or WooCommerce store across: products, collections, pages and the look. It starts after you create the owner in the browser |
68
+ | `--app <name>` | What to start. Only `shop` today; a picker appears once there is more than one |
69
+ | `--verbose` | Show the servers' output while they start (otherwise only if one fails) |
70
+ | `--dry-run` | Show what would run, and exit |
71
+
72
+ ## Apps: Stripe, CJ Dropshipping, Shippo and Reviews
54
73
 
55
- ## Apps: Stripe, CJ Dropshipping and Shippo
74
+ All the bundled apps start by default. Pick some, or none:
56
75
 
57
76
  ```sh
58
- npx create-shopnex@latest --with stripe,cj,shippo
77
+ npx create-shopnex@latest --with stripe,reviews # only these
78
+ npx create-shopnex@latest --no-apps # the shop alone
59
79
  ```
60
80
 
61
- Each app runs as its own small server on this machine only (Stripe on port 4600, CJ Dropshipping on 4700, Shippo on 4900) and keeps
81
+ Each app runs as its own small server on this machine only (Stripe on port 4600, CJ Dropshipping on 4700, Shippo on 4900, Reviews on 5100) and keeps
62
82
  its data in `<shop folder>/apps/`. The admin finds them by itself; install them from the admin like any app and enter
63
83
  your keys there. Stripe cannot reach a `localhost` address, so card payments need a public address for the app or
64
84
  `stripe listen`: see the Stripe app's settings page.
@@ -73,13 +93,13 @@ SHOPNEX_SECRET=<generated once> # encrypts the provider keys saved in the admi
73
93
  ```
74
94
 
75
95
  - **PostgreSQL:** set `DATABASE_URL=postgres://user:password@host:5432/shopnex` and start again. The migrations are applied
76
- on start (`SHOPNEX_AUTO_MIGRATE`). The data in `.pglite/` is not moved (there is no tool for that yet).
96
+ on start (`SHOPNEX_AUTO_MIGRATE`). To move the data from `.pglite/`, run `npx shopnex migrate-db` (see [Getting started](getting-started/README.md)).
77
97
  - **Other settings** in the file (SMTP, and so on) are passed to the admin. The address, the ports and the build's own
78
98
  files are set by the CLI and its flags and win over the file.
79
99
  - Do not commit or share it. Without `SHOPNEX_SECRET` the saved provider keys cannot be read: a lost one means a new
80
100
  shop.
81
101
 
82
- The first run also writes a `.gitignore` (keeps `.env`, `.pglite/` and the apps' keys out of git) and the
102
+ The first run also writes a `README.md` (how to run the shop again), a `package.json` (for `npm start`), a `.gitignore` (keeps `.env`, `.pglite/` and the apps' keys out of git) and the
83
103
  `docker-compose.yml` (fetched from the repository, the file the [self-hosting docs](https://shopnex.ai/docs/self-hosting/docker) describe: ShopNex, the Stripe
84
104
  app and PostgreSQL from prebuilt images), for when the shop should run in Docker instead. Existing files are never
85
105
  overwritten.
@@ -89,7 +109,7 @@ To start over, delete the shop folder.
89
109
  ## Not for production
90
110
 
91
111
  One process owns the data, so nothing else can open the folder, and the servers listen on `127.0.0.1` only. Use
92
- Docker or PostgreSQL for a real shop. There is no tool yet to move the data from the embedded database to PostgreSQL.
112
+ Docker or PostgreSQL for a real shop, and move the data with `npx shopnex migrate-db`.
93
113
 
94
114
  ## Where the build comes from
95
115
 
package/dist/main.mjs CHANGED
@@ -40,7 +40,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
40
40
  var define_PKG_default;
41
41
  var init_define_PKG = __esm({
42
42
  "<define:__PKG__>"() {
43
- define_PKG_default = { version: "0.0.0-edge.c8ad7df", engines: { node: ">=22.22.0" } };
43
+ define_PKG_default = { version: "0.0.0-edge.e014713", engines: { node: ">=22.22.0" } };
44
44
  }
45
45
  });
46
46
 
@@ -678,7 +678,7 @@ function me() {
678
678
  init_define_PKG();
679
679
  import { parseArgs } from "node:util";
680
680
 
681
- // src/errors.ts
681
+ // ../cli-core/src/errors.ts
682
682
  init_define_PKG();
683
683
  var UsageError = class extends Error {
684
684
  };
@@ -692,7 +692,9 @@ var options = {
692
692
  port: { type: "string" },
693
693
  "storefront-port": { type: "string" },
694
694
  app: { type: "string" },
695
+ from: { type: "string" },
695
696
  with: { type: "string", multiple: true },
697
+ "no-apps": { type: "boolean" },
696
698
  verbose: { type: "boolean" },
697
699
  "no-open": { type: "boolean" },
698
700
  "dry-run": { type: "boolean" },
@@ -721,12 +723,19 @@ Run create-shopnex --help for the options.`);
721
723
  const port = toPort("port", values.port, DEFAULT_PORT);
722
724
  const storefrontPort = toPort("storefront-port", values["storefront-port"], DEFAULT_STOREFRONT_PORT);
723
725
  if (port === storefrontPort) throw new UsageError("--port and --storefront-port must be different");
726
+ if (values["no-apps"] && values.with?.length) throw new UsageError("--no-apps and --with cannot be used together");
727
+ const from = values.from?.trim();
728
+ if (values.from !== void 0 && !from)
729
+ throw new UsageError("--from needs a store address, e.g. --from my-store.myshopify.com");
730
+ if (from && from.length > 300) throw new UsageError("--from is too long: give the store address, not a page");
724
731
  return {
725
732
  name: positionals[0],
726
733
  port,
727
734
  storefrontPort,
728
735
  app: values.app,
736
+ from,
729
737
  with: values.with ?? [],
738
+ noApps: Boolean(values["no-apps"]),
730
739
  verbose: Boolean(values.verbose),
731
740
  open: !values["no-open"],
732
741
  dryRun: Boolean(values["dry-run"]),
@@ -807,7 +816,8 @@ function planFromBundle(input) {
807
816
  APP_DATABASE_URL: databaseUrl.startsWith("pglite:") ? `pglite:${join(shopDir, "apps", extra.dir, ".pglite")}` : databaseUrl
808
817
  }
809
818
  },
810
- readyUrl: `http://127.0.0.1:${extra.port}/shopnex/app.js`
819
+ readyUrl: `http://127.0.0.1:${extra.port}/shopnex/app.js`,
820
+ optional: true
811
821
  }))
812
822
  ]
813
823
  };
@@ -879,8 +889,22 @@ var extras = [
879
889
  keyEnv: "CJ_DROPSHIPPING_APP_KEY",
880
890
  database: true
881
891
  },
882
- { name: "shippo", label: "Shippo", dir: "shippo", port: 4900, urlEnv: "SHIPPO_APP_URL", keyEnv: "SHIPPO_APP_KEY" }
892
+ { name: "shippo", label: "Shippo", dir: "shippo", port: 4900, urlEnv: "SHIPPO_APP_URL", keyEnv: "SHIPPO_APP_KEY" },
893
+ {
894
+ name: "reviews",
895
+ label: "Reviews",
896
+ dir: "reviews",
897
+ port: 5100,
898
+ urlEnv: "REVIEWS_APP_URL",
899
+ keyEnv: "REVIEWS_APP_KEY",
900
+ database: true
901
+ }
883
902
  ];
903
+ function selectExtras(options2, list = extras) {
904
+ if (options2.noApps) return [];
905
+ const picked = pickExtras(options2.with, list);
906
+ return picked.length ? picked : list;
907
+ }
884
908
  function pickExtras(values, list = extras) {
885
909
  const names = (values ?? []).flatMap((value) => value.split(",")).map((name) => name.trim().toLowerCase());
886
910
  const picked = [];
@@ -893,7 +917,7 @@ function pickExtras(values, list = extras) {
893
917
  return picked;
894
918
  }
895
919
 
896
- // src/bundle.ts
920
+ // ../cli-core/src/bundle.ts
897
921
  init_define_PKG();
898
922
  import { createHash } from "node:crypto";
899
923
  import {
@@ -911,7 +935,7 @@ import { spawnSync } from "node:child_process";
911
935
  import { Readable, Transform } from "node:stream";
912
936
  import { pipeline } from "node:stream/promises";
913
937
 
914
- // src/paths.ts
938
+ // ../cli-core/src/paths.ts
915
939
  init_define_PKG();
916
940
  import { homedir } from "node:os";
917
941
  import { join as join3, resolve } from "node:path";
@@ -923,14 +947,14 @@ function resolveShopDir(name, cwd = process.cwd()) {
923
947
  }
924
948
  var appCacheDir = () => process.env.SHOPNEX_APP_DIR ?? join3(homedir(), ".shopnex", "app");
925
949
 
926
- // src/bundle.ts
950
+ // ../cli-core/src/bundle.ts
927
951
  var isEdge = (version) => /-edge\./.test(version);
928
952
  var bundleName = (version) => `shopnex-v${version}-node.tgz`;
929
953
  var bundleUrl = (version) => process.env.SHOPNEX_BUNDLE_URL ?? (isEdge(version) ? "https://github.com/shopnex-ai/shopnex/releases/download/edge/shopnex-edge-node.tgz" : `https://github.com/shopnex-ai/shopnex/releases/download/v${version}/${bundleName(version)}`);
930
954
  var bundleDir = (key) => join4(appCacheDir(), key);
931
955
  var isInstalled = (key) => existsSync2(join4(bundleDir(key), "manifest.json"));
932
956
  var installedEdges = () => existsSync2(appCacheDir()) ? readdirSync(appCacheDir()).filter((name) => /^edge-[0-9a-f]{12}$/.test(name)) : [];
933
- async function get(url, what, version) {
957
+ async function get(url, what, version, cli) {
934
958
  let response;
935
959
  try {
936
960
  response = await fetch(url);
@@ -942,7 +966,7 @@ Check your connection and try again.`);
942
966
  if (response.status === 404) {
943
967
  throw new UnavailableError(
944
968
  `ShopNex ${version} has no packaged build to download (404 for ${url}).
945
- Use a released version of create-shopnex.`
969
+ Use a released version of ${cli}.`
946
970
  );
947
971
  }
948
972
  if (!response.ok) {
@@ -969,7 +993,7 @@ async function download(response, file, onProgress) {
969
993
  );
970
994
  return hash.digest("hex");
971
995
  }
972
- async function resolveBundle({ version }) {
996
+ async function resolveBundle({ version, cli = "create-shopnex" }) {
973
997
  const edge = isEdge(version);
974
998
  if (!edge && isInstalled(version)) return bundleDir(version);
975
999
  mkdirSync2(appCacheDir(), { recursive: true });
@@ -982,7 +1006,7 @@ async function resolveBundle({ version }) {
982
1006
  let work;
983
1007
  try {
984
1008
  const url = bundleUrl(version);
985
- const expected = parseChecksum(await (await get(`${url}.sha256`, "the checksum", version)).text());
1009
+ const expected = parseChecksum(await (await get(`${url}.sha256`, "the checksum", version, cli)).text());
986
1010
  if (!/^[0-9a-f]{64}$/.test(expected)) throw new UnavailableError(`${url}.sha256 does not hold a SHA-256 checksum.`);
987
1011
  const key = edge ? `edge-${expected.slice(0, 12)}` : version;
988
1012
  const dir = bundleDir(key);
@@ -995,7 +1019,7 @@ async function resolveBundle({ version }) {
995
1019
  work = mkdtempSync(join4(appCacheDir(), `${key}.tmp-`));
996
1020
  const file = join4(work, "bundle.tgz");
997
1021
  const actual = await download(
998
- await get(url, "ShopNex", version),
1022
+ await get(url, "ShopNex", version, cli),
999
1023
  file,
1000
1024
  (bytes) => say(`Downloading ${label}: ${(bytes / 1e6).toFixed(1)} MB`)
1001
1025
  );
@@ -1032,7 +1056,7 @@ async function resolveBundle({ version }) {
1032
1056
  }
1033
1057
  }
1034
1058
 
1035
- // src/node-version.ts
1059
+ // ../cli-core/src/node-version.ts
1036
1060
  init_define_PKG();
1037
1061
  var atLeast = (version, minimum) => version.replace(/^v/, "").localeCompare(minimum, void 0, { numeric: true }) >= 0;
1038
1062
  function assertNode(version, enginesRange) {
@@ -1044,7 +1068,7 @@ function assertNode(version, enginesRange) {
1044
1068
  }
1045
1069
  }
1046
1070
 
1047
- // src/env.ts
1071
+ // ../cli-core/src/env.ts
1048
1072
  init_define_PKG();
1049
1073
  import { randomBytes } from "node:crypto";
1050
1074
  import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, appendFileSync, writeFileSync as writeFileSync2 } from "node:fs";
@@ -1095,18 +1119,42 @@ function loadShopEnv(shopDir, { write }) {
1095
1119
  // src/scaffold.ts
1096
1120
  init_define_PKG();
1097
1121
  import { existsSync as existsSync4, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
1098
- import { join as join6 } from "node:path";
1122
+ import { basename, join as join6 } from "node:path";
1123
+
1124
+ // src/readme.ts
1125
+ init_define_PKG();
1126
+ var template2 = true ? "# Getting started with ShopNex\n\nRun a ShopNex shop on your machine in a few minutes. No PostgreSQL, no Docker, no clone.\n\nWhen it is running you have:\n\n- the **admin** at http://localhost:3000/admin\n- the **storefront** at http://localhost:4321\n- a **database** in the shop folder (embedded, for trying things out)\n\n## You need\n\n- Node.js 22.22 or newer\n- Free ports `3000` (admin, API, checkout) and `4321` (storefront). Other ports: `--port` and `--storefront-port`.\n\n## 1. Start the shop\n\n```sh\nnpx create-shopnex@latest my-shop\n```\n\nThis creates the folder `my-shop`, downloads ShopNex once (about 15 MB, kept in `~/.shopnex/app` and shared by all\nyour shops), starts the admin and the storefront, and opens the admin in your browser. The first start takes a minute.\nLeave the terminal open: Ctrl+C stops the shop.\n\n## 2. Create the owner account\n\nThe admin opens the setup wizard on the first run. Create the owner account right away: until you do, whoever reaches\nthe admin can. Both servers listen on your machine only (`127.0.0.1`).\n\nThen open the storefront at http://localhost:4321 and the admin at http://localhost:3000/admin.\n\n## 3. Run it again\n\n```sh\ncd my-shop\nnpm start\n```\n\n`npm run dev` does the same. Nothing to install first: the script runs `npx --yes create-shopnex@<version> .` with the\nversion that made the folder. The shop's data stays in the folder, so the same folder is the same shop.\n\n## 4. Add your first product\n\nIn the admin, add a product (a name and a price are enough), then reload the storefront: it shows up there. That is the\nwhole loop: you change things in the admin, customers see them in the storefront.\n\nTo try a card payment, start the Stripe app next to the shop (`--with stripe`, see below), install it from the admin and\nenter your Stripe **test** keys; the test card is `4242 4242 4242 4242`. Stripe cannot reach a `localhost` address, so\npayments need a public address for the app or `stripe listen`: the Stripe app's settings page explains it.\n\n## Update\n\n`npm start` runs the version written in the shop's `package.json` (`create-shopnex@<version>`), so it never changes by\nitself. To move to a newer version:\n\n1. Stop the shop and copy the folder somewhere as a backup.\n2. Change the version in the two scripts of `package.json` (or run `npx create-shopnex@latest my-shop` once).\n3. Start it again. The database changes the new version needs are applied on start.\n\n## What is in the folder\n\n| File | What it is |\n| -------------------- | ---------------------------------------------------------------------------------------------------------------- |\n| `.env` | The shop's settings and secrets. Keep it out of git; a lost `SHOPNEX_SECRET` means a new shop |\n| `.pglite/` | The embedded trial database |\n| `docker-compose.yml` | For running the shop in Docker instead: see the [self-hosting docs](https://shopnex.ai/docs/self-hosting/docker) |\n| `README.md` | How to run this shop again |\n\n## Next\n\n- **Payments and shipping:** start the optional apps next to the shop with\n `npx create-shopnex@latest my-shop --with stripe,cj,shippo`, then install them from the admin and enter your keys.\n- **From trying it to a real shop:** the embedded database is for trying ShopNex out (one process owns it), so move to\n PostgreSQL before you rely on the shop. With the shop stopped, run this in its folder with an empty PostgreSQL database:\n\n ```sh\n TARGET=postgres://user:password@host:5432/shopnex npx shopnex migrate-db --to-env TARGET\n ```\n\n It copies the data, keeps a copy of the old data next to it and points the `.env` at PostgreSQL. Then run the shop in\n Docker with the `docker-compose.yml` ([self-hosting docs](https://shopnex.ai/docs/self-hosting/docker)).\n\n- **Every option and how the download is checked:** the [package README](https://github.com/shopnex-ai/shopnex/tree/main/packages/create-shopnex#readme).\n\n## If something goes wrong\n\n- **A port is taken:** the command stops before downloading anything and names the flag to change (`--port`,\n `--storefront-port`).\n- **No connection:** the first run needs the network for the download; later runs do not.\n- **Servers will not start:** run again with `--verbose` to see their output.\n- **Start over:** delete the shop folder.\n" : readFileSync(new URL("../getting-started/README.md", import.meta.url), "utf8");
1127
+ var EXAMPLE_NAME = "my-shop";
1128
+ var readme = (name) => template2.replaceAll(EXAMPLE_NAME, name);
1129
+
1130
+ // src/scaffold.ts
1099
1131
  var GITIGNORE = `# ShopNex: secrets and local data stay out of git
1100
1132
  .env
1101
1133
  .pglite/
1102
1134
  apps/*/.pglite/
1103
1135
  apps/*/app-key
1104
1136
  `;
1137
+ var packageJson = (name, version) => {
1138
+ const run2 = `npx --yes create-shopnex@${version} .`;
1139
+ return JSON.stringify(
1140
+ {
1141
+ name: name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[._-]+/, "") || "shopnex-shop",
1142
+ private: true,
1143
+ scripts: { start: run2, dev: run2 }
1144
+ },
1145
+ null,
1146
+ 2
1147
+ ) + "\n";
1148
+ };
1105
1149
  var composeUrl = (version) => `https://raw.githubusercontent.com/shopnex-ai/shopnex/${isEdge(version) ? "main" : `v${version}`}/deploy/docker-compose.yml`;
1106
1150
  async function writeScaffold(shopDir, version, fetcher = fetch) {
1107
1151
  mkdirSync4(shopDir, { recursive: true });
1108
1152
  const gitignore = join6(shopDir, ".gitignore");
1109
1153
  if (!existsSync4(gitignore)) writeFileSync3(gitignore, GITIGNORE);
1154
+ const pkgFile = join6(shopDir, "package.json");
1155
+ if (!existsSync4(pkgFile)) writeFileSync3(pkgFile, packageJson(basename(shopDir), version));
1156
+ const readmeFile = join6(shopDir, "README.md");
1157
+ if (!existsSync4(readmeFile)) writeFileSync3(readmeFile, readme(basename(shopDir)));
1110
1158
  const compose = join6(shopDir, "docker-compose.yml");
1111
1159
  if (existsSync4(compose)) return;
1112
1160
  const url = composeUrl(version);
@@ -1119,7 +1167,7 @@ async function writeScaffold(shopDir, version, fetcher = fetch) {
1119
1167
  }
1120
1168
  }
1121
1169
 
1122
- // src/theme.ts
1170
+ // ../cli-core/src/theme.ts
1123
1171
  init_define_PKG();
1124
1172
  var import_picocolors2 = __toESM(require_picocolors(), 1);
1125
1173
  var BRAND = [67, 192, 122];
@@ -1128,12 +1176,9 @@ var truecolor = import_picocolors2.default.isColorSupported && /^(truecolor|24bi
1128
1176
  var brand = (text) => truecolor ? `\x1B[38;2;${BRAND.join(";")}m${text}\x1B[39m` : import_picocolors2.default.green(text);
1129
1177
  var brandBadge = (text) => truecolor ? `\x1B[48;2;${BRAND.join(";")}m\x1B[38;2;${ON_BRAND.join(";")}m${text}\x1B[39m\x1B[49m` : import_picocolors2.default.bgGreen(import_picocolors2.default.black(text));
1130
1178
 
1131
- // src/run.ts
1179
+ // ../cli-core/src/ports.ts
1132
1180
  init_define_PKG();
1133
- import { spawn } from "node:child_process";
1134
1181
  import { connect } from "node:net";
1135
- var import_picocolors3 = __toESM(require_picocolors(), 1);
1136
- var sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
1137
1182
  function portInUse(port) {
1138
1183
  const tryHost = (host) => new Promise((resolve3) => {
1139
1184
  const socket = connect({ port, host });
@@ -1151,6 +1196,12 @@ async function assertPortsFree(ports) {
1151
1196
  }
1152
1197
  }
1153
1198
  }
1199
+
1200
+ // src/run.ts
1201
+ init_define_PKG();
1202
+ import { spawn } from "node:child_process";
1203
+ var import_picocolors3 = __toESM(require_picocolors(), 1);
1204
+ var sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
1154
1205
  async function isUp(url) {
1155
1206
  try {
1156
1207
  return (await fetch(url, { redirect: "manual" })).status < 500;
@@ -1158,6 +1209,9 @@ async function isUp(url) {
1158
1209
  return false;
1159
1210
  }
1160
1211
  }
1212
+ function adminEntry(appUrl, from) {
1213
+ return from ? `${appUrl}/admin/signup?import=${encodeURIComponent(from)}` : `${appUrl}/admin`;
1214
+ }
1161
1215
  function openBrowser(url) {
1162
1216
  const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
1163
1217
  const child = spawn(command, args, { stdio: "ignore", detached: true });
@@ -1165,12 +1219,13 @@ function openBrowser(url) {
1165
1219
  });
1166
1220
  child.unref();
1167
1221
  }
1168
- function runPlan(plan, { open, verbose }) {
1222
+ function runPlan(plan, { open, verbose, from }) {
1169
1223
  return new Promise((resolve3) => {
1170
1224
  const children = [];
1171
1225
  const tails = /* @__PURE__ */ new Map();
1172
1226
  let stopping = false;
1173
1227
  let ready = false;
1228
+ const failed = /* @__PURE__ */ new Set();
1174
1229
  const spinner = de();
1175
1230
  const animate = Boolean(process.stdout.isTTY) && !verbose;
1176
1231
  if (animate) spinner.start("Starting ShopNex (the first start takes a minute)");
@@ -1212,11 +1267,19 @@ function runPlan(plan, { open, verbose }) {
1212
1267
  });
1213
1268
  }
1214
1269
  child.on("error", (error) => {
1270
+ if (stopping) return;
1215
1271
  console.error(`Could not start ${proc.name}: ${error.message}`);
1272
+ if (proc.optional) return void failed.add(proc.name);
1216
1273
  stop(1);
1217
1274
  });
1218
1275
  child.on("exit", (code, signal) => {
1219
1276
  if (stopping) return;
1277
+ if (proc.optional) {
1278
+ failed.add(proc.name);
1279
+ console.error(`${proc.name} stopped (${signal ?? `exit ${code}`}); the shop keeps running without it.`);
1280
+ if (!verbose) for (const line of tails.get(proc.name) ?? []) console.error(import_picocolors3.default.dim(` ${line}`));
1281
+ return;
1282
+ }
1220
1283
  if (animate && !ready) spinner.stop(`${proc.name} stopped`, 1);
1221
1284
  console.error(`${proc.name} stopped (${signal ?? `exit ${code}`}).`);
1222
1285
  if (!verbose) for (const line of tails.get(proc.name) ?? []) console.error(import_picocolors3.default.dim(` ${line}`));
@@ -1227,21 +1290,27 @@ function runPlan(plan, { open, verbose }) {
1227
1290
  process.on("SIGTERM", () => stop(0));
1228
1291
  void (async () => {
1229
1292
  for (let i = 0; i < 180 && !stopping; i++) {
1230
- if ((await Promise.all(plan.processes.map((proc) => isUp(proc.readyUrl)))).every(Boolean)) break;
1293
+ const up = await Promise.all(
1294
+ plan.processes.map(async (proc) => proc.optional && failed.has(proc.name) || await isUp(proc.readyUrl))
1295
+ );
1296
+ if (up.every(Boolean)) break;
1231
1297
  await sleep(1e3);
1232
1298
  }
1233
1299
  if (stopping) return;
1234
1300
  ready = true;
1235
1301
  if (animate) spinner.stop("ShopNex is running");
1302
+ if (failed.size) f2.warn(`Not running: ${[...failed].join(", ")} (see above). The rest of the shop is up.`);
1236
1303
  le(
1237
1304
  [
1238
1305
  `${import_picocolors3.default.bold("Shop ")} ${brand(plan.storefrontUrl)}`,
1239
- `${import_picocolors3.default.bold("Admin")} ${brand(`${plan.appUrl}/admin`)} (the first run opens the setup wizard)`
1306
+ `${import_picocolors3.default.bold("Admin")} ${brand(`${plan.appUrl}/admin`)} (the first run opens the setup wizard)`,
1307
+ ...from ? [`${import_picocolors3.default.bold("Import")} ${from} (starts once you have created the owner)`] : []
1240
1308
  ].join("\n"),
1241
1309
  "Open"
1242
1310
  );
1311
+ f2.message(`${import_picocolors3.default.dim("Like it? Star us on GitHub:")} ${brand("https://github.com/shopnex-ai/shopnex")}`);
1243
1312
  $e("Create the owner account right away. Ctrl+C stops everything.");
1244
- if (open) openBrowser(`${plan.appUrl}/admin`);
1313
+ if (open) openBrowser(adminEntry(plan.appUrl, from));
1245
1314
  })();
1246
1315
  });
1247
1316
  }
@@ -1262,7 +1331,9 @@ Options
1262
1331
  --port <n> admin, API and checkout (default 3000)
1263
1332
  --storefront-port <n> storefront (default 4321)
1264
1333
  --no-open do not open the browser
1265
- --with <apps> also start optional apps: stripe, cj, shippo (comma separated, or repeat the flag)
1334
+ --with <apps> start only these apps: stripe, cj, shippo, reviews (comma separated, or repeat the flag)
1335
+ --no-apps start the shop alone, without the bundled apps (all four start by default)
1336
+ --from <store> bring a Shopify or WooCommerce store across (products, pages, look): its address, e.g. my-store.myshopify.com
1266
1337
  --app <name> what to start (default shop; a picker appears once there is more than one)
1267
1338
  --verbose show the output of the servers while they start
1268
1339
  --dry-run show what would run and exit
@@ -1274,7 +1345,8 @@ function describe({
1274
1345
  database,
1275
1346
  plan,
1276
1347
  source,
1277
- extras: extras2 = []
1348
+ extras: extras2 = [],
1349
+ from
1278
1350
  }) {
1279
1351
  const rows = [
1280
1352
  ["Source", source],
@@ -1282,6 +1354,7 @@ function describe({
1282
1354
  ["Database", redactUrl(database)],
1283
1355
  ["Admin", `${plan.appUrl}/admin`],
1284
1356
  ["Storefront", plan.storefrontUrl],
1357
+ ...from ? [["Import", `${from} (starts after you create the owner)`]] : [],
1285
1358
  ...extras2.map((extra) => [extra.label, `http://localhost:${extra.port} (install it from the admin)`])
1286
1359
  ];
1287
1360
  const width = Math.max(...rows.map(([label]) => label?.length ?? 0)) + 2;
@@ -1297,16 +1370,28 @@ async function run(argv) {
1297
1370
  const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
1298
1371
  const name = options2.name ?? DEFAULT_SHOP_NAME;
1299
1372
  const shopDir = resolveShopDir(name);
1300
- const extras2 = pickExtras(options2.with);
1373
+ let extras2 = selectExtras(options2);
1301
1374
  const shopEnv = loadShopEnv(shopDir, { write: !options2.dryRun });
1302
1375
  const scaffoldWarning = options2.dryRun ? void 0 : await writeScaffold(shopDir, pkg.version);
1303
1376
  if (scaffoldWarning) f2.warn(scaffoldWarning);
1304
1377
  const ports = [
1305
1378
  { port: options2.port, flag: "--port" },
1306
- { port: options2.storefrontPort, flag: "--storefront-port" },
1307
- ...extras2.map((extra) => ({ port: extra.port, flag: `--with (${extra.name} needs it free)` }))
1379
+ { port: options2.storefrontPort, flag: "--storefront-port" }
1308
1380
  ];
1309
- if (!options2.dryRun) await assertPortsFree(ports);
1381
+ if (!options2.dryRun) {
1382
+ await assertPortsFree(ports);
1383
+ if (options2.with.length) {
1384
+ await assertPortsFree(extras2.map((extra) => ({ port: extra.port, flag: `--with (${extra.name} needs it free)` })));
1385
+ } else {
1386
+ const busy = /* @__PURE__ */ new Set();
1387
+ for (const extra of extras2) if (await portInUse(extra.port)) busy.add(extra.name);
1388
+ for (const name2 of busy) {
1389
+ const extra = extras2.find((e2) => e2.name === name2);
1390
+ f2.warn(`Port ${extra?.port} is in use, so ${extra?.label} is not started. --no-apps hides this.`);
1391
+ }
1392
+ extras2 = extras2.filter((extra) => !busy.has(extra.name));
1393
+ }
1394
+ }
1310
1395
  const root = options2.dryRun ? bundleDir(pkg.version) : await resolveBundle({ version: pkg.version });
1311
1396
  const source = isEdge(pkg.version) ? "ShopNex edge (the latest build from main, checked on every run)" : `ShopNex ${pkg.version} ${isInstalled(pkg.version) ? "(downloaded)" : "(downloaded on the first run)"}`;
1312
1397
  const app = await pickApp(options2.app, { interactive });
@@ -1321,10 +1406,10 @@ async function run(argv) {
1321
1406
  secret: shopEnv.secret,
1322
1407
  appKeys: loadAppKeys(shopDir, extras2, { write: !options2.dryRun })
1323
1408
  });
1324
- le(describe({ shopDir, database: shopEnv.databaseUrl, plan, source, extras: extras2 }), app.label);
1409
+ le(describe({ shopDir, database: shopEnv.databaseUrl, plan, source, extras: extras2, from: options2.from }), app.label);
1325
1410
  if (options2.dryRun) return $e("Dry run: nothing was started.");
1326
1411
  f2.warn("This is a trial database: it is not for production.");
1327
- process.exitCode = await runPlan(plan, { open: options2.open, verbose: options2.verbose });
1412
+ process.exitCode = await runPlan(plan, { open: options2.open, verbose: options2.verbose, from: options2.from });
1328
1413
  }
1329
1414
  async function main(argv) {
1330
1415
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-shopnex",
3
- "version": "0.0.0-edge.c8ad7df",
3
+ "version": "0.0.0-edge.e014713",
4
4
  "description": "Try ShopNex with one command: npx create-shopnex starts the admin and the storefront on an embedded database, nothing else to install",
5
5
  "license": "MIT",
6
6
  "homepage": "https://shopnex.ai",
@@ -38,6 +38,7 @@
38
38
  },
39
39
  "devDependencies": {
40
40
  "@clack/prompts": "^0.7.0",
41
+ "@shopnex/cli-core": "workspace:*",
41
42
  "@types/node": "catalog:",
42
43
  "esbuild": "0.28.2",
43
44
  "picocolors": "^1.1.1",