@open-workspace/create 0.3.0 → 0.4.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.
package/setup/ui.ts ADDED
@@ -0,0 +1,146 @@
1
+ // The terminal conversation, behind an interface so the flow can be driven
2
+ // by a script in tests. `clackUi` is the real one.
3
+ import * as p from "@clack/prompts";
4
+
5
+ export type Choice<T extends string> = {
6
+ value: T;
7
+ label: string;
8
+ hint?: string;
9
+ };
10
+
11
+ export type Ui = {
12
+ intro(title: string): void;
13
+ outro(message: string): void;
14
+ cancel(message: string): void;
15
+ text(prompt: {
16
+ message: string;
17
+ placeholder?: string;
18
+ initialValue?: string;
19
+ validate?: (value: string) => string | undefined;
20
+ }): Promise<string>;
21
+ password(prompt: { message: string }): Promise<string>;
22
+ confirm(prompt: {
23
+ message: string;
24
+ initialValue?: boolean;
25
+ }): Promise<boolean>;
26
+ select<T extends string>(prompt: {
27
+ message: string;
28
+ options: Choice<T>[];
29
+ initialValue?: T;
30
+ }): Promise<T>;
31
+ multiselect<T extends string>(prompt: {
32
+ message: string;
33
+ options: Choice<T>[];
34
+ initialValues?: T[];
35
+ }): Promise<T[]>;
36
+ info(message: string): void;
37
+ success(message: string): void;
38
+ warn(message: string): void;
39
+ error(message: string): void;
40
+ step(message: string): void;
41
+ note(message: string, title: string): void;
42
+ /** Shows `message` while `work` runs, then `done(result)`. */
43
+ progress<T>(
44
+ message: string,
45
+ work: () => Promise<T>,
46
+ done: (result: T) => string
47
+ ): Promise<T>;
48
+ };
49
+
50
+ /** A prompt the person cancelled (Ctrl-C or Esc). */
51
+ export class Cancelled extends Error {
52
+ constructor() {
53
+ super("Cancelled");
54
+ }
55
+ }
56
+
57
+ function answered<T>(value: T | symbol): T {
58
+ if (p.isCancel(value)) throw new Cancelled();
59
+
60
+ // SAFETY: clack resolves a prompt with its answer or its cancel symbol, ruled out above.
61
+ return value as T;
62
+ }
63
+
64
+ export const clackUi: Ui = {
65
+ intro: (title) => p.intro(title),
66
+ outro: (message) => p.outro(message),
67
+ cancel: (message) => p.cancel(message),
68
+ async text(prompt) {
69
+ const { validate } = prompt;
70
+
71
+ return answered<string>(
72
+ await p.text({
73
+ message: prompt.message,
74
+ placeholder: prompt.placeholder,
75
+ initialValue: prompt.initialValue,
76
+ validate: validate && ((value) => validate(value ?? "")),
77
+ })
78
+ );
79
+ },
80
+ async password(prompt) {
81
+ return answered<string>(await p.password({ message: prompt.message }));
82
+ },
83
+ async confirm(prompt) {
84
+ return answered<boolean>(await p.confirm(prompt));
85
+ },
86
+ async select(prompt) {
87
+ const value = answered<string>(
88
+ await p.select<string>({
89
+ message: prompt.message,
90
+ options: prompt.options,
91
+ initialValue: prompt.initialValue,
92
+ })
93
+ );
94
+
95
+ const chosen = prompt.options.find((option) => option.value === value);
96
+
97
+ if (!chosen) throw new Error(`Unknown choice: ${value}`);
98
+
99
+ return chosen.value;
100
+ },
101
+ async multiselect(prompt) {
102
+ const values = answered<string[]>(
103
+ await p.multiselect<string>({
104
+ message: prompt.message,
105
+ options: prompt.options,
106
+ initialValues: prompt.initialValues,
107
+ required: true,
108
+ })
109
+ );
110
+
111
+ return prompt.options
112
+ .filter((option) => values.includes(option.value))
113
+ .map((option) => option.value);
114
+ },
115
+ info: (message) => p.log.info(message),
116
+ success: (message) => p.log.success(message),
117
+ warn: (message) => p.log.warn(message),
118
+ error: (message) => p.log.error(message),
119
+ step: (message) => p.log.step(message),
120
+ note: (message, title) => p.note(message, title),
121
+ async progress(message, work, done) {
122
+ // A spinner's frames are noise in a log: without a terminal, only the outcome is printed.
123
+ if (!process.stdout.isTTY) {
124
+ const result = await work();
125
+
126
+ p.log.step(done(result));
127
+
128
+ return result;
129
+ }
130
+
131
+ const spinner = p.spinner();
132
+
133
+ spinner.start(message);
134
+
135
+ try {
136
+ const result = await work();
137
+
138
+ spinner.stop(done(result));
139
+
140
+ return result;
141
+ } catch (failure) {
142
+ spinner.error(message);
143
+ throw failure;
144
+ }
145
+ },
146
+ };
package/templates.ts CHANGED
@@ -1,120 +1,119 @@
1
1
  export type ProjectAnswers = {
2
- /** Directory and Worker script name, e.g. "acme-workspace". */
2
+ /** Directory and package name, e.g. "acme-workspace"; the Alchemy stack is named after it. */
3
3
  name: string;
4
4
  /** Hostname the app is served on, e.g. "mail.acme.com". */
5
- domain: string;
5
+ hostname: string;
6
6
  /** Mail domains, primary first. */
7
7
  mailDomains: string[];
8
- /** Whether alchemy wires up Email Routing and Email Sending for them. */
9
- configureMail: boolean;
10
8
  ai: "none" | "cloudflare" | "openai" | "anthropic";
9
+ /** Where it deploys: the Cloudflare account, and the Alchemy profile signed in to it (none with environment credentials). */
10
+ cloudflare?: {
11
+ account: { id: string; name: string };
12
+ profile: string | undefined;
13
+ };
11
14
  };
