ref0-git 0.7.0 → 0.8.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.
@@ -1,6 +1,6 @@
1
1
  import { fitted, ignoring, lines, withCli, withDependencies, withLines } from "./files.mjs";
2
- import { basePathLines, gitDependencies, gitImports, gitPackages, githubHandler, header, looseObjects, queueLine } from "./git-module.mjs";
3
- import { itemsAt, jsonString, manifestText, parseJsonc, stringAt, withEntries, withValue } from "./jsonc.mjs";
2
+ import { effectImports, featuresLines, gitDependencies, gitImports, gitPackages, header, runtimeLines, writtenCpu } from "./git-module.mjs";
3
+ import { itemsAt, jsonString, manifestText, nodeAt, parseJsonc, stringAt, withEntries, withValue } from "./jsonc.mjs";
4
4
  import { filled, templates, unless } from "./template.mjs";
5
5
  import { catalog } from "./metadata.mjs";
6
6
  import * as Redacted from "effect/Redacted";
@@ -15,21 +15,10 @@ import * as Redacted from "effect/Redacted";
15
15
  const secretFiles = [".dev.vars"];
16
16
  /** The secrets Git's Worker takes: the admin's, which signs in to make repos and tokens. */
17
17
  const gitSecrets = ["ADMIN_TOKEN"];
18
- /** The handlers an entry imports from `src/git.ts`, and how it routes to them. */
19
- const routing = {
20
- github: {
21
- names: "github, rest",
22
- first: (request) => `(await github.route(${request})) ?? (await rest.route(${request}))`
23
- },
24
- api: {
25
- names: "rest",
26
- first: (request) => `(await rest.route(${request}))`
27
- },
28
- git: {
29
- names: "git",
30
- first: (request) => `(await git.route(${request}))`
31
- }
32
- };
18
+ /** What an entry that falls through to its host's own `fetch` imports, to route Git's URLs first. */
19
+ const fallThroughImports = lines("import { Git } from '@ref0/git';", "import * as Option from 'effect/Option';");
20
+ /** Git's answer to `request` on the module's runtime, `undefined` for a URL no route of Git's owns. */
21
+ const routed = (request) => `Option.getOrUndefined(await runtime.runPromise(Git.route(${request})))`;
33
22
  /** The bindings and classes Git needs. */
