ref0-git 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/app/apps/github/README.md +1 -5
  2. package/app/apps/github/package.json +0 -1
  3. package/app/apps/github/src/signin/auth.ts +17 -89
  4. package/app/apps/github/src/signin/credentials.ts +10 -14
  5. package/app/apps/github/src/signin/guarded-write.ts +19 -0
  6. package/app/apps/github/src/signin/owner-names.ts +11 -41
  7. package/app/apps/github/src/signin/unborn.ts +20 -30
  8. package/app/apps/github/tsconfig.json +0 -2
  9. package/app/pnpm-workspace.yaml +14 -34
  10. package/dist/cli/documents.mjs +39 -25
  11. package/dist/cli/keys.mjs +9 -3
  12. package/dist/cli/node.mjs +1 -2
  13. package/dist/cli/runtime.mjs +3 -4
  14. package/dist/cli/setup.mjs +216 -468
  15. package/dist/cli/tools-node.mjs +8 -7
  16. package/dist/cli/tools.mjs +3 -3
  17. package/dist/cli/vercel-stores.mjs +287 -0
  18. package/dist/init/app.mjs +4 -37
  19. package/dist/init/choices.mjs +62 -209
  20. package/dist/init/cloudflare.mjs +1 -2
  21. package/dist/init/detect.mjs +77 -167
  22. package/dist/init/files.mjs +2 -12
  23. package/dist/init/frameworks.mjs +50 -174
  24. package/dist/init/git-module.mjs +5 -1
  25. package/dist/init/metadata.mjs +4 -22
  26. package/dist/init/next.mjs +13 -66
  27. package/dist/init/output.mjs +3 -6
  28. package/dist/init/plan.mjs +1 -29
  29. package/dist/init/routes.mjs +1 -78
  30. package/dist/init/stores.mjs +6 -35
  31. package/dist/init/template.mjs +14 -49
  32. package/dist/init/templates.mjs +30 -115
  33. package/dist/init/vercel-regions.mjs +87 -0
  34. package/dist/init/vercel.mjs +313 -212
  35. package/dist/init/versions.mjs +3 -3
  36. package/package.json +5 -11
  37. package/app/apps/github/migrations/postgres/0001_auth.sql +0 -53
  38. package/app/apps/github/src/camo/lookup.ts +0 -23
  39. package/app/apps/github/src/camo/node.ts +0 -50
  40. package/app/apps/github/src/signin/person-lock.ts +0 -104
  41. package/dist/cli/sqlite.mjs +0 -28
  42. package/dist/init/astro.mjs +0 -49
  43. package/dist/init/create.mjs +0 -152
  44. package/dist/init/mounts.mjs +0 -104
  45. package/dist/init/node-app.mjs +0 -196
  46. package/dist/init/node.mjs +0 -446
  47. package/dist/init/nuxt.mjs +0 -240
  48. package/dist/init/react-router.mjs +0 -59
  49. package/dist/init/sveltekit.mjs +0 -141
@@ -1,4 +1,4 @@
1
- import { catalog, frameworkPackages, nodeAppPackages, nodePackages, peerPackages, release, storePackages, vercelPackages } from "./metadata.mjs";
1
+ import { catalog, peerPackages, release, storePackages, vercelPackages } from "./metadata.mjs";
2
2
  // src/init/versions.ts
3
3
  /**
4
4
  * The versions `init` writes, pinned exactly, since npm ignores pnpm's lockfile: Git's packages at
@@ -56,5 +56,5 @@ const initPacked = (name, at) => {
56
56
  * the release, or the tarball `--from-checkout` names for that package. One it wrote moves to this
57
57
  * run's spec; any other is the person's, a tarball of their own in `vendor/` too, and stays.
58
58
  */
59
- const initWrote = (name, spec) => spec === "0.27.0" || spec !== void 0 && packedPath(name).test(spec);
60
- export { catalog, contentNamed, frameworkPackages, initPacked, initWrote, nodeAppPackages, nodePackages, peerPackages, published, release, specOf, storePackages, unpacked, vercelPackages };
59
+ const initWrote = (name, spec) => spec === "0.29.0" || spec !== void 0 && packedPath(name).test(spec);
60
+ export { catalog, contentNamed, initPacked, initWrote, peerPackages, published, release, specOf, storePackages, unpacked, vercelPackages };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ref0-git",
3
- "version": "0.27.0",
3
+ "version": "0.29.0",
4
4
  "private": false,