12
15
 
13
16
  export const versions = {
14
- openWorkspace: "0.3.0",
15
- alchemy: "2.0.0-beta.84",
16
- effect: "4.0.7",
17
+ openWorkspace: "0.4.0",
18
+ alchemy: "2.0.0-beta.85",
19
+ effect: "4.1.3",
17
20
  typescript: "7.0.2",
18
- workersTypes: "4.20261031.0",
21
+ nodeTypes: "26.6.6",
22
+ bun: "1.4.4",
19
23
  };
20
24
 
21
25
  function stackName(name: string) {
22
- return name
23
- .split(/[^a-zA-Z0-9]+/u)
24
- .filter(Boolean)
25
- .map((part) => part[0]!.toUpperCase() + part.slice(1))
26
- .join("") || "Workspace";
26
+ return (
27
+ name
28
+ .split(/[^a-zA-Z0-9]+/u)
29
+ .filter(Boolean)
30
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
31
+ .join("") || "Workspace"
32
+ );
27
33
  }
28
34
 
29
35
  export function packageJson(answers: ProjectAnswers) {
30
- return `${JSON.stringify({
31
- name: answers.name,
32
- private: true,
33
- type: "module",
34
- scripts: {
35
- deploy: "alchemy deploy",
36
- dev: "alchemy dev",
37
- destroy: "alchemy destroy",
38
- logs: "alchemy logs --tail",
36
+ return `${JSON.stringify(
37
+ {
38
+ name: answers.name,
39
+ private: true,
40
+ type: "module",
41
+ packageManager: `bun@${versions.bun}`,
42
+ scripts: {
43
+ deploy: "alchemy deploy",
44
+ dev: "alchemy dev",
45
+ destroy: "alchemy destroy",
46
+ logs: "alchemy logs --tail",
47
+ },
48
+ dependencies: {
49
+ "@open-workspace/core": versions.openWorkspace,
50
+ "@open-workspace/email": versions.openWorkspace,
51
+ },
52
+ devDependencies: {
53
+ "@alchemy.run/cloudflare": versions.alchemy,
54
+ "@effect/platform-bun": versions.effect,
55
+ "@effect/platform-node": versions.effect,
56
+ "@types/node": versions.nodeTypes,
57
+ alchemy: versions.alchemy,
58
+ effect: versions.effect,
59
+ typescript: versions.typescript,
60
+ },
39
61
  },
40
- dependencies: {
41
- "@open-workspace/core": versions.openWorkspace,
42
- "@open-workspace/email": versions.openWorkspace,
43
- },
44
- devDependencies: {
45
- "@alchemy.run/cloudflare": versions.alchemy,
46
- "@effect/platform-bun": versions.effect,
47
- "@effect/platform-node": versions.effect,
48
- alchemy: versions.alchemy,
49
- effect: versions.effect,
50
- typescript: versions.typescript,
51
- },
52
- // Alchemy's beta pins Effect 4.0; newer minors rename modules it imports.
53
- overrides: {
54
- effect: versions.effect,
55
- "@effect/platform-bun": versions.effect,
56
- "@effect/platform-node": versions.effect,
57
- "@effect/platform-node-shared": versions.effect,
58
- },
59
- }, null, 2)}\n`;
62
+ null,
63
+ 2
64
+ )}\n`;
60
65
  }
