@open-workspace/create 0.5.1 → 0.6.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,21 +1,40 @@
1
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
1
+ import {
2
+ closeSync,
3
+ existsSync,
4
+ openSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ readSync,
8
+ statSync,
9
+ } from "node:fs";
2
10
  import { dirname, join, relative, sep } from "node:path";
3
11
 
4
12
  import { z } from "zod";
5
13
 
6
- /** A line's object and the line: 25 MiB of mail and room for the line. */
7
- const MAX_OBJECT_BYTES = 25 * 1024 * 1024;
14
+ /**
15
+ * The largest object a restore request carries: Cloudflare's limit on a
16
+ * request body on the Enterprise plan. A workspace on a plan that takes less
17
+ * (100 MB on Free and Pro, 200 MB on Business) refuses a larger request, and
18
+ * the line is reported as failed.
19
+ */
20
+ const MAX_OBJECT_BYTES = 500 * 1000 * 1000;
8
21
 
9
22
  const objectName = /^([0-9a-f]{64})\.[a-z0-9]+$/u;
10
23
 
11
24
  type LinePlace = { sourceId: string; module: string; folder: string };
12
25
 
26
+ /** A request body read from disk as it is sent, so an object needn't fit in memory. */
27
+ export type RestoreBody = {
28
+ size: number;
29
+ stream: () => ReadableStream<Uint8Array>;
30
+ };
31
+
13
32
  /** One line of a module's part, ready to send. */
14
33
  export type BackupLine = LinePlace & {
15
34
  ordered: boolean;
16
35
  parts: string[];
17
36
  bytes: number;
18
- body: Uint8Array<ArrayBuffer>;
37
+ body: RestoreBody;
19
38
  };
20
39
 
21
40
  /** A line, or why it can't be sent. */
@@ -107,43 +126,79 @@ function locateObject(dir: string, name: string) {
107
126
  return { path, hash, size };
108
127
  }
109
128
 
