@cedarjs/cli 7.0.0-canary.3091 → 7.0.0-canary.3093

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.
@@ -0,0 +1,390 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { Listr } from "listr2";
5
+ import { format } from "prettier";
6
+ import { terminalLink } from "termi-link";
7
+ import { colors as c } from "@cedarjs/cli-helpers/colors";
8
+ import { getPrettierOptions } from "@cedarjs/cli-helpers/fileHelpers";
9
+ import {
10
+ addApiPackages,
11
+ addWebPackages
12
+ } from "@cedarjs/cli-helpers/installHelpers";
13
+ import { formatCedarCommand } from "@cedarjs/cli-helpers/packageManager/display";
14
+ import { runTransitiveBin } from "@cedarjs/cli-helpers/packageManager/exec";
15
+ import { getDataMigrationsPath, getSchemaPath } from "@cedarjs/project-config";
16
+ import { errorTelemetry } from "@cedarjs/telemetry";
17
+ import { getPaths, transformTSToJS, writeFile } from "../../../lib/index.js";
18
+ import { isTypeScriptProject } from "../../../lib/project.js";
19
+ import { runTransform } from "../../../lib/runTransform.js";
20
+ import {
21
+ AUTH_NOT_SET_UP_MESSAGE,
22
+ hasWebAuthFile,
23
+ noUserModelMessage
24
+ } from "./preflight.js";
25
+ import { editSchema, hasModel } from "./schemaPrisma.js";
26
+ const DEFAULT_TENANT_FIELD = "organizationId";
27
+ const AUTH_SNIPPET = `
28
+ export const getCurrentUser = async (session) => {
29
+ return await db.user.findUnique({
30
+ where: { id: session.id },
31
+ select: {
32
+ // ...your existing fields...
33
+ memberships: {
34
+ select: {
35
+ id: true,
36
+ organizationId: true,
37
+ role: true,
38
+ organization: { select: { id: true, slug: true, name: true } },
39
+ },
40
+ },
41
+ },
42
+ })
43
+ }
44
+
45
+ export { hasOrgRole, requireMembership } from '@cedarjs/tenancy'
46
+ `;
47
+ const SIGNUP_SNIPPET = `
48
+ handler: async ({ username, hashedPassword, salt, userAttributes }) => {
49
+ const user = await db.user.create({
50
+ data: { email: username, hashedPassword, salt },
51
+ })
52
+
53
+ await ensureDefaultOrganization({
54
+ currentUser: user,
55
+ invitationToken: userAttributes.invitationToken,
56
+ })
57
+
58
+ return user
59
+ },
60
+ `;
61
+ const handler = async ({ tenantField, force }) => {
62
+ const paths = getPaths();
63
+ if (!hasWebAuthFile(paths.web.src)) {
64
+ console.error(c.error(AUTH_NOT_SET_UP_MESSAGE));
65
+ process.exit(1);
66
+ }
67
+ const preflightSchemaPath = await getSchemaPath(paths.api.prismaConfig);
68
+ if (!hasModel(fs.readFileSync(preflightSchemaPath, "utf-8"), "User")) {
69
+ console.error(
70
+ c.error(
71
+ noUserModelMessage(path.relative(paths.base, preflightSchemaPath))
72
+ )
73
+ );
74
+ process.exit(1);
75
+ }
76
+ const projectIsTypescript = isTypeScriptProject();
77
+ const ext = projectIsTypescript ? "ts" : "js";
78
+ const componentExt = projectIsTypescript ? "tsx" : "jsx";
79
+ const packageJson = await import(pathToFileURL(path.join(paths.base, "package.json")).href, { with: { type: "json" } });
80
+ const cedarVersion = packageJson.default.devDependencies["@cedarjs/core"] ?? "latest";
81
+ const authPath = path.join(paths.api.lib, `auth.${ext}`);
82
+ const graphqlPath = path.join(paths.api.functions, `graphql.${ext}`);
83
+ const functionsAuthPath = path.join(paths.api.functions, `auth.${ext}`);
84
+ const isDbAuthProject = fs.existsSync(functionsAuthPath) && fs.readFileSync(functionsAuthPath, "utf-8").includes("DbAuthHandler");
85
+ const writeTemplateFile = async (templateFile, outputPath) => {
86
+ const templatePath = path.resolve(
87
+ import.meta.dirname,
88
+ "templates",
89
+ templateFile
90
+ );
91
+ const templateContent = fs.readFileSync(templatePath, {
92
+ encoding: "utf8",
93
+ flag: "r"
94
+ });
95
+ const content = projectIsTypescript ? templateContent : await transformTSToJS(outputPath, templateContent);
96
+ return writeFile(outputPath, content, { overwriteExisting: force });
97
+ };
98
+ const tasks = new Listr(
99
+ [
100
+ {
101
+ ...addApiPackages([`@cedarjs/tenancy@${cedarVersion}`]),
102
+ title: "Adding @cedarjs/tenancy to your api side..."
103
+ },
104
+ {
105
+ ...addWebPackages([`@cedarjs/tenancy@${cedarVersion}`]),
106
+ title: "Adding @cedarjs/tenancy to your web side..."
107
+ },
108
+ {
109
+ title: "Adding Organization and Membership models to schema.prisma...",
110
+ task: async () => {
111
+ const schemaPath = await getSchemaPath(paths.api.prismaConfig);
112
+ const schema = fs.readFileSync(schemaPath, "utf-8");
113
+ let updatedSchema;
114
+ try {
115
+ updatedSchema = editSchema(schema, { force });
116
+ } catch (e) {
117
+ const message = e instanceof Error ? e.message : String(e);
118
+ if (message === "RW_TENANCY_ERR_NO_USER_MODEL") {
119
+ throw new Error(
120
+ "No `User` model found in schema.prisma. Set up authentication first (e.g. `yarn cedar setup auth dbAuth`) before running `yarn cedar setup tenancy`."
121
+ );
122
+ }
123
+ if (message === "RW_TENANCY_ERR_MODELS_EXIST") {
124
+ throw new Error(
125
+ "`Organization` and/or `Membership` models already exist in schema.prisma. Re-run with --force to keep them as-is and continue with the rest of the setup."
126
+ );
127
+ }
128
+ throw e;
129
+ }
130
+ fs.writeFileSync(schemaPath, updatedSchema);
131
+ try {
132
+ await runTransitiveBin(
133
+ "prisma",
134
+ ["format", "--config", paths.api.prismaConfig],
135
+ { cwd: paths.base }
136
+ );
137
+ } catch {
138
+ throw new Error(
139
+ "`prisma format` failed, so the `memberships` relation was not added to the `User` model. Add it by hand: `memberships Membership[]` as the last field of `model User { ... }`, then re-run this command."
140
+ );
141
+ }
142
+ const membershipsOccurrences = (schema2) => (schema2.match(/memberships\s+Membership\[\]/g) ?? []).length;
143
+ const formattedSchema = fs.readFileSync(schemaPath, "utf-8");
144
+ if (membershipsOccurrences(formattedSchema) <= membershipsOccurrences(updatedSchema)) {
145
+ throw new Error(
146
+ "`prisma format` did not add the `memberships` relation to the `User` model. Add it by hand: `memberships Membership[]` as the last field of `model User { ... }`, then re-run this command."
147
+ );
148
+ }
149
+ }
150
+ },
151
+ {
152
+ title: "Wrapping api/src/lib/db with the tenancy Prisma extension...",
153
+ task: async () => {
154
+ const dbPath = path.join(paths.api.lib, `db.${ext}`);
155
+ const transformResult = await runTransform({
156
+ transformPath: path.join(import.meta.dirname, "dbCodemod.js"),
157
+ targetPaths: [dbPath],
158
+ options: tenantField !== DEFAULT_TENANT_FIELD ? { tenantField } : {}
159
+ });
160
+ if (transformResult.error) {
161
+ if (transformResult.error === "RW_CODEMOD_ERR_OLD_FORMAT") {
162
+ throw new Error(
163
+ "It looks like your api/src/lib/db file is using the old format. Please update it as per the v8 upgrade guide, then run `yarn cedar setup tenancy` again."
164
+ );
165
+ }
166
+ throw new Error(
167
+ "Could not add the tenancy Prisma extension. Please modify api/src/lib/db by hand: wrap the `db` export in `.$extends(createTenancyExtension({ models: { allExcept: ['user', 'organization', 'membership'] } }))`."
168
+ );
169
+ }
170
+ }
171
+ },
172
+ {
173
+ title: "Adding memberships to getCurrentUser and re-exporting tenancy helpers...",
174
+ task: async (_ctx, task) => {
175
+ if (!fs.existsSync(authPath)) {
176
+ task.skip("No api/src/lib/auth file found; skipping.");
177
+ return;
178
+ }
179
+ const transformResult = await runTransform({
180
+ transformPath: path.join(import.meta.dirname, "authCodemod.js"),
181
+ targetPaths: [authPath]
182
+ });
183
+ if (transformResult.error) {
184
+ task.output = `Could not update api/src/lib/auth automatically. Please add this by hand:
185
+ ${AUTH_SNIPPET}`;
186
+ }
187
+ }
188
+ },
189
+ {
190
+ title: "Wiring api/src/functions/graphql for tenancy...",
191
+ task: async () => {
192
+ const transformResult = await runTransform({
193
+ transformPath: path.join(import.meta.dirname, "graphqlCodemod.js"),
194
+ targetPaths: [graphqlPath]
195
+ });
196
+ if (transformResult.error) {
197
+ if (transformResult.error === "RW_CODEMOD_ERR_GRAPHQL_CONTEXT_EXISTS") {
198
+ throw new Error(
199
+ "api/src/functions/graphql already has a `context` option. Please wire it up for tenancy by hand; see the multi-tenancy how-to for the shape it needs."
200
+ );
201
+ }
202
+ throw new Error(
203
+ "Could not find `createGraphQLHandler({ ... })` in api/src/functions/graphql. Please wire it up for tenancy by hand; see the multi-tenancy how-to for the shape it needs."
204
+ );
205
+ }
206
+ },
207
+ skip: () => fs.existsSync(graphqlPath) ? false : "No api/src/functions/graphql file found; skipping."
208
+ },
209
+ {
210
+ title: "Adding the dbAuth signup handler for tenancy...",
211
+ task: async (_ctx, task) => {
212
+ const transformResult = await runTransform({
213
+ transformPath: path.join(import.meta.dirname, "signupCodemod.js"),
214
+ targetPaths: [functionsAuthPath]
215
+ });
216
+ if (transformResult.error) {
217
+ task.output = `Could not update the dbAuth signup handler automatically. Please add this to api/src/functions/auth's signupOptions:
218
+ ${SIGNUP_SNIPPET}`;
219
+ }
220
+ },
221
+ skip: () => isDbAuthProject ? false : "Not a dbAuth project; skipping."
222
+ },
223
+ {
224
+ title: "Adding the requireMembership directive...",
225
+ task: async () => {
226
+ const directiveDir = path.join(
227
+ paths.api.directives,
228
+ "requireMembership"
229
+ );
230
+ await writeTemplateFile(
231
+ "requireMembership.ts.template",
232
+ path.join(directiveDir, `requireMembership.${ext}`)
233
+ );
234
+ await writeTemplateFile(
235
+ "requireMembership.test.ts.template",
236
+ path.join(directiveDir, `requireMembership.test.${ext}`)
237
+ );
238
+ }
239
+ },
240
+ {
241
+ title: "Adding the organizations service...",
242
+ task: async () => {
243
+ const serviceDir = path.join(paths.api.services, "organizations");
244
+ await writeTemplateFile(
245
+ "organizations.ts.template",
246
+ path.join(serviceDir, `organizations.${ext}`)
247
+ );
248
+ await writeTemplateFile(
249
+ "organizations.test.ts.template",
250
+ path.join(serviceDir, `organizations.test.${ext}`)
251
+ );
252
+ await writeTemplateFile(
253
+ "organizations.scenarios.ts.template",
254
+ path.join(serviceDir, `organizations.scenarios.${ext}`)
255
+ );
256
+ await writeTemplateFile(
257
+ "organizations.sdl.ts.template",
258
+ path.join(paths.api.graphql, `organizations.sdl.${ext}`)
259
+ );
260
+ }
261
+ },
262
+ {
263
+ title: "Adding a data migration to backfill existing users...",
264
+ task: async () => {
265
+ const dataMigrationsPath = await getDataMigrationsPath(
266
+ paths.api.prismaConfig
267
+ );
268
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().split(".")[0].replace(/\D/g, "");
269
+ await writeTemplateFile(
270
+ "ensureDefaultOrganizations.dataMigration.ts.template",
271
+ path.join(
272
+ dataMigrationsPath,
273
+ `${timestamp}-ensure-default-organizations.${ext}`
274
+ )
275
+ );
276
+ }
277
+ },
278
+ {
279
+ title: "Adding OrgScope and the invitation landing page...",
280
+ task: async () => {
281
+ await writeTemplateFile(
282
+ "OrgScope.tsx.template",
283
+ path.join(
284
+ paths.web.components,
285
+ "OrgScope",
286
+ `OrgScope.${componentExt}`
287
+ )
288
+ );
289
+ await writeTemplateFile(
290
+ "InvitePage.tsx.template",
291
+ path.join(
292
+ paths.web.pages,
293
+ "InvitePage",
294
+ `InvitePage.${componentExt}`
295
+ )
296
+ );
297
+ }
298
+ },
299
+ {
300
+ title: "Prettifying changed files",
301
+ task: async (_ctx, task) => {
302
+ const prettifyPaths = [
303
+ path.join(paths.api.lib, "db.js"),
304
+ path.join(paths.api.lib, "db.ts"),
305
+ path.join(paths.api.lib, "auth.js"),
306
+ path.join(paths.api.lib, "auth.ts"),
307
+ path.join(paths.api.functions, "graphql.js"),
308
+ path.join(paths.api.functions, "graphql.ts"),
309
+ path.join(paths.api.functions, "auth.js"),
310
+ path.join(paths.api.functions, "auth.ts")
311
+ ];
312
+ for (const prettifyPath of prettifyPaths) {
313
+ try {
314
+ if (!fs.existsSync(prettifyPath)) {
315
+ continue;
316
+ }
317
+ const source = fs.readFileSync(prettifyPath, "utf-8");
318
+ const prettierOptions = await getPrettierOptions();
319
+ const prettifiedApp = await format(source, {
320
+ ...prettierOptions,
321
+ parser: "babel-ts"
322
+ });
323
+ fs.writeFileSync(prettifyPath, prettifiedApp, "utf-8");
324
+ } catch {
325
+ task.output = "Couldn't prettify the changes. Please reformat the files manually if needed.";
326
+ }
327
+ }
328
+ }
329
+ },
330
+ {
331
+ title: "Next steps...",
332
+ task: (_ctx, task) => {
333
+ const migrateCommand = formatCedarCommand([
334
+ "prisma",
335
+ "migrate",
336
+ "dev"
337
+ ]);
338
+ const dataMigrateCommand = formatCedarCommand(["data-migrate", "up"]);
339
+ task.title = `Next steps...
340
+
341
+ ${c.success("\nMulti-tenancy configured!\n")}
342
+
343
+ 1. Run ${c.highlight(migrateCommand)} to create the Organization/Membership
344
+ tables, then ${c.highlight(dataMigrateCommand)} to give every existing
345
+ user a default organization.
346
+ 2. \`db.ts\`'s tenancy extension scopes every model except
347
+ User/Organization/Membership. For each existing model (e.g.
348
+ Contact) whose rows belong to one organization, add ${c.highlight("organizationId String")} plus ${c.highlight("@@index([organizationId])")}
349
+ to it in schema.prisma; for each one that stays global, add it
350
+ to the ${c.highlight("allExcept")} list in api/src/lib/db instead.
351
+ 3. Wrap your organization routes with the generated OrgScope in
352
+ web/src/Routes.tsx:
353
+
354
+ <Set wrap={OrgScope}>
355
+ <Route path="/org/{orgSlug}/projects" page={ProjectsPage} name="projects" />
356
+ </Set>
357
+
358
+ and add the invitation route outside it:
359
+
360
+ <Route path="/invite/{token}" page={InvitePage} name="invite" />
361
+
362
+ 4. Wrap any plain api/src/functions/* handler that touches
363
+ tenant-owned models with ${c.highlight("withTenancy")} from ${c.highlight(
364
+ "@cedarjs/tenancy"
365
+ )}.
366
+
367
+ Check out the docs for more info:
368
+ ${terminalLink("", "https://cedarjs.com/docs/tenancy")}
369
+
370
+ `;
371
+ }
372
+ }
373
+ ],
374
+ {
375
+ rendererOptions: { collapseSubtasks: false }
376
+ }
377
+ );
378
+ try {
379
+ await tasks.run();
380
+ } catch (e) {
381
+ const message = e instanceof Error ? e.message : String(e);
382
+ const exitCode = e instanceof Error && "exitCode" in e && typeof e.exitCode === "number" ? e.exitCode : 1;
383
+ errorTelemetry(process.argv, message);
384
+ console.error(c.error(message));
385
+ process.exit(exitCode);
386
+ }
387
+ };
388
+ export {
389
+ handler
390
+ };
@@ -16,11 +16,12 @@ import * as setupNeon from "./setup/neon/neon.js";
16
16
  import * as setupPackage from "./setup/package/package.js";