61
66
 
62
67
  function aiOption(ai: ProjectAnswers["ai"]) {
63
68
  switch (ai) {
64
- case "none":
69
+ case "none": {
65
70
  return "";
66
- case "cloudflare":
67
- return `
68
- // AI runs through AI Gateway, billed to your Cloudflare account's credits.
69
- ai: {
70
- providers: { cloudflare: { type: "cloudflare" } },
71
- features: {
72
- classification: { enabled: true, provider: "cloudflare", model: "openai/gpt-6-luna", reasoning: "medium" },
73
- translation: { enabled: true, provider: "cloudflare", model: "openai/gpt-6-luna", reasoning: "none" },
74
- },
75
- },`;
76
- case "openai":
77
- return `
78
- // The key is the OPENAI_API_KEY secret, read from .env when you deploy.
79
- ai: {
80
- providers: { openai: { type: "openai", apiKeyEnv: "OPENAI_API_KEY" } },
81
- features: {
82
- classification: { enabled: true, provider: "openai", model: "gpt-5-mini", reasoning: "low" },
83
- translation: { enabled: true, provider: "openai", model: "gpt-5-mini", reasoning: "none" },
84
- },
85
- },`;
86
- case "anthropic":
71
+ }
72
+
73
+ case "cloudflare": {
87
74
  return `
88
- // The key is the ANTHROPIC_API_KEY secret, read from .env when you deploy.
89
- ai: {
90
- providers: { anthropic: { type: "anthropic", apiKeyEnv: "ANTHROPIC_API_KEY" } },
91
- features: {
92
- classification: { enabled: true, provider: "anthropic", model: "claude-haiku-5-5" },
93
- translation: { enabled: true, provider: "anthropic", model: "claude-haiku-5-5" },
94
- },
95
- },`;
96
- }
97
- }
75
+ // AI runs through AI Gateway, billed to your Cloudflare account's credits.
76
+ ai: {
77
+ providers: { cloudflare: { type: "cloudflare" } },
78
+ features: {
79
+ classification: { enabled: true, provider: "cloudflare", model: "openai/gpt-6-luna", reasoning: "medium" },
80
+ translation: { enabled: true, provider: "cloudflare", model: "openai/gpt-6-luna", reasoning: "none" },
81
+ },
82
+ },`;
83
+ }
98
84
 
99
- export function workerTs(answers: ProjectAnswers) {
100
- return `import { createWorkspace } from "@open-workspace/core";
101
- import { email } from "@open-workspace/email";
85
+ case "openai": {
86
+ return `
87
+ // The key is the OPENAI_API_KEY secret, read from .env when you deploy (required).
88
+ ai: {
89
+ providers: { openai: { type: "openai", apiKeyEnv: "OPENAI_API_KEY" } },
90
+ features: {
91
+ classification: { enabled: true, provider: "openai", model: "gpt-5-mini", reasoning: "low" },
92
+ translation: { enabled: true, provider: "openai", model: "gpt-5-mini", reasoning: "none" },
93
+ },
94
+ },`;
95
+ }
102
96
 
103
- // Durable Object classes must be exported from the Worker entry.
104
- export { MailboxDO, OfficePreviewContainer } from "@open-workspace/email";
97
+ case "anthropic": {
98
+ return `
99
+ // The key is the ANTHROPIC_API_KEY secret, read from .env when you deploy (required).
100
+ ai: {
101
+ providers: { anthropic: { type: "anthropic", apiKeyEnv: "ANTHROPIC_API_KEY" } },
102
+ features: {
103
+ classification: { enabled: true, provider: "anthropic", model: "claude-haiku-5-5" },
104
+ translation: { enabled: true, provider: "anthropic", model: "claude-haiku-5-5" },
105
+ },
106
+ },`;
107
+ }
105
108
 
106
- export default createWorkspace({
107
- // Mail domains, primary first. The first administrator signs up on one.
108
- domains: ${JSON.stringify(answers.mailDomains)},${aiOption(answers.ai)}
109
- modules: [email()],
110
- });
111
- `;
109
+ default: {
110
+ const unexpected: never = ai;
111
+ throw new Error(`Unknown AI choice: ${String(unexpected)}`);
112
+ }
113
+ }
112
114
  }
113
115
 
114
116
  export function alchemyRunTs(answers: ProjectAnswers) {
115
- const mail = answers.configureMail
116
- ? `Email({ domains: ${JSON.stringify(answers.mailDomains)} })`
117
- : "Email()";
118
117
  return `import * as Cloudflare from "@alchemy.run/cloudflare";
119
118
  import * as Alchemy from "alchemy";
120
119
  import { OpenWorkspace, providers } from "@open-workspace/core/alchemy";
@@ -124,69 +123,118 @@ export default Alchemy.Stack(
124
123
  ${JSON.stringify(stackName(answers.name))},
125
124
  { providers: providers(), state: Cloudflare.state() },
126
125
  OpenWorkspace({
127
- name: ${JSON.stringify(answers.name)},
128
- main: "./src/worker.ts",
129
- domain: ${JSON.stringify(answers.domain)},
130
- modules: [${mail}],
126
+ // Required. Where the app is served: a hostname in a zone of this account.
127
+ // https://<hostname> is the OIDC issuer, the SAML IdP, and where passkeys work.
128
+ hostname: ${JSON.stringify(answers.hostname)},
129
+ // Mail domains, primary first. Every address is on one of them.
130
+ // Email() turns on Email Routing and Email Sending for each.
131
+ mailDomains: ${JSON.stringify(answers.mailDomains)},${aiOption(answers.ai)}
132
+ modules: [Email()],
133
+ // \`bun run dev\` serves the workspace at http://localhost:5173, where
134
+ // passkeys work too; the hostname above is only for the deploy.
135
+ dev: { port: 5173 },
136
+ // Single sign-on apps can be declared here instead of in the admin UI,
137
+ // SCIM provisioning included (the token is a secret from .env, never a
138
+ // plain string). Wrap this call in Effect.gen to create them first:
139
+ // const grafana = yield* OidcClient("Grafana", {
140
+ // name: "Grafana",
141
+ // redirectUris: ["https://grafana.example.com/login/generic_oauth"],
142
+ // access: "everyone",
143
+ // provisioning: {
144
+ // baseUrl: "https://grafana.example.com/api/scim/v2",
145
+ // token: yield* Config.Redacted("GRAFANA_SCIM_TOKEN"),
146
+ // },
147
+ // });
148
+ // and pass apps: [grafana]. OpenWorkspace returns the workspace's OIDC and
149
+ // SAML endpoints for wiring up the other side, e.g. a Cloudflare Access
150
+ // login method (see @open-workspace/core's README).
131
151
  }),
132
152
  );
133
153
  `;
134
154
  }
135
155
 
136
- export const tsconfigJson = `${JSON.stringify({
137
- compilerOptions: {
138
- target: "ES2023",
139
- lib: ["ES2023"],
140
- module: "ESNext",
141
- moduleResolution: "Bundler",
142
- strict: true,
143
- skipLibCheck: true,
144
- noEmit: true,
145
- allowImportingTsExtensions: true,
146
- types: [],
156
+ export const tsconfigJson = `${JSON.stringify(
157
+ {
158
+ compilerOptions: {
159
+ target: "ES2023",
160
+ lib: ["ES2023"],
161
+ module: "ESNext",
162
+ moduleResolution: "Bundler",
163
+ strict: true,
164
+ skipLibCheck: true,
165
+ noEmit: true,
166
+ allowImportingTsExtensions: true,
167
+ types: ["node"],
168
+ },
169
+ include: ["alchemy.run.ts"],
147
170
  },
148
- include: [
149
- "src",
150
- "node_modules/@open-workspace/core/types",
151
- "node_modules/@open-workspace/core/worker/bindings.d.ts",
152
- "node_modules/@open-workspace/email/worker/bindings.d.ts",
153
- ],
154
- }, null, 2)}\n`;
171
+ null,
172
+ 2
173
+ )}\n`;
155
174
 
156
175
  export const gitignore = `node_modules
157
176
  .alchemy
158
177
  .env
159
178
  `;
160
179
 
180
+ function deployTarget(answers: ProjectAnswers) {
181
+ const { cloudflare } = answers;
182
+
183
+ if (!cloudflare) {
184
+ return `
185
+ Sign in to Cloudflare once first: \`bun alchemy profile edit --add Cloudflare\`.
186
+ `;
187
+ }
188
+
189
+ const account = `${cloudflare.account.name} (\`${cloudflare.account.id}\`)`;
190
+
191
+ return cloudflare.profile
192
+ ? `
193
+ It deploys to the Cloudflare account ${account}, signed in as Alchemy
194
+ profile \`${cloudflare.profile}\`${cloudflare.profile === "default" ? "" : " (`ALCHEMY_PROFILE` in `.env`)"}.
195
+ If that login expires, run \`bun alchemy profile refresh${cloudflare.profile === "default" ? "" : ` --profile ${cloudflare.profile}`}\`.
196
+ `
197
+ : `
198
+ It deploys to the Cloudflare account ${account}, with the CLOUDFLARE_API_TOKEN and
199
+ CLOUDFLARE_ACCOUNT_ID environment variables.
200
+ `;
201
+ }
202
+
161
203
  export function readme(answers: ProjectAnswers) {
162
204
  return `# ${answers.name}
163
205
 
164
206
  An [OpenWorkspace](https://openworkspace.dev) deployment on your Cloudflare account.
165
207
 
166
- - \`src/worker.ts\` — the workspace: mail domains, AI, and modules.
167
- - \`alchemy.run.ts\` — the Cloudflare resources, managed by [Alchemy](https://alchemy.run).
208
+ - \`alchemy.run.ts\` — the workspace (mail domains, AI, and modules) and its Cloudflare
209
+ resources, managed by [Alchemy](https://alchemy.run). The Worker's code comes from the
210
+ packages; Alchemy writes its entry from this file on every deploy.
168
211
  - \`.env\` — API keys for outside services, uploaded as Worker secrets on deploy. Keep it out of git. The OIDC and SAML signing keys and the push keys are minted by Alchemy on the first deploy and kept in its state.
169
212
 
170
213
  ## Deploy
171
214
 
172
215
  \`\`\`sh
173
- bun alchemy profile edit --add Cloudflare # once: sign in to Cloudflare
174
216
  bun run deploy
175
217
  \`\`\`
176
-
177
- Open https://${answers.domain} and create the first administrator with a passkey,
218
+ ${deployTarget(answers)}
219
+ Open https://${answers.hostname} and create the first administrator with a passkey,
178
220
  using an address on ${answers.mailDomains[0]}.
179
- ${answers.configureMail ? `
221
+
180
222
  Alchemy turns on Email Routing for ${answers.mailDomains.join(", ")}, sends every
181
- address to the Worker, onboards the domains to Email Sending, and subscribes
182
- the delivery events queue.` : `
183
- In the Cloudflare dashboard, for each mail domain: enable Email Routing, send the
184
- catch-all to this Worker, onboard the domain to Email Sending, and subscribe the
185
- \`${answers.name}-delivery-events\` queue to its Email Sending events.`}
223
+ address to the Worker, onboards the mail domains to Email Sending, and subscribes
224
+ the delivery events queue. Email Routing adds the zones' MX and SPF records and
225
+ locks them; remove another mail provider's MX records from a zone first, or the
226
+ deploy fails.
227
+
228
+ Profile photos and the workspace logo need no setup: they are kept in an R2
229
+ bucket the deploy creates and resized by the Worker's Images binding, without
230
+ Cloudflare Images storage or an Images subscription. The first 5,000 unique
231
+ transformations a month are free; each photo or logo size counts once a month.
186
232
 
187
233
  ## Develop
188
234
 
189
- \`bun run dev\` runs the workspace locally with \`alchemy dev\`.
235
+ \`bun run dev\` runs the workspace at http://localhost:5173 on Cloudflare's local
236
+ runtime, with its own local data: create a first administrator there with a
237
+ passkey, as on the deployed app. Mail from outside doesn't reach it.
190
238
 
191
239
  ## Update
192
240
 
@@ -197,15 +245,33 @@ bun run deploy
197
245
  `;
198
246
  }