110
- /** The preflight and the upload check the same bytes against the object name. */
111
- function checkedBytes(path: string, hash: string) {
112
- const bytes = readFileSync(path);
129
+ /** The file's SHA-256, read a MiB at a time. */
130
+ function fileSha256(path: string) {
131
+ const hasher = new Bun.CryptoHasher("sha256");
132
+ const buffer = new Uint8Array(1024 * 1024);
133
+ const fd = openSync(path, "r");
134
+
135
+ try {
136
+ for (let read; (read = readSync(fd, buffer)) > 0;) {
137
+ hasher.update(buffer.subarray(0, read));
138
+ }
139
+ } finally {
140
+ closeSync(fd);
141
+ }
113
142
 
114
- return sha256(bytes) === hash ? { bytes } : { problem: "damaged" };
143
+ return hasher.digest("hex");
115
144
  }
116
145
 
117
- export function readBackupObject(dir: string, name: string) {
146
+ /**
147
+ * An object's file under `dir`, its bytes checked against its name, or why
148
+ * it can't be sent. The workspace checks them again as they arrive.
149
+ */
150
+ function backupObject(dir: string, name: string) {
118
151
  const object = locateObject(dir, name);
119
152
 
120
- if (object.problem !== undefined) {
121
- return { problem: object.problem, bytes: undefined };
153
+ if (object.problem !== undefined) return object;
154
+
155
+ if (fileSha256(object.path) !== object.hash) {
156
+ return { problem: "damaged" };
122
157
  }
123
158
 
124
- return checkedBytes(object.path, object.hash);
159
+ return object;
125
160
  }
126
161
 
127
- export function restoreBody(text: string, object?: Uint8Array) {
162
+ /** A line, a newline and its object's file, as the restore route reads them. */
163
+ export function restoreBody(text: string, object?: string) {
128
164
  const line = new TextEncoder().encode(object ? `${text}\n` : text);
129
165
 
130
- if (!object) return line;
131
- const body = new Uint8Array(line.length + object.length);
132
- body.set(line);
133
- body.set(object, line.length);
166
+ if (!object) {
167
+ return {
168
+ size: line.byteLength,
169
+ stream: () => new Blob([line]).stream(),
170
+ } satisfies RestoreBody;
171
+ }
134
172
 
135
- return body;
173
+ const file = Bun.file(object);
174
+
175
+ return {
176
+ size: line.byteLength + file.size,
177
+ stream: () => {
178
+ const reader = file.stream().getReader();
179
+
180
+ return new ReadableStream<Uint8Array>({
181
+ start: (controller) => controller.enqueue(line),
182
+ async pull(controller) {
183
+ const next = await reader.read();
184
+
185
+ if (next.done) controller.close();
186
+ else controller.enqueue(next.value);
187
+ },
188
+ cancel: (reason) => reader.cancel(reason),
189
+ });
190
+ },
191
+ } satisfies RestoreBody;
136
192
  }
137
193
 
138
194
  /**
139
- * Each module's lines in a snapshot, in order, each with its object read
140
- * from `../objects/` and checked against its hash.
195
+ * Each module's lines in a snapshot, in order, each with its object's file
196
+ * in `../objects/`, checked against its hash.
141
197
  * @yields {BackupItem} Each line, or why it is skipped.
142
198
  */
143
199
  export function* backupItems(
144
200
  snapshot: string,
145
- onInvalid?: ((message: string) => void) | null,
146
- verifyParts = true
201
+ onInvalid?: ((message: string) => void) | null
147
202
  ) {
148
203
  const objects = join(snapshot, "..", "objects");
149
204
 
@@ -172,13 +227,9 @@ export function* backupItems(
172
227
  let failedObject = refs.object;
173
228
 
174
229
  for (const part of refs.parts) {
175
- const partFile = locateObject(objects, part);
230
+ const partFile = backupObject(objects, part);
176
231
  problem = partFile.problem;
177
232
 
178
- if (partFile.path && verifyParts) {
179
- problem = checkedBytes(partFile.path, partFile.hash).problem;
180
- }
181
-
182
233
  if (!partFile.path || problem) {
183
234
  failedObject = part;
184
235
  break;
@@ -188,9 +239,7 @@ export function* backupItems(
188
239
  parts.push(partFile.path);
189
240
  }
190
241
 
191
- const object = refs.object
192
- ? readBackupObject(objects, refs.object)
193
- : undefined;
242
+ const object = refs.object ? backupObject(objects, refs.object) : undefined;
194
243
 
195
244
  problem ??= object?.problem;
196
245
 
@@ -209,11 +258,9 @@ export function* backupItems(
209
258
  bytes:
210
259
  partBytes +
211
260
  Buffer.byteLength(text) +
212
- (object?.bytes ? 1 + object.bytes.byteLength : 0),
261
+ (object?.path ? 1 + object.size : 0),
213
262
  ordered: module !== "email" || refs.kind !== undefined,
214
- get body() {
215
- return restoreBody(text, object?.bytes);
216
- },
263
+ body: restoreBody(text, object?.path),
217
264
  };
218
265
  }
219
266
  }
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { basename, dirname, join } from "node:path";
2
+ import { basename, join } from "node:path";
3
3
 
4
4
  import { z } from "zod";
5
5
 
@@ -9,7 +9,6 @@ import { parseCliArgs } from "./args.ts";
9
9
  import {
10
10
  backupItems,
11
11
  inspectSnapshot,
12
- readBackupObject,
13
12
  restoreBody,
14
13
  sha256,
15
14
  } from "./backup-snapshot.ts";
@@ -75,17 +74,12 @@ async function restoreLine(workspace: Workspace, line: BackupLine) {
75
74
  const path = `/api/admin/backups/restore/${encodeURIComponent(line.module)}?folder=${encodeURIComponent(line.folder)}`;
76
75
 
77
76
  for (const part of line.parts) {
78
- const name = basename(part);
79
- const data = readBackupObject(dirname(part), name);
80
-
81
- if (!data.bytes) return { skipped: data.problem ?? "damaged" };
82
-
83
- // oxlint-disable-next-line eslint/no-await-in-loop -- one file part in memory per concurrent restore
77
+ // oxlint-disable-next-line eslint/no-await-in-loop -- a line's parts go before it, in order
84
78
  const answer = await workspace.json(path, restoreAnswer, {
85
79
  method: "POST",
86
80
  raw: restoreBody(
87
- JSON.stringify({ kind: "backup-part", object: name }),
88
- data.bytes
81
+ JSON.stringify({ kind: "backup-part", object: basename(part) }),
82
+ part
89
83
  ),
90
84
  });
91
85
 
@@ -246,8 +240,8 @@ export async function backupCommand(args: string[], deps: CliDeps) {
246
240
  state,
247
241
  run: (onProgress) =>
248
242
  runResumable<BackupLine>({
249
- // Each part is checked again on the bytes actually sent by restoreLine.
250
- items: backupItems(snapshot, values.partial ? null : undefined, false),
243
+ // A damaged object is skipped here; the workspace checks what arrives too.
244
+ items: backupItems(snapshot, values.partial ? null : undefined),
251
245
  state,
252
246
  concurrency: concurrency(values),
253
247
  exclusive: (line) => !("skipped" in line) && line.ordered,
@@ -52,13 +52,11 @@ export function invitationFile(path: string, origin: string) {
52
52
  process.kill(pending.pid, 0);
53
53
  throw new Error(`Another import is writing ${path}.`);
54
54
  } catch (error) {
55
- if (
56
- !(
57
- error instanceof Error &&
58
- "code" in error &&
59
- error.code === "ESRCH"
60
- )
61
- ) {
55
+ if (!(
56
+ error instanceof Error &&
57
+ "code" in error &&
58
+ error.code === "ESRCH"
59
+ )) {
62
60
  throw error;
63
61
  }
64
62
  }
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
 
3
+ import type { RestoreBody } from "./backup-snapshot.ts";
3
4
  import { SignInError } from "./oauth.ts";
4
5
  import type { Fetch, TokenSource } from "./oauth.ts";
5
6
  import { importTargetSchema } from "./protocol.ts";
@@ -85,13 +86,24 @@ export class Workspace {
85
86
  this.origin = new URL(workspace).origin;
86
87
  }
87
88
 
88
- /** A request with the token; a refused token is refreshed once. */
89
- async request(path: string, init: RequestInit = {}) {
89
+ /**
90
+ * A request with the token; a refused token is refreshed once. A body
91
+ * that is a stream comes from `openBody`, opened again for that retry.
92
+ */
93
+ async request(
94
+ path: string,
95
+ init: RequestInit = {},
96
+ openBody?: () => ReadableStream<Uint8Array>
97
+ ) {
90
98
  const send = (token: string) => {
91
99
  const headers = new Headers(init.headers);
92
100
  headers.set("authorization", `Bearer ${token}`);
93
101
 
94
- return this.fetchImpl(`${this.origin}${path}`, { ...init, headers });
102
+ return this.fetchImpl(`${this.origin}${path}`, {
103
+ ...init,
104
+ headers,
105
+ body: openBody ? openBody() : init.body,
106
+ });
95
107
  };
96
108
 
97
109
  const token = await this.auth.token();
@@ -118,12 +130,21 @@ export class Workspace {
118
130
  }
119
131
 
120
132
  private send(path: string, init: JsonRequest) {
121
- if (init.raw) {
122
- return this.request(path, {
123
- method: init.method ?? "POST",
124
- headers: { "content-type": "application/octet-stream" },
125
- body: init.raw,
126
- });
133
+ const { raw } = init;
134
+
135
+ if (raw) {
136
+ // Its length up front: the workspace reads an object's size from it.
137
+ return this.request(
138
+ path,
139
+ {
140
+ method: init.method ?? "POST",
141
+ headers: {
142
+ "content-type": "application/octet-stream",
143
+ "content-length": String(raw.size),
144
+ },
145
+ },
146
+ raw.stream
147
+ );
127
148
  }
128
149
 
129
150
  return this.request(path, {
@@ -219,8 +240,8 @@ export class Workspace {
219
240
  type JsonRequest = {
220
241
  method?: string;
221
242
  body?: unknown;
222
- /** Bytes sent as they are, instead of a JSON `body`. */
223
- raw?: Uint8Array<ArrayBuffer>;
243
+ /** Bytes sent as they are, read as they go, instead of a JSON `body`. */
244
+ raw?: RestoreBody;
224
245
  };
225
246
 
226
247
  const importResponseSchema = z.object({
package/index.ts CHANGED
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/env bun
2
2
  // `bun create @open-workspace` writes a new project; `… module <name>` adds a
3
- // module to one; `… import` brings people and mail into a deployed workspace.
3
+ // module to one; `… import` brings people and mail into a deployed workspace;
4
+ // `… update` moves one to the latest release and deploys it.
4
5
  if (process.argv[2] === "module") {
5
6
  const { main } = await import("./module.ts");
6
7
  process.exitCode = main(process.argv.slice(3));
7
8
  } else if (process.argv[2] === "import") {
8
9
  const { main } = await import("./import/cli.ts");
9
10
  process.exitCode = await main(process.argv.slice(3));
11
+ } else if (process.argv[2] === "update") {
12
+ const { main } = await import("./update.ts");
13
+ process.exitCode = await main(process.argv.slice(3));
10
14
  } else if (process.argv[2] === "restore-mx") {
11
15
  const { main } = await import("./setup/mx-recovery.ts");
12
16
  process.exitCode = await main(process.argv.slice(3));
@@ -11,17 +11,17 @@ export const MODULE_NAME = /^[a-z]+(?:-[a-z]+)*$/u;
11
11
 
12
12
  /** What the generated module imports, at the versions core is built with. */
13
13
  export const moduleDependencies = {
14
- "@tanstack/react-query": "5.107.1",
14
+ "@tanstack/react-query": "5.108.4",
15
15
  "drizzle-orm": "0.45.4",
16
- hono: "4.13.17",
17
- "lucide-react": "1.71.0",
16
+ hono: "4.13.23",
17
+ "lucide-react": "1.84.0",
18
18
  react: "19.3.1",
19
- "react-router": "8.5.1",
19
+ "react-router": "8.5.3",
20
20
  zod: "4.6.7",
21
21
  } satisfies Record<string, string>;
22
22
 
23
23
  export const moduleDevDependencies = {
24
- "@types/react": "19.3.0",
24
+ "@types/react": "19.3.3",
25
25
  "drizzle-kit": "0.31.11",
26
26
  } satisfies Record<string, string>;
27
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-workspace/create",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Create an OpenWorkspace deployment (`bun create @open-workspace`), and import people, teams, SSO apps and mail.",
5
5
  "homepage": "https://openworkspace.dev",
6
6
  "license": "Apache-2.0",
@@ -17,6 +17,7 @@
17
17
  "create.ts",
18
18
  "templates.ts",
19
19
  "module.ts",
20
+ "update.ts",
20
21
  "setup",
21
22
  "module-templates.ts",
22
23
  "import",
@@ -42,14 +43,14 @@
42
43
  },
43
44
  "dependencies": {
44
45
  "@clack/prompts": "1.9.0",
45
- "imapflow": "2.11.0",
46
+ "imapflow": "2.12.2",
46
47
  "zod": "4.6.7"
47
48
  },
48
49
  "devDependencies": {
49
- "@alchemy.run/cloudflare": "2.0.0-beta.85",
50
- "@types/bun": "1.4.4",
51
- "alchemy": "2.0.0-beta.85",
52
- "effect": "4.1.3",
50
+ "@alchemy.run/cloudflare": "2.0.0-beta.87",
51
+ "@types/bun": "1.4.5",
52
+ "alchemy": "2.0.0-beta.87",
53
+ "effect": "4.1.7",
53
54
  "hoodiecrow-imap": "3.3.1",
54
55
  "typescript": "7.0.2"
55
56
  }
package/templates.ts CHANGED
@@ -14,11 +14,11 @@ export type ProjectAnswers = {
14
14
  };
15
15
 
16
16
  export const versions = {
17
- openWorkspace: "0.5.1",
18
- alchemy: "2.0.0-beta.85",
19
- effect: "4.1.3",
17
+ openWorkspace: "0.6.0",
18
+ alchemy: "2.0.0-beta.87",
19
+ effect: "4.1.7",
20
20
  typescript: "7.0.2",
21
- nodeTypes: "26.6.6",
21
+ nodeTypes: "26.6.11",
22
22
  bun: "1.4.4",
23
23
  };
24
24
 
@@ -31,6 +31,9 @@ export const versions = {
31
31
  */
32
32
  export const DEPLOY_STAGE = "production";
33
33
 
34
+ /** The project's `update` script: the latest release, installed and deployed. */
35
+ export const UPDATE_SCRIPT = "bunx @open-workspace/create@latest update";
36
+
34
37
  export function packageJson(answers: ProjectAnswers) {
35
38
  return `${JSON.stringify(
36
39
  {
@@ -44,6 +47,7 @@ export function packageJson(answers: ProjectAnswers) {
44
47
  dev: "alchemy dev",
45
48
  destroy: `alchemy destroy --stage ${DEPLOY_STAGE}`,
46
49
  logs: `alchemy logs --tail --stage ${DEPLOY_STAGE}`,
50
+ update: UPDATE_SCRIPT,
47
51
  },
48
52
  dependencies: {
49
53
  "@open-workspace/core": versions.openWorkspace,
@@ -255,10 +259,9 @@ passkey, as on the deployed app. Mail from outside doesn't reach it.
255
259
 
256
260
  ## Update
257
261
 
258
- \`\`\`sh
259
- bun update --latest @open-workspace/core @open-workspace/email
260
- bun run deploy
261
- \`\`\`
262
+ \`bun run update\` moves OpenWorkspace to the latest release, with the Alchemy
263
+ and Effect versions it needs, installs it and deploys. Read the release's
264
+ upgrade notes first; Administration shows them when an update is available.
262
265
  `;
263
266
  }
264
267
 
package/update.ts ADDED
@@ -0,0 +1,180 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+
4
+ import { z } from "zod";
5
+
6
+ import { UPDATE_SCRIPT } from "./templates";
7
+
8
+ /** What npm says of @open-workspace/core's latest release. */
9
+ const latestSchema = z.object({
10
+ version: z.string(),
11
+ peerDependencies: z.record(z.string(), z.string()).default({}),
12
+ });
13
+
14
+ export type LatestRelease = z.infer<typeof latestSchema>;
15
+
16
+ const manifestSchema = z.looseObject({
17
+ scripts: z.record(z.string(), z.string()).optional(),
18
+ dependencies: z.record(z.string(), z.string()).optional(),
19
+ devDependencies: z.record(z.string(), z.string()).optional(),
20
+ });
21
+
22
+ /** The packages released together under one version. */
23
+ const OWN_PACKAGES = new Set(["@open-workspace/core", "@open-workspace/email"]);
24
+
25
+ /** Versioned with effect, though core doesn't name them. */
26
+ const EFFECT_PLATFORMS = new Set([
27
+ "@effect/platform-bun",
28
+ "@effect/platform-node",
29
+ ]);
30
+
31
+ export type VersionChange = { name: string; from: string; to: string };
32
+
33
+ /**
34
+ * The project's package.json moved to `latest`: OpenWorkspace's packages to
35
+ * its version, and Alchemy and Effect to the versions core was built with
36
+ * (it pins them as peers), with the `update` script added if missing.
37
+ */
38
+ export function updatedManifest(text: string, latest: LatestRelease) {
39
+ const manifest = manifestSchema.parse(JSON.parse(text));
40
+ const changes: VersionChange[] = [];
41
+
42
+ const wanted = (name: string) => {
43
+ if (OWN_PACKAGES.has(name)) return latest.version;
44
+
45
+ if (EFFECT_PLATFORMS.has(name)) return latest.peerDependencies.effect;
46
+
47
+ return latest.peerDependencies[name];
48
+ };
49
+
50
+ for (const field of ["dependencies", "devDependencies"] as const) {
51
+ const deps = manifest[field];
52
+
53
+ if (!deps) continue;
54
+
55
+ for (const [name, from] of Object.entries(deps)) {
56
+ const to = wanted(name);
57
+
58
+ if (to && to !== from) {
59
+ deps[name] = to;
60
+ changes.push({ name, from, to });
61
+ }
62
+ }
63
+ }
64
+
65
+ const scripts = manifest.scripts ?? {};
66
+ const addsScript = !scripts.update;
67
+
68
+ if (addsScript) manifest.scripts = { ...scripts, update: UPDATE_SCRIPT };
69
+
70
+ return {
71
+ text: `${JSON.stringify(manifest, null, 2)}\n`,
72
+ changes,
73
+ addsScript,
74
+ };
75
+ }
76
+
77
+ export type UpdateDeps = {
78
+ latest: () => Promise<LatestRelease>;
79
+ /** Runs a command in the project on this terminal; whether it succeeded. */
80
+ run: (command: string[]) => Promise<boolean>;
81
+ log: (line: string) => void;
82
+ };
83
+
84
+ const usage = `Usage: bunx @open-workspace/create update [--no-deploy] (or bun run update), in your workspace's project
85
+
86
+ Moves @open-workspace/core and email to the latest release, with the Alchemy
87
+ and Effect versions it needs, installs them and deploys.`;
88
+
89
+ /**
90
+ * `bunx @open-workspace/create update`, run in a deployment project. Returns
91
+ * the exit code.
92
+ */
93
+ export async function main(
94
+ args: string[],
95
+ cwd = process.cwd(),
96
+ deps: UpdateDeps = defaultDeps(cwd)
97
+ ) {
98
+ const unknown = args.filter((arg) => arg !== "--no-deploy");
99
+
100
+ if (unknown.length) {
101
+ deps.log(usage);
102
+
103
+ return unknown.includes("--help") || unknown.includes("-h") ? 0 : 1;
104
+ }
105
+
106
+ const path = join(resolve(cwd), "package.json");
107
+ let text: string;
108
+
109
+ try {
110
+ text = readFileSync(path, "utf-8");
111
+ } catch {
112
+ deps.log(`No package.json here. ${usage}`);
113
+
114
+ return 1;
115
+ }
116
+
117
+ if (!text.includes('"@open-workspace/core"')) {
118
+ deps.log(`This project doesn't use @open-workspace/core. ${usage}`);
119
+
120
+ return 1;
121
+ }
122
+
123
+ const latest = await deps.latest();
124
+ const updated = updatedManifest(text, latest);
125
+
126
+ if (!updated.changes.length) {
127
+ if (updated.addsScript) writeFileSync(path, updated.text);
128
+ deps.log(`Already on OpenWorkspace ${latest.version}.`);
129
+
130
+ return 0;
131
+ }
132
+
133
+ for (const change of updated.changes) {
134
+ deps.log(`${change.name} ${change.from} → ${change.to}`);
135
+ }
136
+
137
+ deps.log(
138
+ `What changed: https://github.com/iivankin/openworkspace/releases/tag/v${latest.version}`
139
+ );
140
+ writeFileSync(path, updated.text);
141
+
142
+ if (!(await deps.run([process.execPath, "install"]))) return 1;
143
+
144
+ if (args.includes("--no-deploy")) {
145
+ deps.log("Updated. Deploy with: bun run deploy");
146
+
147
+ return 0;
148
+ }
149
+
150
+ return (await deps.run([process.execPath, "run", "deploy"])) ? 0 : 1;
151
+ }
152
+
153
+ function defaultDeps(cwd: string) {
154
+ const deps: UpdateDeps = {
155
+ async latest() {
156
+ const response = await fetch(
157
+ "https://registry.npmjs.org/@open-workspace/core/latest"
158
+ );
159
+
160
+ if (!response.ok) {
161
+ throw new Error(`npm answered ${response.status}`);
162
+ }
163
+
164
+ return latestSchema.parse(await response.json());
165
+ },
166
+ async run(command) {
167
+ const child = Bun.spawn(command, {
168
+ cwd,
169
+ stdin: "inherit",
170
+ stdout: "inherit",
171
+ stderr: "inherit",
172
+ });
173
+
174
+ return (await child.exited) === 0;
175
+ },
176
+ log: console.log,
177
+ };
178
+
179
+ return deps;
180
+ }