@open-workspace/create 0.3.0 → 0.4.1

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,192 +1,249 @@
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.1",
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()";
117
+ // The options sit one level deeper here, inside Effect.gen.
118
+ const ai = aiOption(answers.ai).replaceAll("\n", "\n ");
119
+
118
120
  return `import * as Cloudflare from "@alchemy.run/cloudflare";
119
121
  import * as Alchemy from "alchemy";
122
+ import * as Effect from "effect/Effect";
120
123
  import { OpenWorkspace, providers } from "@open-workspace/core/alchemy";
121
124
  import { Email } from "@open-workspace/email/alchemy";
122
125
 
123
126
  export default Alchemy.Stack(
124
127
  ${JSON.stringify(stackName(answers.name))},
125
128
  { providers: providers(), state: Cloudflare.state() },
126
- OpenWorkspace({
127
- name: ${JSON.stringify(answers.name)},
128
- main: "./src/worker.ts",
129
- domain: ${JSON.stringify(answers.domain)},
130
- modules: [${mail}],
129
+ Effect.gen(function* () {
130
+ // Single sign-on apps can be declared here instead of in the admin UI,
131
+ // SCIM provisioning included (the token is a secret from .env, never a
132
+ // plain string), and passed to OpenWorkspace as apps: [grafana]:
133
+ // const grafana = yield* OidcClient("Grafana", {
134
+ // name: "Grafana",
135
+ // redirectUris: ["https://grafana.example.com/login/generic_oauth"],
136
+ // access: "everyone",
137
+ // provisioning: {
138
+ // baseUrl: "https://grafana.example.com/api/scim/v2",
139
+ // token: yield* Config.Redacted("GRAFANA_SCIM_TOKEN"),
140
+ // },
141
+ // });
142
+
143
+ const workspace = yield* OpenWorkspace({
144
+ // Required. Where the app is served: a hostname in a zone of this account.
145
+ // https://<hostname> is the OIDC issuer, the SAML IdP, and where passkeys work.
146
+ hostname: ${JSON.stringify(answers.hostname)},
147
+ // Mail domains, primary first. Every address is on one of them.
148
+ // Email() turns on Email Routing and Email Sending for each.
149
+ mailDomains: ${JSON.stringify(answers.mailDomains)},${ai}
150
+ modules: [Email()],
151
+ // \`bun run dev\` serves the workspace at http://localhost:5173, where
152
+ // passkeys work too; the hostname above is only for the deploy.
153
+ dev: { port: 5173 },
154
+ });
155
+
156
+ // \`workspace\` also holds the OIDC and SAML endpoints and certificate, for
157
+ // wiring up other resources such as a Cloudflare Access login method
158
+ // (https://openworkspace.dev/docs/sso). The deploy prints only the URL.
159
+ return { url: workspace.url };
131
160
  }),
132
161
  );
133
162
  `;
134
163
  }
135
164
 
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: [],
165
+ export const tsconfigJson = `${JSON.stringify(
166
+ {
167
+ compilerOptions: {
168
+ target: "ES2023",
169
+ lib: ["ES2023"],
170
+ module: "ESNext",
171
+ moduleResolution: "Bundler",
172
+ strict: true,
173
+ skipLibCheck: true,
174
+ noEmit: true,
175
+ allowImportingTsExtensions: true,
176
+ types: ["node"],
177
+ },
178
+ include: ["alchemy.run.ts"],
147
179
  },
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`;
180
+ null,
181
+ 2
182
+ )}\n`;
155
183
 
156
184
  export const gitignore = `node_modules
157
185
  .alchemy
158
186
  .env