199
247
 
200
- export function envFile(input: { aiKey?: { name: string; value: string } }) {
248
+ export function envFile(input: {
249
+ aiKey?: { name: string; value: string };
250
+ /** The Alchemy profile signed in to the chosen Cloudflare account, when it isn't "default". */
251
+ alchemyProfile?: string;
252
+ }) {
201
253
  return [
202
254
  "# Secrets for outside services, uploaded as Worker secrets by `alchemy deploy`.",
203
255
  "# Never commit this file. Signing keys need no entry: Alchemy mints them.",
204
- ...(input.aiKey ? ["", `${input.aiKey.name}=${input.aiKey.value}`] : []),
256
+ ...(input.alchemyProfile
257
+ ? [
258
+ "",
259
+ "# The Alchemy profile signed in to this deployment's Cloudflare account.",
260
+ `ALCHEMY_PROFILE=${input.alchemyProfile}`,
261
+ ]
262
+ : []),
263
+ ...(input.aiKey
264
+ ? [
265
+ "",
266
+ input.aiKey.value
267
+ ? `${input.aiKey.name}=${input.aiKey.value}`
268
+ : `# Required to deploy: the AI provider in alchemy.run.ts reads it.\n${input.aiKey.name}=`,
269
+ ]
270
+ : []),
205
271
  "",
206
272
  "# Optional:",
207
273
  "# SPAMHAUS_DQS_KEY=",
208
- "# R2_ACCESS_KEY_ID= / R2_SECRET_ACCESS_KEY= (an R2 API token for the mail bucket) for direct attachment transfers",
274
+ "# SCIM tokens of single sign-on apps declared in alchemy.run.ts, e.g. GRAFANA_SCIM_TOKEN=",
209
275
  "",
210
276
  ].join("\n");
211
277
  }