34
23
  const gitClasses = [{
35
24
  name: "RECORDS",
@@ -41,36 +30,37 @@ const gitClasses = [{
41
30
  /** The infra import of a `src/git.ts` with no bucket. */
42
31
  const looseInfraImport = "import { layer, toJobObject, toRecordsObject } from '@ref0/infra/cloudflare';";
43
32
  /** The adapter of a `src/git.ts` with no bucket: the records and jobs' Layer alone. */
44
- const looseAdapter = " adapter: layer({ records: env.RECORDS, jobs: env.JOBS }),";
33
+ const looseAdapter = lines("/** The records and job objects. */", "const adapter = layer({ records: env.RECORDS, jobs: env.JOBS });", "", "");
34
+ /** A push's pack upload, once the bucket signs parts: `signed` only with R2's S3 credentials. */
35
+ const uploads = lines(" // A push past 64 MiB may upload its pack, once the bucket signs parts.", " signed === undefined", " ? Layer.empty", " : Layer.provide(Git.layerUploads({ above: 64 * 1024 * 1024 }), signed),");
45
36
  /** `src/git.ts`: `examples/git-worker`'s own, with what it serves, the store and the queue as chosen. */
46
- const gitModule = (choices, envFile) => {
37
+ const gitModule = (choices, envFile, cpu) => {
47
38
  const packs = choices.objects === "packs";
48
- const queue = choices.queue === "on";
49
- const github = choices.serve === "github";
50
- const basePath = basePathLines(choices);
51
39
  return filled(templates.workerGit, {
52
40
  header: `${header(choices, "Cloudflare")}\n`,
53
41
  gitImports: `${gitImports(choices)}\n`,
54
42
  infraImport: unless(packs, looseInfraImport),
43
+ effectImports: `${effectImports(choices)}\n`,
55
44
  envFile: `'${envFile}'`,
56
45
  safety: unless(packs, "binds the objects"),
57
- bucket: unless(packs, ""),
58
- adapter: unless(packs, looseAdapter),
59
- merge: unless(queue, ""),
60
- objects: unless(packs, looseObjects),
61
- lfs: unless(packs, ""),
62
- uploads: unless(packs, ""),
63
- basePath: basePath === false ? void 0 : `${basePath}\n`,
64
- queue: queue ? `${queueLine(github)}\n` : "",
65
- github: github ? `${githubHandler}\n` : void 0,
66
- rest: choices.serve === "git" ? "" : void 0
46
+ bucket: unless(packs, looseAdapter),
47
+ merge: unless(choices.queue === "on", ""),
48
+ features: `${featuresLines(choices, {
49
+ cpu,
50
+ merges: "{ xdiff }",
51
+ uploads: packs && uploads
52
+ })}\n`,
53
+ runtime: `${runtimeLines(choices, {
54
+ token: "env.ADMIN_TOKEN",
55
+ adapter: "adapter"
56
+ })}\n`
67
57
  });
68
58
  };
69
- /** `src/worker.ts`'s default export, for what it serves past the example's REST. */
70
- const workerExports = {
71
- github: lines("/** The drop-in's URLs, then Git's REST and protocol, then a JSON `404`. */", "export default {", " fetch: async (request) => (await github.route(request)) ?? rest.fetch(request),", "} satisfies ExportedHandler<Env>;", ""),
72
- api: "/** Git's REST and protocol, then a JSON `404`. */\nexport default { fetch: rest.fetch } satisfies ExportedHandler<Env>;\n",
73
- git: "/** Git's protocol and sign-in, then a JSON `404`. */\nexport default { fetch: git.fetch } satisfies ExportedHandler<Env>;\n"
59
+ /** What a Worker `init` writes serves, which its entry's comment names. */
60
+ const servedSays = {
61
+ github: "The drop-in's URLs, Git's REST and protocol",
62
+ api: "Git's REST and protocol",
63
+ git: "Git's protocol and sign-in"
74
64
  };
75
65
  /**
76
66
  * `src/worker.ts`, the entry of a Worker `init` writes whole: `examples/git-worker`'s own, without
@@ -78,8 +68,7 @@ const workerExports = {
78
68
  */
79
69
  const workerEntry = (choices) => filled(templates.workerEntry, {
80
70
  gate: "",
81
- names: `import { ${routing[choices.serve].names} } from './git.ts';`,
82
- exports: workerExports[choices.serve]
71
+ exports: lines(`/** ${servedSays[choices.serve]}, then a JSON \`404\`. */`, "export default { fetch: Git.toFetch(runtime) } satisfies ExportedHandler<Env>;", "")
83
72
  });
84
73
  /** `main`'s path as `src/git-entry.ts` imports it. */
85
74
  const fromEntry = (main) => {
@@ -87,9 +76,9 @@ const fromEntry = (main) => {
87
76
  return up.startsWith("../") ? up : `./${up}`;
88
77
  };
89
78
  /** `src/git-entry.ts`: an existing Worker's new `main`, which runs its own after Git's URLs. */
90
- const wrappedEntry = (choices, main) => lines("// This Worker's entry, written by `ref0-git init`: Git's URLs first, then the Worker in", `// \`${main}\`, whose other exports and handlers it keeps. \`wrangler.jsonc\`'s \`main\` names it.`, `import worker from '${fromEntry(main)}';`, "", `import { ${routing[choices.serve].names} } from './git.ts';`, "", `export * from '${fromEntry(main)}';`, "", "export { Jobs, Records } from './git.ts';", "", "export default {", " ...worker,", " fetch: async (...call: Parameters<typeof worker.fetch>) =>", ` ${routing[choices.serve].first("call[0]")} ?? worker.fetch(...call),`, "};", "");
79
+ const wrappedEntry = (main) => lines("// This Worker's entry, written by `ref0-git init`: Git's URLs first, then the Worker in", `// \`${main}\`, whose other exports and handlers it keeps. \`wrangler.jsonc\`'s \`main\` names it.`, fallThroughImports, "", `import worker from '${fromEntry(main)}';`, "", "import { runtime } from './git.ts';", "", `export * from '${fromEntry(main)}';`, "", "export { Jobs, Records } from './git.ts';", "", "export default {", " ...worker,", " fetch: async (...call: Parameters<typeof worker.fetch>) =>", ` ${routed("call[0]")} ?? worker.fetch(...call),`, "};", "");
91
80
  /** `src/server.ts`: Start's server entry, Git's URLs before the app's. */
92
- const startEntry = (choices) => lines("// Start's server entry, written by `ref0-git init`: Git's URLs first, then the app.", "// `wrangler.jsonc`'s `main` names it, so the Worker exports Git's two classes too.", "import handler, { createServerEntry } from '@tanstack/react-start/server-entry';", "", `import { ${routing[choices.serve].names} } from './git.ts';`, "", "export { Jobs, Records } from './git.ts';", "", "export default createServerEntry({", fitted(" fetch: async (request) =>", `${routing[choices.serve].first("request")} ?? handler.fetch(request),`), "});", "");
81
+ const startEntry = lines("// Start's server entry, written by `ref0-git init`: Git's URLs first, then the app.", "// `wrangler.jsonc`'s `main` names it, so the Worker exports Git's two classes too.", fallThroughImports, "import handler, { createServerEntry } from '@tanstack/react-start/server-entry';", "", "import { runtime } from './git.ts';", "", "export { Jobs, Records } from './git.ts';", "", "export default createServerEntry({", fitted(" fetch: async (request) =>", `${routed("request")} ?? handler.fetch(request),`), "});", "");
93
82
  /** `src/env.ts`, or `src/git-env.ts` beside a project's own: `examples/git-worker`'s, as the store has it. */
94
83
  const envModule = (choices) => {
95
84
  const packs = choices.objects === "packs";
@@ -102,6 +91,8 @@ const envModule = (choices) => {
102
91
  const bucketName = (name) => `${name}-packs`;
103
92
  /** `wrangler.jsonc`'s bucket line, with its newline, for a store that has one. */
104
93
  const bucketLine = (choices, name) => choices.objects === "packs" ? ` "r2_buckets": [{ "binding": "PACKS", "bucket_name": "${bucketName(name)}" }],\n` : "";
94
+ /** `wrangler.jsonc`'s CPU a request may use, which `Lfs.layer` in `src/git.ts` takes too. */
95
+ const limitsLine = ` "limits": { "cpu_ms": ${writtenCpu.ms} },`;
105
96
  /** `wrangler.jsonc` for a Worker `init` writes whole: `examples/git-worker`'s, named `name`. */
106
97
  const wranglerConfig = (choices, name) => {
107
98
  const packs = choices.objects === "packs";
@@ -109,6 +100,7 @@ const wranglerConfig = (choices, name) => {
109
100
  about: unless(packs, "Durable Object classes"),
110
101
  signing: unless(packs, ""),
111
102
  name: ` "name": ${jsonString(name)},`,
103
+ limits: limitsLine,
112
104
  bucket: bucketLine(choices, name),
113
105
  vars: packs ? ` "vars": { "PACKS_BUCKET": "${bucketName(name)}" },\n` : ""
114
106
  });
@@ -126,6 +118,38 @@ const bound = (text, path, key) => itemsAt(parseJsonc(text), path).flatMap((item
126
118
  /** Each string a TOML config sets `key` to, basic or literal, on a line of its own or in an array. */
127
119
  const tomlStrings = (text, key) => [...text.matchAll(new RegExp(`^\\s*${key}\\s*=\\s*(\\[[^\\]]*\\]|"[^"]*"|'[^']*')`, "gm"))].flatMap((line) => [...(line[1] ?? "").matchAll(/"([^"]*)"|'([^']*)'/g)].map((each) => each[1] ?? each[2] ?? ""));
128
120
  /**
121
+ * The CPU a Worker's config gives one request, its `limits.cpu_ms`, if it sets one: where it sets
122
+ * none, the platform's default, which the adapter holds an upload to.
123
+ */
124
+ const configCpu = (file, text) => {
125
+ const raw = file === "wrangler.toml" ? tomlCpu(text) : rawAt(nodeAt(parseJsonc(text), ["limits", "cpu_ms"]));
126
+ return raw !== void 0 && /^\d+$/.test(raw) && Number(raw) > 0 ? {
127
+ ms: Number(raw),
128
+ file
129
+ } : void 0;
130
+ };
131
+ /** How a `wrangler.toml` line sets the root `limits.cpu_ms`, by the table it's in: none in an env's. */
132
+ const tomlCpuLines = /* @__PURE__ */ new Map([["limits", /^cpu_ms\s*=\s*([\d_]+)$/], ["", /^limits\s*(?:\.\s*cpu_ms\s*=|=\s*\{.*\bcpu_ms\s*=)\s*([\d_]+)/]]);
133
+ /**
134
+ * A `wrangler.toml`'s root `limits.cpu_ms`, its digits without their `_`: in its `[limits]` table,
135
+ * or as `limits = { cpu_ms = … }` or `limits.cpu_ms = …` before any table, never an env's.
136
+ */
137
+ const tomlCpu = (text) => {
138
+ let table = "";
139
+ for (const line of text.split("\n")) {
140
+ const bare = line.replace(/#.*$/, "").trim();
141
+ const header = /^\[\s*([^\]]+?)\s*\]$/.exec(bare)?.[1];
142
+ if (header !== void 0) {
143
+ table = header.replace(/^(["'])(.*)\1$/, "$2");
144
+ continue;
145
+ }
146
+ const found = tomlCpuLines.get(table)?.exec(bare)?.[1];
147
+ if (found !== void 0) return found.replaceAll("_", "");
148
+ }
149
+ };
150
+ /** A JSONC value's text, when `node` is one and not an object or an array. */
151
+ const rawAt = (node) => node?.kind === "value" ? node.raw : void 0;
152
+ /**
129
153
  * What `doctor` reads of a Worker's config, `wrangler.jsonc` or `wrangler.json` as JSONC, and
130
154
  * `wrangler.toml`, which `init` writes nothing into, by its lines: its `main`, the Durable Objects
131
155
  * it binds, the classes its migrations make, the buckets it binds and the D1 databases it binds
@@ -195,11 +219,28 @@ const devVars = (names, secret) => ({
195
219
  secrets: names,
196
220
  merge: (current) => withLines(current, names.map((name) => `${name}=${Redacted.value(secret())}`), (line) => line.split("=")[0] ?? "")
197
221
  });
222
+ /**
223
+ * The packs' bucket's rule that aborts an upload a day after it began: one a crashed merge left,
224
+ * which no row names, ends no other way (#2226). Alchemy clears every rule its bucket doesn't
225
+ * declare, so it goes in the bucket's line, as `examples/git-alchemy` has it.
226
+ */
227
+ const abortUploads = [
228
+ " lifecycleRules: [",
229
+ " {",
230
+ " id: \"abort-uploads\",",
231
+ " abortMultipartUploadsTransition: { condition: { type: \"Age\", maxAge: 86_400 } },",
232
+ " },",
233
+ " ],"
234
+ ];
198
235
  /** Alchemy's lines for Git's part of a Worker's `env`, as the Alchemy guide gives them. */
199
236
  const alchemyLines = (choices, _name) => [
200
237
  " RECORDS: Cloudflare.DurableObject(\"Records\"),",
201
238
  " JOBS: Cloudflare.DurableObject(\"Jobs\"),",
202
- ...choices.objects === "packs" ? [" PACKS: Cloudflare.R2.Bucket(\"Packs\"),"] : [],
239
+ ...choices.objects === "packs" ? [
240
+ " PACKS: Cloudflare.R2.Bucket(\"Packs\", {",
241
+ ...abortUploads,
242
+ " }),"
243
+ ] : [],
203
244
  " ADMIN_TOKEN: Config.Redacted(\"ADMIN_TOKEN\"),"
204
245
  ];
205
246
  /** The lines a `wrangler.toml` needs, since `init` writes no TOML. */
@@ -221,11 +262,13 @@ const tomlLines = (choices, name) => [
221
262
  "new_sqlite_classes = [\"Records\", \"Jobs\"]"
222
263
  ];
223
264
  /** What a Worker's own entry needs, to answer Git's URLs first and export its classes. */
224
- const entryLines = (choices, _name) => [
225
- `import { ${routing[choices.serve].names} } from './git.ts';`,
265
+ const entryLines = (_choices, _name) => [
266
+ "import { Git } from '@ref0/git';",
267
+ "import * as Option from 'effect/Option';",
268
+ "import { runtime } from './git.ts';",
226
269
  "export { Jobs, Records } from './git.ts';",
227
270
  "// First in its fetch, before its own routes:",
228
- `const answered = ${routing[choices.serve].first("request")};`,
271
+ `const answered = ${routed("request")};`,
229
272
  "if (answered !== undefined) return answered;"
230
273
  ];
231
274
  /** The lines each kind of manual step prints. */
@@ -251,12 +294,12 @@ const entryOf = (choices, layout) => {
251
294
  };
252
295
  case "wrapped": return {
253
296
  path: "src/git-entry.ts",
254
- text: wrappedEntry(choices, layout.main),
297
+ text: wrappedEntry(layout.main),
255
298
  main: "src/git-entry.ts"
256
299
  };
257
300
  case "start": return {
258
301
  path: "src/server.ts",
259
- text: startEntry(choices),
302
+ text: startEntry,
260
303
  main: "src/server.ts"
261
304
  };
262
305
  case "manual":
@@ -270,9 +313,11 @@ const cloudflareOutput = (choices, project, secret, vendor) => {
270
313
  const envFile = own ? "env.ts" : "git-env.ts";
271
314
  const entry = entryOf(choices, layout);
272
315
  const config = project.config?.file ?? "wrangler.jsonc";
316
+ const jsonc = config !== "wrangler.toml" && !(layout.kind === "manual" && layout.why === "alchemy");
317
+ const cpu = project.config === void 0 ? jsonc ? writtenCpu : void 0 : configCpu(project.config.file, project.config.text);
273
318
  return {
274
319
  files: [
275
- ...config !== "wrangler.toml" && !(layout.kind === "manual" && layout.why === "alchemy") ? [{
320
+ ...jsonc ? [{
276
321
  path: config,
277
322
  kind: "merge",
278
323
  merge: (current) => current === void 0 ? wranglerConfig(choices, name) : mergeWrangler(current, choices, name, entry?.main)
@@ -285,7 +330,7 @@ const cloudflareOutput = (choices, project, secret, vendor) => {
285
330
  {
286
331
  path: "src/git.ts",
287
332
  kind: "whole",
288
- text: gitModule(choices, `./${envFile}`)
333
+ text: gitModule(choices, `./${envFile}`, cpu)
289
334
  },
290
335
  ...entry === void 0 ? [] : [{
291
336
  path: entry.path,
@@ -321,4 +366,4 @@ const cloudflareOutput = (choices, project, secret, vendor) => {
321
366
  next: "Check it, then deploy it"
322
367
  };
323
368
  };
324
- export { bucketLine, bucketName, cloudflareOutput, configParts, devVars, gitClasses, gitModule, gitSecrets, looseAdapter, looseInfraImport, mergePackage, mergeWrangler, secretFiles };
369
+ export { bucketLine, bucketName, cloudflareOutput, configCpu, configParts, devVars, gitClasses, gitModule, gitSecrets, limitsLine, looseAdapter, looseInfraImport, mergePackage, mergeWrangler, secretFiles };
@@ -54,13 +54,13 @@ const readBack = (text) => {
54
54
  const onNode = !vercel && (imports("node") || imports("sqlite"));
55
55
  if (!vercel && !onNode && !imports("cloudflare")) return void 0;
56
56
  const app = text.includes("from './signin/auth.ts'");
57
- const loose = app ? text.includes("\nconst objects = Objects.layerRecords();") : /\bloose\(\)/.test(text);
58
- const queue = app ? text.includes("MergeQueue.layer({ target: 'refs/heads/main', keys: 'once', merge: queueMerge })") : text.includes("mergeQueue(");
57
+ const loose = /\bObjects\.layerRecords\(\)/.test(text);
58
+ const queue = text.includes("MergeQueue.layer({ target: 'refs/heads/main', keys: ");
59
59
  const shared = {
60
- serve: text.includes("from '@ref0/github'") ? "github" : text.includes("from '@ref0/git/rest'") ? "api" : "git",
60
+ serve: text.includes("from '@ref0/github'") ? "github" : /^ {2}Rest\.layer\(\),$/m.test(text) ? "api" : "git",
61
61
  app: app ? "ref0" : "none",
62
62
  queue: queue ? "on" : "off",
63
- basePath: /^ {2}basePath: '([^']*)',$/m.exec(text)?.[1] ?? "/"
63
+ basePath: /\bGit\.layer\(\{ basePath: '([^']*)'/.exec(text)?.[1] ?? "/"
64
64
  };
65
65
  if (vercel) return {
66
66
  ...shared,
@@ -1,11 +1,12 @@
1
- import { peerPackages } from "./metadata.mjs";
2
1
  import { lines, served } from "./files.mjs";
2
+ import { peerPackages, workerCpuMs } from "./metadata.mjs";
3
3
  import { specOf } from "./versions.mjs";
4
+ import * as Predicate from "effect/Predicate";
4
5
  import { looseLimits } from "@ref0/git";
5
6
  // src/init/git-module.ts
6
7
  /**
7
- * The lines Cloudflare's and Node's `src/git.ts` share, from its imports of Git to its handlers,
8
- * so the two say one thing the same way.
8
+ * The lines every platform's `src/git.ts` shares, from its imports of Git to its runtime, so each
9
+ * composes Git the same way: Git's features and the drop-in's over `Git.layer`, one runtime.
9
10
  */
10
11
  /** Git's packages a setup depends on, at this release. */
11
12
  const gitPackages = (choices) => [
@@ -19,44 +20,102 @@ const gitPackages = (choices) => [
19
20
  * take at the catalog's version: a project's own `effect` is the one Git's packages run on.
20
21
  */
21
22
  const gitDependencies = (choices, vendor) => [...gitPackages(choices).map((each) => [each, specOf(each, vendor)]), ...Object.entries(peerPackages)];
23
+ /** Where a host that serves Git's protocol alone makes its repos: from code, on its runtime. */
24
+ const repoHint = lines("// Nothing here makes a repo over HTTP: make one from code, as", "// `runtime.runPromise(Repos.create({ name: 'acme/app' }))`.");
22
25
  /** `src/git.ts`'s first lines: what it serves, on `on`, and whose file it is. */
23
- const header = (choices, on) => lines(`// Git on ${on}, ${served[choices.serve]}${choices.queue === "on" ? ", with a merge queue on `main`" : ""}. Written by`, "// `ref0-git init`, and yours to change: `init` rewrites it only while it reads as written, and", "// `ref0-git doctor` checks it.", choices.serve === "git" && "// Nothing here makes a repo over HTTP: make one from code, as `git.repos.create({ name: 'acme/app' })`.");
24
- /** The `@ref0/git` import, naming what the choices use. */
25
- const gitImport = (choices) => {
26
- const packs = choices.objects === "packs";
27
- const queue = choices.queue === "on";
28
- return `import { accept, createGitServer, ${packs ? "lfs, " : "loose, "}${queue ? "mergeQueue, " : ""}${packs ? "packs, " : ""}reject } from '@ref0/git';`;
26
+ const header = (choices, on) => lines(`// Git on ${on}, ${served[choices.serve]}${choices.queue === "on" ? ", with a merge queue on `main`" : ""}. Written by`, "// `ref0-git init`, and yours to change: `init` rewrites it only while it reads as written, and", "// `ref0-git doctor` checks it.", choices.serve === "git" && repoHint);
27
+ /** The `@ref0/git` names the composition uses, as chosen. */
28
+ const gitNames = (choices) => [
29
+ choices.serve === "github" && "accept",
30
+ "Auth",
31
+ "Git",
32
+ choices.objects === "packs" && "Lfs",
33
+ choices.queue === "on" && "MergeQueue",
34
+ "Merges",
35
+ "Objects",
36
+ "Policy",
37
+ choices.serve !== "git" && "Rest",
38
+ "Tokens"
39
+ ].filter(Predicate.isString);
40
+ /** The drop-in's names, under `--serve github`: Releases only beside a bucket. */
41
+ const githubNames = (choices) => [
42
+ "Apps",
43
+ "Deployments",
44
+ "GitHub",
45
+ "GitHubPolicy",
46
+ "Imports",
47
+ "Inbox",
48
+ "People",
49
+ choices.objects === "packs" && "Releases",
50
+ "Search",
51
+ "Streams",
52
+ "Webhooks",
53
+ "defaultPeople"
54
+ ].filter(Predicate.isString);
55
+ /** An import of `names` from `from`, as the formatter writes it: on one line where it fits. */
56
+ const namedImport = (names, from) => {
57
+ const line = `import { ${names.join(", ")} } from '${from}';`;
58
+ return line.length <= 100 ? line : `import {\n${names.map((name) => ` ${name},`).join("\n")}\n} from '${from}';`;
29
59
  };
30
60
  /** Git's imports, from `@ref0/git` to the drop-in. */
31
- const gitImports = (choices) => lines(gitImport(choices), choices.queue === "on" && "import type { MergeInput, MergePlan } from '@ref0/git';", "import { bearer, tokens } from '@ref0/git/auth';", choices.serve !== "git" && "import { createRestHandler } from '@ref0/git/rest';", choices.serve === "github" && "import { createGitHubHandler } from '@ref0/github';");
61
+ const gitImports = (choices) => lines(namedImport(gitNames(choices), "@ref0/git"), choices.queue === "on" && "import type { MergeInput, MergePlan } from '@ref0/git';", choices.serve === "github" && lines("import { JoinedCalls } from '@ref0/git/extend';", namedImport(githubNames(choices), "@ref0/github"), "import * as Languages from '@ref0/github/languages';"));
62
+ /** Effect's imports, which the composition is written in. */
63
+ const effectImports = (choices) => lines(choices.serve === "github" && lines("import * as Effect from 'effect/Effect';", "import * as FetchHttpClient from 'effect/http/FetchHttpClient';"), "import * as Layer from 'effect/Layer';", "import * as ManagedRuntime from 'effect/ManagedRuntime';", "import * as Redacted from 'effect/Redacted';");
32
64
  /** Who `ADMIN_TOKEN` signs in as. */
33
65
  const adminLines = lines("/** Who `ADMIN_TOKEN` signs in as: it makes repos and tokens, and never pushes. */", "const admin = { id: '_admin' };", "");
34
66
  /** How the queue writes an entry onto `main`, when there's a queue. */
35
67
  const mergeLines = (choices) => choices.queue === "on" && lines("/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */", "const merge = ({ entry }: MergeInput): MergePlan => ({", " method: 'merge',", " message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,", " author: {", " name: entry.actor.id,", " email: `${entry.actor.id}@users.noreply.git`,", " at: Date.now(),", " offset: 0,", " },", "});", "");
36
- /** `createGitServer`'s lines for a push's pack upload, once the bucket signs parts. */
37
- const uploads = " // A push past 64 MiB may upload its pack, once the bucket signs parts.\n pushes: { upload: { above: 64 * 1024 * 1024 } },";
38
- /** What one push may carry into `loose()`, as `@ref0/git` holds it. */
68
+ /** Who may do what: the admin's and a visitor's limits, as `Policy` decides them. */
69
+ const policyLines = lines("/**", " * Who may do what: a visitor signs in first, and the admin makes repos and tokens but never", " * pushes.", " */", "const policy = Policy.make(({ caller: { actor }, operation }) => {", " if (actor.anonymous === true) return Policy.reject({ message: 'Sign in first' });", "", " if (actor.id === admin.id && operation.kind === 'push') {", " return Policy.reject({", " message: \"The admin token can't push\",", " hint: 'Make a write token for yourself: npx ref0-git tokens create --help',", " });", " }", "", " return Policy.accept();", "});", "");
70
+ /** What one push may carry into `Objects.layerRecords()`, as `@ref0/git` holds it. */
39
71
  const looseSays = `up to ${looseLimits.objects.toLocaleString("en-US")} objects and ${looseLimits.bytes / 1024 / 1024} MiB a push`;
40
- /** `createGitServer`'s `lfs`, beside a bucket: LFS is on only when the host turns it on. */
41
- const lfsLines = " // Git LFS, its objects in the bucket beside the packs.\n lfs: lfs(),";
42
- /** `createGitServer`'s `objects` with no bucket: each object a row, and what `loose()` takes. */
43
- const looseObjects = ` // Each object a row in its push's commit: no bucket, ${looseSays}.\n objects: loose(),`;
44
- /** `createGitServer`'s `basePath`, when Git's URLs are under one. */
45
- const basePathLines = (choices) => choices.basePath !== "/" && ` // Git's URLs, Smart HTTP, sign-in and REST, under this path.\n basePath: '${choices.basePath.replace(/\/$/, "")}',`;
72
+ /** What a Worker `init` writes its config whole for: `workerCpuMs`, in `wrangler.jsonc`. */
73
+ const writtenCpu = {
74
+ ms: workerCpuMs,
75
+ file: "wrangler.jsonc"
76
+ };
77
+ /**
78
+ * `Lfs.layer`'s line at `indent`, with its comment: on a Worker whose config sets `limits.cpu_ms`,
79
+ * its uploads held to that `cpu`, and elsewhere to what the adapter says its platform gives.
80
+ */
81
+ const lfsLines = (indent, cpu) => cpu === void 0 ? `${indent}// Git LFS, its objects in the bucket beside the packs.\n${indent}Lfs.layer(),` : lines(`${indent}// Git LFS, its objects in the bucket beside the packs. An upload through the Worker may use`, `${indent}// \`limits.cpu_ms\` from ${cpu.file}: raise both together.`, `${indent}Lfs.layer({ cpuMs: ${cpu.ms.toLocaleString("en-US").replaceAll(",", "_")} }),`);
46
82
  /**
47
83
  * The queue's line: under the drop-in, a pull request's key merges once, so a push to it after its
48
84
  * merge isn't queued again before the drop-in sees the merge.
49
85
  */
50
- const queueLine = (github) => ` queue: mergeQueue({ target: 'refs/heads/main', keys: '${github ? "once" : "reusable"}', merge }),`;
51
- /** The drop-in's handler, under `--serve github`. */
52
- const githubHandler = "/**\n * GitHub's REST, GraphQL, webhooks and Event Streams, so `gh` and Octokit work, with the owner\n * index, so repo and user search answer, and `org:` and `user:` search an owner's public repos.\n */\nexport const github = createGitHubHandler(git, { ownerIndex: {} });\n";
53
- /** `export const git = createGitServer({ … });`, as chosen. */
54
- const serverLines = (choices, parts) => lines("export const git = createGitServer({", parts.adapter, choices.objects === "packs" ? " objects: packs()," : looseObjects, parts.xdiff, " tokens: tokens(),", choices.objects === "packs" && " // Git LFS, its objects in the bucket beside the packs.\n lfs: lfs(),", parts.uploads && " // A push past 64 MiB may upload its pack, once the bucket signs parts.\n pushes: { upload: { above: 64 * 1024 * 1024 } },", basePathLines(choices), ` auth: bearer({ token: ${parts.token}, actor: admin }),`, " authorize: ({ actor, operation }) => {", " if (actor.anonymous === true) return reject({ message: 'Sign in first' });", "", " if (actor.id === admin.id && operation.kind === 'push') {", " return reject({", " message: \"The admin token can't push\",", " hint: 'Make a write token for yourself: npx ref0-git tokens create --help',", " });", " }", "", " return accept();", " },", choices.queue === "on" && queueLine(choices.serve === "github"), "});", "");
55
- /** The drop-in's and the REST's handlers, as served: none for Git's protocol alone. */
56
- const handlerLines = (choices) => choices.serve !== "git" && lines(choices.serve === "github" && "/**\n * GitHub's REST, GraphQL, webhooks and Event Streams, so `gh` and Octokit work, with the owner\n * index, so repo and user search answer, and `org:` and `user:` search an owner's public repos.\n */\nexport const github = createGitHubHandler(git, { ownerIndex: {} });\n", "/** Git's REST, whose `route` and `fetch` serve Git's protocol and sign-in too. */\nexport const rest = createRestHandler(git);\n");
86
+ const queueLine = (github) => ` MergeQueue.layer({ target: 'refs/heads/main', keys: '${github ? "once" : "reusable"}', merge }),`;
87
+ /** Git's own features, `features`: REST, Git LFS and the queue as chosen, over tokens and merges. */
88
+ const gitFeatures = (choices, parts) => {
89
+ const each = [
90
+ choices.serve !== "git" && " // Git's REST, beside Git's protocol and sign-in.\n Rest.layer(),",
91
+ choices.objects === "packs" && lfsLines(" ", parts.cpu),
92
+ parts.uploads,
93
+ choices.queue === "on" && queueLine(choices.serve === "github")
94
+ ].filter(Predicate.isString);
95
+ const merges = `Layer.provideMerge(Merges.layer(${parts.merges}))`;
96
+ const below = `).pipe(Layer.provideMerge(Tokens.layer()), ${merges});`;
97
+ return lines("/** Git's features, each a line: delete one to turn it off. */", each.length === 0 ? `const features = Tokens.layer().pipe(Layer.provideMerge(Merges.layer(${parts.merges})));` : lines("const features = Layer.mergeAll(", ...each, below.length <= 100 ? below : `).pipe(\n Layer.provideMerge(Tokens.layer()),\n ${merges},\n);`), "");
98
+ };
99
+ /**
100
+ * The directive that lets the next line call an unstable Effect API, as the app's `src/git.ts`
101
+ * writes it. Joined as it runs, since its text whole in this file is a directive of this file's.
102
+ */
103
+ const unstableNextLine = ["// @effect", "diagnostics-next-line unstableApiUsage:off"].join("-");
104
+ /** The drop-in over Git's features, under `--serve github`: each of its features a line too. */
105
+ const githubFeatures = (choices) => lines("/**", " * GitHub's REST, GraphQL, webhooks and Event Streams over Git's, so `gh` and Octokit work, and", " * the drop-in's features, each a line: delete one to turn it off.", " */", "const github = Layer.mergeAll(", " Inbox.layer(),", " Deployments.layer(),", " // Without it, a repo's `language` and `license` answer null.", " Languages.layer(),", " // Repo and user search, and `org:` and `user:` search over an owner's public repos.", " Search.layer(),", " // A repo's and an org's hooks, each delivery a `fetch`, and GitHub Apps, whose hooks they send.", " Layer.provideMerge(Apps.layer(), Webhooks.layer()),", " // GitHub's Event Streams over Git's event feeds.", " Streams.layer(),", " // A repo's import from GitHub, its releases among it.", " Imports.layer(),", ").pipe(", choices.objects === "packs" && " // A release's assets, in the bucket beside the packs.\n Layer.provideMerge(Releases.layer()),", " Layer.provideMerge(GitHub.layer()),", " // The drop-in's own permissions narrow nothing past `policy`'s.", " Layer.provideMerge(GitHubPolicy.layer(GitHubPolicy.make(() => Effect.succeed(accept())))),", " // Who's who, by login, from Git's own records.", " Layer.provideMerge(", " People.layer(", " Effect.map(Effect.service(JoinedCalls), (joined) =>", " defaultPeople({ git: joined.effectHostCalls }),", " ),", " ),", " ),", " Layer.provideMerge(features),", " // A webhook's deliveries and an import's calls to GitHub, each the platform's `fetch`.", ` ${unstableNextLine}`, " Layer.provide(FetchHttpClient.layer),", ");", "");
106
+ /** Git's features, and the drop-in's over them under `--serve github`. */
107
+ const featuresLines = (choices, parts) => lines(gitFeatures(choices, parts), choices.serve === "github" && githubFeatures(choices));
108
+ /**
109
+ * `Git.layer`'s options: Git's URLs under the base path, when there's one, and the platform's
110
+ * `maxDuration`, when it sets one.
111
+ */
112
+ const gitOptions = (choices, maxDuration) => {
113
+ const options = [choices.basePath !== "/" && `basePath: '${choices.basePath.replace(/\/$/, "")}'`, maxDuration !== void 0 && `maxDuration: '${maxDuration} seconds'`].filter(Predicate.isString);
114
+ return options.length === 0 ? "{}" : `{ ${options.join(", ")} }`;
115
+ };
57
116
  /**
58
- * A framework's `serve` under `--serve github`, which its Git route calls: the drop-in's links
59
- * under the base path first, then REST and Git's protocol.
117
+ * The admin's sign-in, then `export const runtime`: the whole host, Git with its features over the
118
+ * adapter, one runtime that every entry, object and job runner takes.
60
119
  */
61
- const serveExport = (choices) => choices.serve === "github" && lines(`/** What \`${choices.basePath.replace(/\/$/, "")}\` serves: the drop-in's links first, then REST and Git's protocol. */`, "export const serve = {", " fetch: async (request: Request) => (await github.route(request)) ?? rest.fetch(request),", "};", "");
62
- export { adminLines, basePathLines, gitDependencies, gitImports, gitPackages, githubHandler, handlerLines, header, lfsLines, looseObjects, looseSays, mergeLines, queueLine, serveExport, serverLines, uploads };
120
+ const runtimeLines = (choices, parts) => lines("/** The admin's sign-in: `ADMIN_TOKEN`, as a Bearer token or as Basic's password. */", `const auth = Auth.bearer({ token: Redacted.make(${parts.token}), actor: admin });`, "", "/**", " * The whole host, one runtime that every request and job shares: Git and its features over the", " * adapter, deciding with `policy`, and the admin signing in with `auth`.", parts.jobs !== void 0 && ` * ${parts.jobs}`, " */", "export const runtime = ManagedRuntime.make(", parts.maxDuration !== void 0 && lines(" // The functions' `maxDuration`, from `vercel.json`: a clone that would outrun it ends first,", " // with Git's own message."), ` Git.layer(${gitOptions(choices, parts.maxDuration)}, ${choices.serve === "github" ? "github" : "features"}).pipe(`, " Layer.provide(Policy.layer(policy)),", " Layer.provide(Auth.layer(auth)),", choices.objects === "packs" ? " Layer.provide(Objects.layer())," : ` // Each object a row in its push's commit: no bucket, ${looseSays}.\n Layer.provide(Objects.layerRecords()),`, ` Layer.provideMerge(${parts.adapter}),`, " ),", ");", "");
121
+ export { adminLines, effectImports, featuresLines, gitDependencies, gitImports, gitPackages, header, lfsLines, looseSays, mergeLines, policyLines, queueLine, repoHint, runtimeLines, writtenCpu };
@@ -1,6 +1,6 @@
1
1
  // src/init/metadata.ts
2
2
  /** The version `ref0-git`, `create-ref0-git` and Git's packages release at, all at once (Q738). */
3
- const release = "0.7.0";
3
+ const release = "0.8.0";
4
4
  /** The packages the app depends on, by their folder in a checkout's `packages/`. */
5
5
  const appPackages = [
6
6
  "infra",
@@ -51,4 +51,9 @@ const peerPackages = { effect: "4.1.7" };
51
51
  * which differs from the root's.
52
52
  */
53
53
  const frameworkPackages = { "@sveltejs/adapter-node": "6.0.5" };
54
- export { appPackages, catalog, frameworkPackages, nodeAppPackages, nodePackages, peerPackages, release, storePackages, vercelPackages };
54
+ /**
55
+ * The CPU a Worker's request may use, in ms: the app's and the example's `limits.cpu_ms`, which
56
+ * their `Lfs.layer` takes too.
57
+ */
58
+ const workerCpuMs = 3e5;
59
+ export { appPackages, catalog, frameworkPackages, nodeAppPackages, nodePackages, peerPackages, release, storePackages, vercelPackages, workerCpuMs };
@@ -1,23 +1,16 @@
1
- import { matcherCall, matcherImport, servedBy } from "./routes.mjs";
1
+ import { matcherCall, matcherImport } from "./routes.mjs";
2
2
  // src/init/mounts.ts
3
- /**
4
- * The server module's exports a mount imports: Git, whose runtime runs the jobs, and what serves
5
- * Git's URLs, as `served` in Hono's, whose app imports `serve` from `@hono/node-server`.
6
- */
7
- const importsOf = (choices, asServed) => servedBy(choices) === "git" ? "git" : `git, ${servedBy(choices)}${asServed ? " as served" : ""}`;
8
- /** What Hono's lines mount: Git itself, or what serves its URLs, imported `as served`. */
9
- const honoServed = (choices) => servedBy(choices) === "git" ? "git" : "served";
10
3
  /** Express's middleware, before any body parser, as printed source: the matcher's paths to Git. */
11
- const expressLine = (choices) => `app.use(toNodeMiddleware(${servedBy(choices)}, (url) => ${matcherCall(choices)}))`;
4
+ const expressLine = (choices) => `app.use(toNodeMiddleware(runtime, (url) => ${matcherCall(choices)}))`;
12
5
  /**
13
6
  * The imports a mount's lines start with: `@ref0/git/node`'s `names`, Node's job runner, the
14
- * matcher, and the module, what serves `as served` where `asServed`.
7
+ * matcher, and the module's runtime, which serves Git's URLs and runs its jobs.
15
8
  */
16
- const imports = (choices, names, asServed = false) => [
9
+ const imports = (choices, names) => [
17
10
  `import { ${names} } from '@ref0/git/node';`,
18
11
  matcherImport(choices),
19
12
  "import * as Node from '@ref0/infra/node';",
20
- `import { ${importsOf(choices, asServed)} } from './git.ts';`,
13
+ "import { runtime } from './git.ts';",
21
14
  ""
22
15
  ];
23
16
  /** What Hono's lines take from Node and `@hono/node-server`: a server, and the app as a listener. */
@@ -27,23 +20,22 @@ const honoImports = ["import { createServer } from 'node:http';", "import { getR
27
20
  * the listener runs once, then raises it again for Node, or the person's own listener, to exit.
28
21
  */
29
22
  const startLines = [
30
- "const stop = Node.toJobRunner(git.runtime);",
23
+ "const stop = Node.toJobRunner(runtime);",
31
24
  "",
32
25
  "process.once('SIGTERM', () => void stop().finally(() => process.kill(process.pid, 'SIGTERM')));"
33
26
  ];
34
27
  /** Each server's lines, after its imports. */
35
28
  const mountLines = (server, choices) => {
36
- const serve = servedBy(choices);
37
29
  if (server === "hono") return [
38
30
  ...startLines,
39
31
  "",
40
- `const mount = toNodeMiddleware(${honoServed(choices)}, (url) => ${matcherCall(choices)});`,
32
+ `const mount = toNodeMiddleware(runtime, (url) => ${matcherCall(choices)});`,
41
33
  "",
42
34
  "const listener = getRequestListener(app.fetch);",
43
35
  "",
44
36
  "// In place of serve(), after the app's routes: Git answers its URLs in front of the app, as",
45
37
  "// Express's middleware does, so Hono's middleware doesn't run on them; a guard for Git goes",
46
- "// in git.ts's authorize. Every other request goes on to the app. Over HTTP/2, node:http2's",
38
+ "// in git.ts's policy. Every other request goes on to the app. Over HTTP/2, node:http2's",
47
39
  "// createSecureServer takes it too.",
48
40
  "createServer((incoming, outgoing) =>",
49
41
  " mount(incoming, outgoing, () => void listener(incoming, outgoing)),",
@@ -56,13 +48,13 @@ const mountLines = (server, choices) => {
56
48
  `${expressLine(choices)};`
57
49
  ];
58
50
  return [
59
- "const stop = Node.toJobRunner(git.runtime);",
51
+ "const stop = Node.toJobRunner(runtime);",
60
52
  "",
61
53
  "app.addHook('onClose', () => stop());",
62
54
  "",
63
55
  "// Git's URLs, answered before Fastify parses a body, so the body streams to Git and your routes",
64
56
  "// keep their parsers and bodyLimit. The middleware calls its next before it returns, or never.",
65
- `const mount = toNodeMiddleware(${serve}, (url) => ${matcherCall(choices)});`,
57
+ `const mount = toNodeMiddleware(runtime, (url) => ${matcherCall(choices)});`,
66
58
  "",
67
59
  "app.addHook('onRequest', (request, reply, done) => {",
68
60
  " let passed = false;",
@@ -92,7 +84,7 @@ const mountManual = (choices, framework) => {
92
84
  says: says[framework],
93
85
  lines: [
94
86
  ...framework === "hono" ? honoImports : [],
95
- ...imports(choices, "toNodeMiddleware", framework === "hono"),
87
+ ...imports(choices, "toNodeMiddleware"),
96
88
  ...mountLines(framework, choices)
97
89
  ]
98
90
  };
@@ -104,7 +96,7 @@ const mountManual = (choices, framework) => {
104
96
  ...imports(choices, "toNodeHandler, toNodeMiddleware"),
105
97
  ...startLines,
106
98
  "",
107
- `// node:http: createServer(toNodeHandler(${servedBy(choices)})).`,
99
+ "// node:http: createServer(toNodeHandler(runtime)).",
108
100
  `// Express, before express.json(): ${expressLine(choices)}.`
109
101
  ]
110
102
  };
@@ -43,7 +43,7 @@ const routeFile = (route, app, module, maxDuration) => {
43
43
  return {
44
44
  path,
45
45
  kind: "whole",
46
- text: lines(`// ${route.says} Written by \`ref0-git init\`.`, ...loaded, handlerLine(`(await import('${importOf(path, module)}')).${route.calls}.fetch(request);`), "", maxDuration !== void 0 && `export const maxDuration = ${maxDuration};\n`, `export { ${route.methods.map((method) => `git as ${method}`).join(", ")} };`, "")
46
+ text: lines(`// ${route.says} Written by \`ref0-git init\`.`, "import { Git } from '@ref0/git';", "", ...loaded, handlerLine(`Git.toFetch((await import('${importOf(path, module)}')).runtime)(request);`), "", maxDuration !== void 0 && `export const maxDuration = ${maxDuration};\n`, `export { ${route.methods.map((method) => `git as ${method}`).join(", ")} };`, "")
47
47
  };
48
48
  };
49
49
  /** A job route on Vercel: `jobs`, the queue's handler, for the queue's message or the cron's call. */