159
187
  `;
160
188
 
189
+ function deployTarget(answers: ProjectAnswers) {
190
+ const { cloudflare } = answers;
191
+
192
+ if (!cloudflare) {
193
+ return `
194
+ Sign in to Cloudflare once first: \`bun alchemy profile edit --add Cloudflare\`.
195
+ `;
196
+ }
197
+
198
+ const account = `${cloudflare.account.name} (\`${cloudflare.account.id}\`)`;
199
+
200
+ return cloudflare.profile
201
+ ? `
202
+ It deploys to the Cloudflare account ${account}, signed in as Alchemy
203
+ profile \`${cloudflare.profile}\`${cloudflare.profile === "default" ? "" : " (`ALCHEMY_PROFILE` in `.env`)"}.
204
+ If that login expires, run \`bun alchemy profile refresh${cloudflare.profile === "default" ? "" : ` --profile ${cloudflare.profile}`}\`.
205
+ `
206
+ : `
207
+ It deploys to the Cloudflare account ${account}, with the CLOUDFLARE_API_TOKEN and
208
+ CLOUDFLARE_ACCOUNT_ID environment variables.
209
+ `;
210
+ }
211
+
161
212
  export function readme(answers: ProjectAnswers) {
162
213
  return `# ${answers.name}
163
214
 
164
215
  An [OpenWorkspace](https://openworkspace.dev) deployment on your Cloudflare account.
165
216
 
166
- - \`src/worker.ts\` — the workspace: mail domains, AI, and modules.
167
- - \`alchemy.run.ts\` — the Cloudflare resources, managed by [Alchemy](https://alchemy.run).
217
+ - \`alchemy.run.ts\` — the workspace (mail domains, AI, and modules) and its Cloudflare
218
+ resources, managed by [Alchemy](https://alchemy.run). The Worker's code comes from the
219
+ packages; Alchemy writes its entry from this file on every deploy.
168
220
  - \`.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
221
 
170
222
  ## Deploy
171
223
 
172
224
  \`\`\`sh
173
- bun alchemy profile edit --add Cloudflare # once: sign in to Cloudflare
174
225
  bun run deploy
175
226
  \`\`\`
176
-
177
- Open https://${answers.domain} and create the first administrator with a passkey,
227
+ ${deployTarget(answers)}
228
+ Open https://${answers.hostname} and create the first administrator with a passkey,
178
229
  using an address on ${answers.mailDomains[0]}.
179
- ${answers.configureMail ? `
230
+
180
231
  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.`}
232
+ address to the Worker, onboards the mail domains to Email Sending, and subscribes
233
+ the delivery events queue. Email Routing adds the zones' MX and SPF records and
234
+ locks them; remove another mail provider's MX records from a zone first, or the
235
+ deploy fails.
236
+
237
+ Profile photos and the workspace logo need no setup: they are kept in an R2
238
+ bucket the deploy creates and resized by the Worker's Images binding, without
239
+ Cloudflare Images storage or an Images subscription. The first 5,000 unique
240
+ transformations a month are free; each photo or logo size counts once a month.
186
241
 
187
242
  ## Develop
188
243
 
189
- \`bun run dev\` runs the workspace locally with \`alchemy dev\`.
244
+ \`bun run dev\` runs the workspace at http://localhost:5173 on Cloudflare's local
245
+ runtime, with its own local data: create a first administrator there with a
246
+ passkey, as on the deployed app. Mail from outside doesn't reach it.
190
247
 
191
248
  ## Update
192
249
 
@@ -197,15 +254,33 @@ bun run deploy
197
254
  `;
198
255
  }
199
256
 
200
- export function envFile(input: { aiKey?: { name: string; value: string } }) {
257
+ export function envFile(input: {
258
+ aiKey?: { name: string; value: string };
259
+ /** The Alchemy profile signed in to the chosen Cloudflare account, when it isn't "default". */
260
+ alchemyProfile?: string;
261
+ }) {
201
262
  return [
202
263
  "# Secrets for outside services, uploaded as Worker secrets by `alchemy deploy`.",
203
264
  "# Never commit this file. Signing keys need no entry: Alchemy mints them.",
204
- ...(input.aiKey ? ["", `${input.aiKey.name}=${input.aiKey.value}`] : []),
265
+ ...(input.alchemyProfile
266
+ ? [
267
+ "",
268
+ "# The Alchemy profile signed in to this deployment's Cloudflare account.",
269
+ `ALCHEMY_PROFILE=${input.alchemyProfile}`,
270
+ ]
271
+ : []),
272
+ ...(input.aiKey
273
+ ? [
274
+ "",
275
+ input.aiKey.value
276
+ ? `${input.aiKey.name}=${input.aiKey.value}`
277
+ : `# Required to deploy: the AI provider in alchemy.run.ts reads it.\n${input.aiKey.name}=`,
278
+ ]
279
+ : []),
205
280
  "",
206
281
  "# Optional:",
207
282
  "# SPAMHAUS_DQS_KEY=",
208
- "# R2_ACCESS_KEY_ID= / R2_SECRET_ACCESS_KEY= (an R2 API token for the mail bucket) for direct attachment transfers",
283
+ "# SCIM tokens of single sign-on apps declared in alchemy.run.ts, e.g. GRAFANA_SCIM_TOKEN=",
209
284
  "",
210
285
  ].join("\n");
211
286
  }