5
5
  "description": "ref0-git, the CLI for a Git host built on @ref0/git, and git-remote-ref0, its remote helper",
6
6
  "license": "Apache-2.0",
@@ -24,28 +24,22 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@effect/platform-node-shared": "4.1.7",
27
- "@ref0/git": "0.27.0",
28
- "@ref0/infra": "0.27.0",
27
+ "@ref0/git": "0.29.0",
28
+ "@ref0/infra": "0.29.0",
29
29
  "diff": "9.0.0",
30
30
  "effect": "^4.1.7"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@cloudflare/workers-types": "5.20261123.1",
34
34
  "@effect/vitest": "4.1.7",
35
- "@libsql/client": "0.18.0",
36
- "@libsql/kysely-libsql": "0.4.1",
37
- "@ref0/github": "0.27.0",
38
- "@ref0/xdiff-wasm": "0.27.0",
35
+ "@ref0/github": "0.29.0",
36
+ "@ref0/xdiff-wasm": "0.29.0",
39
37
  "@tanstack/react-start": "1.169.7",
40
38
  "@types/node": "24.19.4",
41
39
  "@types/pg": "8.23.1",
42
40
  "@types/semver": "7.8.0",
43
41
  "@vercel/blob": "2.9.0",
44
- "@vercel/queue": "0.11.0",
45
42
  "ajv": "8.20.0",
46
- "h3": "1.15.11",
47
- "kysely": "0.29.9",
48
- "nitro": "3.0.261103-rc",
49
43
  "path-to-regexp": "6.3.0",
50
44
  "pg": "8.23.1",
51
45
  "semver": "7.8.6",