17
17
  import * as setupRealtime from "./setup/realtime/realtime.js";
18
18
  import * as setupServerFile from "./setup/server-file/serverFile.js";
19
+ import * as setupTenancy from "./setup/tenancy/tenancy.js";
19
20
  import * as setupUi from "./setup/ui/ui.js";
20
21
  import * as setupUploads from "./setup/uploads/uploads.js";
21
22
  const command = "setup <command>";
22
23
  const description = "Initialize project config and install packages";
23
- const builder = (yargs) => yargs.command(setupAuth).command(setupCache).command(setupDatabase).command(setupDeploy).command(setupDocker).command(setupGenerator).command(setupGraphql).command(setupI18n).command(setupJobs).command(setupMailer).command(setupMiddleware).command(setupMonitoring).command(setupNeon).command(setupPackage).command(setupRealtime).command(setupServerFile).command(setupUi).command(setupUploads).demandCommand().middleware(detectCedarVersion).epilogue(
24
+ const builder = (yargs) => yargs.command(setupAuth).command(setupCache).command(setupDatabase).command(setupDeploy).command(setupDocker).command(setupGenerator).command(setupGraphql).command(setupI18n).command(setupJobs).command(setupMailer).command(setupMiddleware).command(setupMonitoring).command(setupNeon).command(setupPackage).command(setupRealtime).command(setupServerFile).command(setupTenancy).command(setupUi).command(setupUploads).demandCommand().middleware(detectCedarVersion).epilogue(
24
25
  `Also see the ${terminalLink(
25
26
  "CedarJS CLI Reference",
26
27
  "https://cedarjs.com/docs/cli-commands#setup"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cedarjs/cli",
3
- "version": "7.0.0-canary.3091",
3
+ "version": "7.0.0-canary.3093",
4
4
  "description": "The CedarJS Command Line",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,17 +36,17 @@
36
36
  "@babel/preset-typescript": "7.29.7",
37
37
  "@babel/traverse": "7.29.8",
38
38
  "@babel/types": "7.29.8",
39
- "@cedarjs/api-server": "7.0.0-canary.3091",
40
- "@cedarjs/babel-config": "7.0.0-canary.3091",
41
- "@cedarjs/cli-helpers": "7.0.0-canary.3091",
42
- "@cedarjs/internal": "7.0.0-canary.3091",
43
- "@cedarjs/prerender": "7.0.0-canary.3091",
44
- "@cedarjs/project-config": "7.0.0-canary.3091",
45
- "@cedarjs/structure": "7.0.0-canary.3091",
46
- "@cedarjs/telemetry": "7.0.0-canary.3091",
47
- "@cedarjs/utils": "7.0.0-canary.3091",
48
- "@cedarjs/vite": "7.0.0-canary.3091",
49
- "@cedarjs/web-server": "7.0.0-canary.3091",
39
+ "@cedarjs/api-server": "7.0.0-canary.3093",
40
+ "@cedarjs/babel-config": "7.0.0-canary.3093",
41
+ "@cedarjs/cli-helpers": "7.0.0-canary.3093",
42
+ "@cedarjs/internal": "7.0.0-canary.3093",
43
+ "@cedarjs/prerender": "7.0.0-canary.3093",
44
+ "@cedarjs/project-config": "7.0.0-canary.3093",
45
+ "@cedarjs/structure": "7.0.0-canary.3093",
46
+ "@cedarjs/telemetry": "7.0.0-canary.3093",
47
+ "@cedarjs/utils": "7.0.0-canary.3093",
48
+ "@cedarjs/vite": "7.0.0-canary.3093",
49
+ "@cedarjs/web-server": "7.0.0-canary.3093",
50
50
  "@listr2/prompt-adapter-enquirer": "4.3.1",
51
51
  "@opentelemetry/api": "1.9.1",
52
52
  "@opentelemetry/core": "1.30.1",
@@ -94,7 +94,7 @@
94
94
  "yargs": "17.7.3"
95
95
  },
96
96
  "devDependencies": {
97
- "@cedarjs/framework-tools": "7.0.0-canary.3091",
97
+ "@cedarjs/framework-tools": "7.0.0-canary.3093",
98
98
  "@prisma/dmmf": "7.10.0",
99
99
  "@types/archiver": "^7.0.0",
100
100
  "memfs": "4.68.2",