@@ -1,53 +0,0 @@
1
- -- Better Auth 1.7.19's tables, with @better-auth/passkey's and the organization plugin's, for the
2
- -- starter's options in src/signin/auth.ts, on Postgres: people by their login (username), their
3
- -- password accounts and passkeys, sessions with each one's sealed Git token, orgs and their
4
- -- members, `owner_names`' claims on the logins people and orgs share, `avatar`'s pictures of
5
- -- people, orgs and repos, `repo_grant`'s grants of a repo to a person (#1998), and the rate limit's
6
- -- counts.
7
- -- Written by Better Auth's getMigrations from those options on a database with no tables, as
8
- -- credentials.test.ts checks, with `collate "C"` on the logins, `username` and `slug`, so a
9
- -- search's range of their indexes is their prefix's; apply it once, before the app's first
10
- -- start, as `psql -f` does.
11
- create table "user" ("id" text not null primary key, "name" text not null, "email" text not null unique, "emailVerified" boolean not null, "image" text, "createdAt" timestamptz default CURRENT_TIMESTAMP not null, "updatedAt" timestamptz default CURRENT_TIMESTAMP not null, "username" text collate "C" unique);
12
-
13
- create table "session" ("id" text not null primary key, "expiresAt" timestamptz not null, "token" text not null unique, "createdAt" timestamptz default CURRENT_TIMESTAMP not null, "updatedAt" timestamptz not null, "ipAddress" text, "userAgent" text, "userId" text not null references "user" ("id") on delete cascade, "activeOrganizationId" text, "gitTokenId" text, "gitToken" text);
14
-
15
- create table "account" ("id" text not null primary key, "accountId" text not null, "providerId" text not null, "userId" text not null references "user" ("id") on delete cascade, "accessToken" text, "refreshToken" text, "idToken" text, "accessTokenExpiresAt" timestamptz, "refreshTokenExpiresAt" timestamptz, "scope" text, "password" text, "createdAt" timestamptz default CURRENT_TIMESTAMP not null, "updatedAt" timestamptz not null);
16
-
17
- create table "verification" ("id" text not null primary key, "identifier" text not null, "value" text not null, "expiresAt" timestamptz not null, "createdAt" timestamptz default CURRENT_TIMESTAMP not null, "updatedAt" timestamptz default CURRENT_TIMESTAMP not null);
18
-
19
- create table "passkey" ("id" text not null primary key, "name" text, "publicKey" text not null, "userId" text not null references "user" ("id") on delete cascade, "credentialID" text not null unique, "counter" integer not null, "deviceType" text not null, "backedUp" boolean not null, "transports" text, "createdAt" timestamptz, "aaguid" text);
20
-
21
- create table "organization" ("id" text not null primary key, "name" text not null, "slug" text collate "C" not null unique, "logo" text, "createdAt" timestamptz not null, "metadata" text);
22
-
23
- create table "member" ("id" text not null primary key, "organizationId" text not null references "organization" ("id") on delete cascade, "userId" text not null references "user" ("id") on delete cascade, "role" text not null, "createdAt" timestamptz not null);
24
-
25
- create table "invitation" ("id" text not null primary key, "organizationId" text not null references "organization" ("id") on delete cascade, "email" text not null, "role" text, "status" text not null, "expiresAt" timestamptz not null, "createdAt" timestamptz default CURRENT_TIMESTAMP not null, "inviterId" text not null references "user" ("id") on delete cascade);
26
-
27
- create table "owner_names" ("id" text not null primary key, "claim" text not null, "claimedAt" timestamptz not null, "held" boolean not null);
28
-
29
- create table "avatar" ("id" text not null primary key, "kind" text not null, "type" text not null, "bytes" text not null, "size" integer not null, "hash" text not null, "updatedAt" timestamptz not null);
30
-
31
- create table "repo_grant" ("id" text not null primary key, "repo" text not null, "userId" text not null references "user" ("id") on delete cascade, "role" text not null, "createdAt" timestamptz not null);
32
-
33
- create table "rateLimit" ("id" text not null primary key, "key" text not null unique, "count" integer not null, "lastRequest" bigint not null);
34
-
35
- create index "session_userId_idx" on "session" ("userId");
36
-
37
- create index "account_userId_idx" on "account" ("userId");
38
-
39
- create index "verification_identifier_idx" on "verification" ("identifier");
40
-
41
- create index "passkey_userId_idx" on "passkey" ("userId");
42
-
43
- create index "member_organizationId_idx" on "member" ("organizationId");
44
-
45
- create index "member_userId_idx" on "member" ("userId");
46
-
47
- create index "invitation_organizationId_idx" on "invitation" ("organizationId");
48
-
49
- create index "invitation_email_idx" on "invitation" ("email");
50
-
51
- create index "repo_grant_repo_idx" on "repo_grant" ("repo");
52
-
53
- create index "repo_grant_userId_idx" on "repo_grant" ("userId");
@@ -1,23 +0,0 @@
1
- import { type LookupAddress, lookup } from 'node:dns';
2
- import type { LookupFunction } from 'node:net';
3
-
4
- import { refusedAddress } from './addresses.ts';
5
-
6
- /**
7
- * Node's lookup, refusing a name any of whose addresses the proxy refuses: the socket connects to
8
- * what this answers, so a name that resolves elsewhere between a check and a connect can't reach
9
- * the host's own network, as it could if the name were checked first and fetched after.
10
- */
11
- export const checkedLookup: LookupFunction = (hostname, options, done) => {
12
- lookup(hostname, { ...options, all: true }, (error, found: LookupAddress[]) => {
13
- if (error !== null) return done(error, '', 0);
14
-
15
- const refused = found.length === 0 || found.some(({ address }) => refusedAddress(address));
16
- if (refused) return done(new Error(`${hostname} resolves to a refused address`), '', 0);
17
-
18
- const [first] = found;
19
- if (options.all === true) return done(null, found);
20
-
21
- return done(null, first?.address ?? '', first?.family ?? 4);
22
- });
23
- };
@@ -1,50 +0,0 @@
1
- import { request as httpRequest } from 'node:http';
2
- import { request as httpsRequest } from 'node:https';
3
- import { Readable } from 'node:stream';
4
-
5
- import type { Fetcher } from './fetch.ts';
6
- import { checkedLookup } from './lookup.ts';
7
-
8
- /** Statuses a `Response` holds no body with. */
9
- const empty = new Set([101, 204, 205, 304]);
10
-
11
- /**
12
- * The proxy's `Fetcher` on Node: one `GET` through `node:http` or `node:https`, connecting only to
13
- * an address `checkedLookup` passes, never following a redirect, and stopped by `signal`.
14
- */
15
- export const nodeFetch: Fetcher = (url, { headers, signal }) =>
16
- new Promise((resolve, reject) => {
17
- const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
18
- const asked = send(
19
- url,
20
- { method: 'GET', headers: Object.fromEntries(headers), lookup: checkedLookup, signal },
21
- (answer) => {
22
- const status = answer.statusCode ?? 0;
23
-
24
- if (status < 200 || status > 599) {
25
- answer.destroy();
26
-
27
- return reject(new Error(`${status} is no answer`));
28
- }
29
-
30
- try {
31
- const said = new Headers();
32
-
33
- for (let at = 0; at + 1 < answer.rawHeaders.length; at += 2) {
34
- said.append(answer.rawHeaders[at] ?? '', answer.rawHeaders[at + 1] ?? '');
35
- }
36
-
37
- const body = empty.has(status) ? null : Readable.toWeb(answer);
38
- // SAFETY: `Readable.toWeb` answers `node:stream/web`'s `ReadableStream`, the stream a
39
- // `Response` takes; only the two declarations of its type differ.
40
- resolve(new Response(body as BodyInit | null, { status, headers: said }));
41
- } catch (cause) {
42
- // A header no `Headers` takes: the answer is refused, as any other failed fetch.
43
- answer.destroy();
44
- reject(cause);
45
- }
46
- },
47
- );
48
- asked.on('error', reject);
49
- asked.end();
50
- });
@@ -1,104 +0,0 @@
1
- import {
2
- DummyDriver,
3
- Kysely,
4
- type Dialect,
5
- type QueryExecutorProvider,
6
- type RawBuilder,
7
- SqliteAdapter,
8
- SqliteIntrospector,
9
- SqliteQueryCompiler,
10
- sql,
11
- } from 'kysely';
12
-
13
- import type { AuthDatabase, NodeSqliteValue } from './auth.ts';
14
-
15
- /** Runs one write, and answers how many rows it changed. */
16
- export type Write = (statement: RawBuilder<unknown>) => Promise<number>;
17
-
18
- /** One query engine per dialect, since a Kysely of its own would open the dialect's driver again. */
19
- const engines = new WeakMap<Dialect, Kysely<unknown>>();
20
-
21
- const engineOf = (dialect: Dialect) => {
22
- const known = engines.get(dialect);
23
- if (known !== undefined) return known;
24
-
25
- const made = new Kysely<unknown>({ dialect });
26
- engines.set(dialect, made);
27
-
28
- return made;
29
- };
30
-
31
- /**
32
- * SQLite's compiler alone, for D1 and `node:sqlite`, which speak SQLite though no Kysely dialect
33
- * of either is ours.
34
- */
35
- const sqliteOnly = new Kysely<unknown>({
36
- dialect: {
37
- createAdapter: () => new SqliteAdapter(),
38
- createDriver: () => new DummyDriver(),
39
- createIntrospector: (db) => new SqliteIntrospector(db),
40
- createQueryCompiler: () => new SqliteQueryCompiler(),
41
- },
42
- });
43
-
44
- const throughEngine =
45
- (engine: QueryExecutorProvider): Write =>
46
- async (statement) => {
47
- const ran = await statement.execute(engine);
48
-
49
- return Number(ran.numAffectedRows ?? 0n);
50
- };
51
-
52
- /**
53
- * Runs a person's guarded writes, each a statement that checks what the person holds as it
54
- * writes, such as deleting their row only while no session is theirs.
55
- *
56
- * D1, SQLite and libSQL run one writer at a time, so each such statement sees every write before
57
- * it, and runs as it is. Postgres at READ COMMITTED doesn't: a statement's snapshot misses a write
58
- * not yet committed, such as a session whose insert holds the person's row, or another passkey's
59
- * delete. There the writes run in one transaction that first locks the person's row `for update`,
60
- * so it waits for any of theirs in flight, and each statement after it sees what they committed.
61
- * The level is set, not taken from the database, since REPEATABLE READ would keep the snapshot
62
- * from before the lock.
63
- */
64
- export const withPersonLocked = async <A>(
65
- database: AuthDatabase,
66
- id: string,
67
- writes: (write: Write) => Promise<A>,
68
- ): Promise<A> => {
69
- // `node:sqlite`'s database closes, and D1's binding doesn't.
70
- if ('close' in database) {
71
- return writes(async (statement) => {
72
- const compiled = statement.compile(sqliteOnly);
73
- // SAFETY: every guarded write binds ids, as text: a person's and a passkey's.
74
- const values = compiled.parameters as readonly NodeSqliteValue[];
75
- const ran = database.prepare(compiled.sql).run(...values);
76
-
77
- return Number(ran.changes);
78
- });
79
- }
80
-
81
- if (!('dialect' in database)) {
82
- return writes(async (statement) => {
83
- const compiled = statement.compile(sqliteOnly);
84
- const ran = await database
85
- .prepare(compiled.sql)
86
- .bind(...compiled.parameters)
87
- .run();
88
-
89
- return ran.meta.changes;
90
- });
91
- }
92
-
93
- const engine = engineOf(database.dialect);
94
- if (database.type !== 'postgres') return writes(throughEngine(engine));
95
-
96
- return engine
97
- .transaction()
98
- .setIsolationLevel('read committed')
99
- .execute(async (locked) => {
100
- await sql`select 1 from "user" where "id" = ${id} for update`.execute(locked);
101
-
102
- return writes(throughEngine(locked));
103
- });
104
- };
@@ -1,28 +0,0 @@
1
- import { node } from "./node.mjs";
2
- import * as Context from "effect/Context";
3
- import * as Effect from "effect/Effect";
4
- import * as Data from "effect/Data";
5
- import * as Layer from "effect/Layer";
6
- // src/cli/sqlite.ts
7
- /** A SQLite file that couldn't be opened or read, as one that isn't a database. */
8
- var SqliteUnreadable = class extends Data.TaggedError("SqliteUnreadable") {};
9
- /** The local SQLite `doctor` reads, read-only: Node's own, which has no Effect service (D12). */
10
- var Sqlite = class extends (/* @__PURE__ */ Context.Service()("ref0-git/cli/Sqlite")) {};
11
- const migrated = (path) => Effect.try({
12
- try: () => {
13
- if (!node.fs.existsSync(path)) return /* @__PURE__ */ new Set();
14
- const database = new (node.sqlite()).DatabaseSync(path, { readOnly: true });
15
- try {
16
- return database.prepare("select \"name\" from \"sqlite_master\" where \"name\" = ?").all("_migrations").length === 0 ? /* @__PURE__ */ new Set() : new Set(database.prepare("select \"name\" from \"_migrations\"").all().map((row) => String(row.name)));
17
- } finally {
18
- database.close();
19
- }
20
- },
21
- catch: (cause) => new SqliteUnreadable({
22
- path,
23
- cause
24
- })
25
- });
26
- /** `Sqlite` over `node:sqlite`. */
27
- const layer = Layer.succeed(Sqlite, { migrated });
28
- export { Sqlite, SqliteUnreadable, layer };
@@ -1,49 +0,0 @@
1
- import { lines } from "./files.mjs";
2
- import { fileRoutes, routeHandler, routeImports } from "./routes.mjs";
3
- // src/init/astro.ts
4
- /**
5
- * What `init` writes in an Astro project on Node: an endpoint for each route, rendered on request
6
- * by `@astrojs/node`, and the adapter's step where the config has none or keeps its body limit.
7
- */
8
- /**
9
- * A route's endpoint under `src/pages/`, where a rest parameter matches an empty path too, and a
10
- * parameter such as `:repo` is the segment `[repo]`, with the text that follows it in the segment.
11
- */
12
- const pathOf = (route) => {
13
- const tail = {
14
- rest: "/[...path]",
15
- optional: "/[...path]",
16
- segment: "/[id]",
17
- none: ""
18
- }[route.tail];
19
- return `src/pages/${route.at.replace(/:(\w+)/g, "[$1]")}${tail}.ts`;
20
- };
21
- /** One endpoint: every method to Git's handler, rendered on request, never at build time. */
22
- const endpoint = (choices, route, module) => {
23
- const path = pathOf(route);
24
- return {
25
- path,
26
- kind: "whole",
27
- text: lines(`// ${route.says} Written by \`ref0-git init\`.`, "import type { APIRoute } from 'astro';", "", ...routeImports(choices), "", "// Loaded on the first request, so `astro build` opens no database and needs no secret.", ...routeHandler(choices, path, module), "", "export const prerender = false;", "", "export const ALL: APIRoute = ({ request }) => git(request);", "")
28
- };
29
- };
30
- /** Astro's endpoints for `choices`, over `framework`'s server module. */
31
- const astroRouteFiles = (choices, framework) => fileRoutes(choices).map((route) => endpoint(choices, route, framework.serverModule));
32
- /**
33
- * The adapter's step: `@astrojs/node` where the config has no adapter, and its `bodySizeLimit`,
34
- * 1 GiB by default, lifted where the config doesn't set it, so a larger push isn't cut off. The
35
- * limit is the adapter's, for every route, so the step says it lifts the app's own too.
36
- */
37
- const astroSteps = (framework) => {
38
- const config = framework.config;
39
- const node = framework.adapter?.name === "node";
40
- const call = node ? framework.adapter?.call ?? "node" : "node";
41
- if (node && config?.text.includes("bodySizeLimit")) return [];
42
- return [{
43
- path: config?.path ?? "astro.config.mjs",
44
- why: "yours",
45
- says: node ? "Lift @astrojs/node's 1 GiB bodySizeLimit, which cuts off a larger push, for every route, the app's own too" : "Serve Astro on Node with @astrojs/node, standalone, with no body limit for any route, the app's own too: astro add node installs it",
46
- lines: [...node ? [] : ["import node from '@astrojs/node';", ""], `adapter: ${call}({ mode: 'standalone', bodySizeLimit: 0 }),`]
47
- }];
48
- };
49
- export { astroRouteFiles, astroSteps };
@@ -1,152 +0,0 @@
1
- import { newFramework } from "./frameworks.mjs";
2
- import { nodeAt, parseJsonc } from "./jsonc.mjs";
3
- import { nextConfigAnchor } from "./next.mjs";
4
- import { shellWord } from "./shell.mjs";
5
- import { nuxtConfigAnchor } from "./nuxt.mjs";
6
- import { svelteAdapterAnchor } from "./sveltekit.mjs";
7
- import * as Schema from "effect/Schema";
8
- // src/init/create.ts
9
- /** The create commands' packages, at the versions each was run at on 20 Nov, as `init.md` lists. */
10
- const creators = {
11
- next: "create-next-app@16.5.0",
12
- sveltekit: "sv@1.7.1",
13
- nuxt: "create-nuxt@4.1.1"
14
- };
15
- /** The values `--framework` takes, in the table's order. */
16
- const creatable = Object.keys(creators);
17
- /**
18
- * The platforms a new app from each create command runs on, the first what `--yes` takes: a new
19
- * app is Node's, and Next.js's on Vercel too. Making one a Worker is its own setup.
20
- */
21
- const createPlatforms = {
22
- next: ["node", "vercel"],
23
- sveltekit: ["node"],
24
- nuxt: ["node"]
25
- };
26
- /** Each framework's config, as its anchor line alone: what `init` edits there, and nothing else. */
27
- const anchors = {
28
- next: [["next.config.ts", nextConfigAnchor]],
29
- sveltekit: [["vite.config.ts", `import adapter from ${svelteAdapterAnchor};\n`]],
30
- nuxt: [["nuxt.config.ts", nuxtConfigAnchor]]
31
- };
32
- /** The `package.json` a create command writes, as `creatorFolder` stands it in: two-space JSON. */
33
- const creatorManifest = /* @__PURE__ */ Schema.encodeSync(Schema.fromJsonString(Schema.Struct({
34
- name: Schema.String,
35
- dependencies: Schema.Record(Schema.String, Schema.String)
36
- }), { space: 2 }));
37
- /**
38
- * What a create command's folder holds for `--dry-run`, which runs nothing: only what `init` relies
39
- * on each command writing, not its files. That's a `package.json` naming the framework at the major
40
- * `init` was tested with, under the project's name, an empty `.gitignore`, and, for Next.js and
41
- * SvelteKit, their config's anchor line, which a real run edits in the file the command actually
42
- * wrote. A real run whose command wrote no anchor gives the step `template_changed` instead.
43
- */
44
- const creatorFolder = (framework, folder, name) => {
45
- const { dependency, majors } = newFramework(framework);
46
- const major = majors.at(-1);
47
- const read = new Map([
48
- ["package.json", `${creatorManifest({
49
- name,
50
- dependencies: { [dependency]: major === void 0 ? "*" : `^${major}` }
51
- })}\n`],
52
- [".gitignore", ""],
53
- ...anchors[framework]
54
- ]);
55
- return {
56
- name: folder.name,
57
- entries: [...read.keys()],
58
- read: (path) => read.get(path),
59
- isFolder: () => false,
60
- userAgent: folder.userAgent
61
- };
62
- };
63
- /** How each package manager runs a package it hasn't installed, without asking first. */
64
- const runners = {
65
- npm: ["npx", "--yes"],
66
- pnpm: ["pnpm", "dlx"],
67
- yarn: ["yarn", "dlx"],
68
- bun: ["bunx"]
69
- };
70
- /** A create command's own arguments, after its package, for `dir`, `manager` and the platform it's for. */
71
- const argumentsOf = {
72
- next: (dir, manager) => [
73
- dir,
74
- "--yes",
75
- "--ts",
76
- "--app",
77
- "--empty",
78
- "--no-tailwind",
79
- "--no-eslint",
80
- "--no-biome",
81
- "--no-src-dir",
82
- "--no-react-compiler",
83
- "--no-cache-components",
84
- "--no-agents-md",
85
- "--no-agent-feedback",
86
- "--import-alias",
87
- "@/*",
88
- `--use-${manager}`,
89
- "--skip-install",
90
- "--disable-git"
91
- ],
92
- sveltekit: (dir, manager) => [
93
- "create",
94
- dir,
95
- "--template",
96
- "minimal",
97
- "--types",
98
- "ts",
99
- "--no-add-ons",
100
- "--no-install",
101
- "--package-manager",
102
- manager
103
- ],
104
- nuxt: (dir, manager) => [
105
- dir,
106
- "--template",
107
- "minimal",
108
- "--no-install",
109
- "--no-gitInit",
110
- "--packageManager",
111
- manager,
112
- "--no-modules",
113
- "--force"
114
- ]
115
- };
116
- /** The create command for `framework` in `dir` on `platform`, run through `manager`. */
117
- const createCommand = (framework, dir, manager, platform) => {
118
- const argv = [
119
- ...runners[manager],
120
- creators[framework],
121
- ...argumentsOf[framework](dir, manager, platform)
122
- ];
123
- return {
124
- line: argv.map(shellWord).join(" "),
125
- argv
126
- };
127
- };
128
- /** Whether a create command's `package.json` names its framework, as one that ran through does. */
129
- const created = (framework, packageJson) => {
130
- const tree = packageJson === void 0 ? void 0 : parseJsonc(packageJson);
131
- return ["dependencies", "devDependencies"].some((key) => nodeAt(tree, [key, newFramework(framework).dependency]) !== void 0);
132
- };
133
- /**
134
- * `create_failed`'s document, for a create command that exited non-zero, or 0 with no
135
- * `package.json` naming the framework: what ran, how it ended, and the paths it left, which are
136
- * the command's and stay. Its next step removes them and runs the same `init` again.
137
- */
138
- const createFailed = (framework, command, ended, left) => ({
139
- reason: "create_failed",
140
- headline: ended.exit === 0 ? `${creators[framework]} exited 0 but wrote no package.json naming ${newFramework(framework).dependency}` : `${creators[framework]} ${ended.signal === null ? `exited ${ended.exit ?? "without a status"}` : `stopped on ${ended.signal}`}`,
141
- data: {
142
- create: {
143
- command: {
144
- line: command.line,
145
- argv: command.argv
146
- },
147
- ...ended
148
- },
149
- left
150
- }
151
- });
152
- export { creatable, createCommand, createFailed, createPlatforms, created, creatorFolder, creators };
@@ -1,104 +0,0 @@
1
- import { matcherCall, matcherImport } from "./routes.mjs";
2
- // src/init/mounts.ts
3
- /** Express's middleware, before any body parser, as printed source: the matcher's paths to Git. */
4
- const expressLine = (choices) => `app.use(toNodeMiddleware(runtime, (url) => ${matcherCall(choices)}))`;
5
- /**
6
- * The imports a mount's lines start with: `@ref0/git/node`'s `names`, Node's job runner, the
7
- * matcher, and the module's runtime, which serves Git's URLs and runs its jobs.
8
- */
9
- const imports = (choices, names) => [
10
- `import { ${names} } from '@ref0/git/node';`,
11
- matcherImport(choices),
12
- "import * as Node from '@ref0/infra/node';",
13
- "import { runtime } from './git.ts';",
14
- ""
15
- ];
16
- /** What Hono's lines take from Node and `@hono/node-server`: a server, and the app as a listener. */
17
- const honoImports = ["import { createServer } from 'node:http';", "import { getRequestListener } from '@hono/node-server';"];
18
- /**
19
- * Git's jobs, started, and stopped on `SIGTERM`. A listener takes away Node's own exit on it, so
20
- * the listener runs once, then raises it again for Node, or the person's own listener, to exit.
21
- */
22
- const startLines = [
23
- "const stop = Node.toJobRunner(runtime);",
24
- "",
25
- "process.once('SIGTERM', () => void stop().finally(() => process.kill(process.pid, 'SIGTERM')));"
26
- ];
27
- /** Each server's lines, after its imports. */
28
- const mountLines = (server, choices) => {
29
- if (server === "hono") return [
30
- ...startLines,
31
- "",
32
- `const mount = toNodeMiddleware(runtime, (url) => ${matcherCall(choices)});`,
33
- "",
34
- "const listener = getRequestListener(app.fetch);",
35
- "",
36
- "// In place of serve(), after the app's routes: Git answers its URLs in front of the app, as",
37
- "// Express's middleware does, so Hono's middleware doesn't run on them; a guard for Git goes",
38
- "// in git.ts's policy. Every other request goes on to the app. Over HTTP/2, node:http2's",
39
- "// createSecureServer takes it too.",
40
- "createServer((incoming, outgoing) =>",
41
- " mount(incoming, outgoing, () => void listener(incoming, outgoing)),",
42
- ").listen(Number(process.env['PORT'] ?? 3000));"
43
- ];
44
- if (server === "express") return [
45
- ...startLines,
46
- "",
47
- "// Before express.json() or any body parser, which would read the body Git streams.",
48
- `${expressLine(choices)};`
49
- ];
50
- return [
51
- "const stop = Node.toJobRunner(runtime);",
52
- "",
53
- "app.addHook('onClose', () => stop());",
54
- "",
55
- "// Git's URLs, answered before Fastify parses a body, so the body streams to Git and your routes",
56
- "// keep their parsers and bodyLimit. The middleware calls its next before it returns, or never.",
57
- `const mount = toNodeMiddleware(runtime, (url) => ${matcherCall(choices)});`,
58
- "",
59
- "app.addHook('onRequest', (request, reply, done) => {",
60
- " let passed = false;",
61
- " mount(request.raw, reply.raw, () => (passed = true));",
62
- "",
63
- " if (!passed) reply.hijack();",
64
- " done();",
65
- "});"
66
- ];
67
- };
68
- const mounting = (name) => name === "hono" || name === "express" || name === "fastify";
69
- /** Each server's step, in a few words. */
70
- const says = {
71
- hono: "Start Git's jobs and serve it in front of your Hono app, in the file that makes it, in place of serve()",
72
- express: "Start Git's jobs and serve it, in the file that makes your Express app, before any body parser",
73
- fastify: "Start Git's jobs and serve it, in the file that makes your Fastify app, from an onRequest hook"
74
- };
75
- /**
76
- * The printed step that mounts Git in the person's server: `framework`'s own words for Hono,
77
- * Express and Fastify, whatever their major, and for any other `node:http`'s, where Git takes every
78
- * path, and Express's, commented.
79
- */
80
- const mountManual = (choices, framework) => {
81
- if (mounting(framework)) return {
82
- path: "its server",
83
- why: "yours",
84
- says: says[framework],
85
- lines: [
86
- ...framework === "hono" ? honoImports : [],
87
- ...imports(choices, "toNodeMiddleware"),
88
- ...mountLines(framework, choices)
89
- ]
90
- };
91
- return {
92
- path: "its server",
93
- why: "yours",
94
- says: "Start Git's jobs and serve it, before any body parser, which would read the body Git streams",
95
- lines: [
96
- ...imports(choices, "toNodeHandler, toNodeMiddleware"),
97
- ...startLines,
98
- "",
99
- "// node:http: createServer(toNodeHandler(runtime)).",
100
- `// Express, before express.json(): ${expressLine(choices)}.`
101
- ]
102
- };
103
- };
104
- export { mountManual };