@cedarjs/cli 9.0.0-canary.1784 → 9.0.0-canary.3124

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.
Files changed (277) hide show
  1. package/README.md +7 -10
  2. package/dist/cfw.js +10 -6
  3. package/dist/commands/build/buildHandler.js +220 -45
  4. package/dist/commands/build/buildPackagesTask.js +21 -20
  5. package/dist/commands/build.js +13 -2
  6. package/dist/commands/check.js +4 -6
  7. package/dist/commands/console.js +6 -4
  8. package/dist/commands/deploy/baremetal/SshExecutor.js +13 -4
  9. package/dist/commands/deploy/baremetal/baremetalHandler.js +116 -50
  10. package/dist/commands/deploy/baremetal.js +11 -4
  11. package/dist/commands/deploy/flightcontrolHandler.js +28 -15
  12. package/dist/commands/deploy/helpers/deployHandler.js +11 -6
  13. package/dist/commands/deploy/netlify.js +1 -1
  14. package/dist/commands/deploy/packing/nft.js +1 -2
  15. package/dist/commands/deploy/render.js +1 -1
  16. package/dist/commands/deploy/renderHandler.js +24 -13
  17. package/dist/commands/deploy/serverlessHandler.js +69 -27
  18. package/dist/commands/deploy/vercel.js +1 -1
  19. package/dist/commands/destroy/component/component.js +2 -3
  20. package/dist/commands/destroy/directive/directive.js +1 -3
  21. package/dist/commands/destroy/directive/directiveHandler.js +2 -4
  22. package/dist/commands/destroy/function/function.js +1 -3
  23. package/dist/commands/destroy/handlerHelpers.js +17 -17
  24. package/dist/commands/destroy/helpers.js +8 -2
  25. package/dist/commands/destroy/layout/layout.js +1 -2
  26. package/dist/commands/destroy/page/pageHandler.js +3 -3
  27. package/dist/commands/destroy/scaffold/scaffoldHandler.js +31 -12
  28. package/dist/commands/destroy/sdl/sdlHandler.js +3 -3
  29. package/dist/commands/dev/apiDebugFlag.js +5 -4
  30. package/dist/commands/dev/devHandler.js +219 -68
  31. package/dist/commands/dev/packageWatchCommands.js +8 -3
  32. package/dist/commands/dev.js +16 -6
  33. package/dist/commands/execHandler.js +49 -29
  34. package/dist/commands/experimental/live-queries/liveQueries.js +32 -0
  35. package/dist/commands/experimental/live-queries/liveQueriesHandler.js +448 -0
  36. package/dist/commands/experimental/live-queries/templates/liveQueriesListener.ts.template +153 -0
  37. package/dist/commands/experimental/live-queries/templates/migration.sql.template +100 -0
  38. package/dist/commands/experimental/setupInngest.js +2 -2
  39. package/dist/commands/experimental/setupInngestHandler.js +13 -12
  40. package/dist/commands/experimental/setupOpentelemetry.js +2 -2
  41. package/dist/commands/experimental/setupOpentelemetryHandler.js +14 -10
  42. package/dist/commands/experimental/setupReactCompiler.js +2 -2
  43. package/dist/commands/experimental/setupReactCompilerHandler.js +48 -33
  44. package/dist/commands/experimental/setupRsc.js +1 -1
  45. package/dist/commands/experimental/setupRscHandler.js +20 -16
  46. package/dist/commands/experimental/setupStreamingSsr.js +2 -2
  47. package/dist/commands/experimental/setupStreamingSsrHandler.js +49 -34
  48. package/dist/commands/experimental/templates/opentelemetry.ts.template +2 -1
  49. package/dist/commands/experimental/templates/rsc/Document.tsx.template +1 -1
  50. package/dist/commands/experimental/templates/rsc/entry.client.tsx.template +8 -8
  51. package/dist/commands/experimental/templates/streamingSsr/Document.tsx.template +1 -1
  52. package/dist/commands/experimental/templates/streamingSsr/entry.client.tsx.template +6 -6
  53. package/dist/commands/experimental/templates/streamingSsr/tsconfig.json.template +6 -6
  54. package/dist/commands/experimental/util.js +27 -25
  55. package/dist/commands/experimental.js +3 -2
  56. package/dist/commands/generate/cell/cell.js +20 -0
  57. package/dist/commands/generate/cell/cellHandler.js +89 -40
  58. package/dist/commands/generate/cell/templates/cell.tsx.template +21 -2
  59. package/dist/commands/generate/cell/templates/cellFragment.tsx.template +43 -0
  60. package/dist/commands/generate/cell/templates/cellList.tsx.template +21 -2
  61. package/dist/commands/generate/cell/templates/storiesFragment.tsx.template +23 -0
  62. package/dist/commands/generate/cell/templates/test.js.template +1 -1
  63. package/dist/commands/generate/cell/templates/testFragment.js.template +30 -0
  64. package/dist/commands/generate/component/componentHandler.js +14 -16
  65. package/dist/commands/generate/dataMigration/dataMigration.js +36 -18
  66. package/dist/commands/generate/dataMigration/templates/dataMigration.js.template +1 -1
  67. package/dist/commands/generate/dataMigration/templates/dataMigration.ts.template +1 -1
  68. package/dist/commands/generate/dbAuth/dbAuth.js +1 -0
  69. package/dist/commands/generate/dbAuth/dbAuthHandler.js +63 -34
  70. package/dist/commands/generate/dbAuth/templates/login.oauth.tsx.template +164 -0
  71. package/dist/commands/generate/dbAuth/templates/signup.oauth.tsx.template +147 -0
  72. package/dist/commands/generate/directive/directiveHandler.js +14 -16
  73. package/dist/commands/generate/function/function.js +1 -0
  74. package/dist/commands/generate/function/functionHandler.js +14 -19
  75. package/dist/commands/generate/helpers.js +34 -18
  76. package/dist/commands/generate/job/job.js +1 -0
  77. package/dist/commands/generate/job/jobHandler.js +20 -24
  78. package/dist/commands/generate/layout/layoutHandler.js +13 -16
  79. package/dist/commands/generate/model/model.js +1 -0
  80. package/dist/commands/generate/model/modelHandler.js +11 -5
  81. package/dist/commands/generate/ogImage/ogImage.js +1 -0
  82. package/dist/commands/generate/ogImage/ogImageHandler.js +18 -11
  83. package/dist/commands/generate/package/filesTask.js +9 -0
  84. package/dist/commands/generate/package/packageHandler.js +50 -61
  85. package/dist/commands/generate/package/templates/test.ts.template +2 -2
  86. package/dist/commands/generate/package/templates/vitest.config.ts.template +9 -0
  87. package/dist/commands/generate/page/pageHandler.js +27 -24
  88. package/dist/commands/generate/realtime/realtime.js +2 -2
  89. package/dist/commands/generate/realtime/realtimeHandler.js +51 -32
  90. package/dist/commands/generate/realtime/templates/subscriptions/blank/blank.ts.template +1 -1
  91. package/dist/commands/generate/scaffold/scaffold.js +1 -0
  92. package/dist/commands/generate/scaffold/scaffoldHandler.js +176 -49
  93. package/dist/commands/generate/scaffold/templates/lib/formatters.tsx.template +1 -1
  94. package/dist/commands/generate/script/script.js +1 -0
  95. package/dist/commands/generate/script/scriptHandler.js +10 -6
  96. package/dist/commands/generate/script/templates/script.ts.template +9 -4
  97. package/dist/commands/generate/script/templates/tsconfig.json.template +16 -2
  98. package/dist/commands/generate/sdl/sdl.js +4 -3
  99. package/dist/commands/generate/sdl/sdlHandler.js +135 -46
  100. package/dist/commands/generate/sdl/stubFiles.js +132 -0
  101. package/dist/commands/generate/sdl/templates/sdl.js.template +2 -1
  102. package/dist/commands/generate/sdl/templates/sdl.ts.template +2 -1
  103. package/dist/commands/generate/secret/secret.js +20 -20
  104. package/dist/commands/generate/service/service.js +5 -5
  105. package/dist/commands/generate/service/serviceHandler.js +126 -61
  106. package/dist/commands/generate/service/templates/scenarios.ts.template +4 -2
  107. package/dist/commands/generate/service/templates/service.ts.template +22 -8
  108. package/dist/commands/generate/service/templates/test.ts.template +2 -2
  109. package/dist/commands/generate/yargsCommandHelpers.js +7 -2
  110. package/dist/commands/generate/yargsHandlerHelpers.js +20 -18
  111. package/dist/commands/generate.js +4 -4
  112. package/dist/commands/info.js +2 -2
  113. package/dist/commands/jobsHandler.js +7 -4
  114. package/dist/commands/lint.js +26 -69
  115. package/dist/commands/prerenderHandler.js +95 -58
  116. package/dist/commands/prismaHandler.js +51 -26
  117. package/dist/commands/record/init.js +2 -2
  118. package/dist/commands/record.js +4 -3
  119. package/dist/commands/serve.js +245 -31
  120. package/dist/commands/serveApiHandler.js +7 -6
  121. package/dist/commands/serveBothHandler.js +22 -13
  122. package/dist/commands/serveWebHandler.js +3 -2
  123. package/dist/commands/setup/auth/auth.js +15 -11
  124. package/dist/commands/setup/cache/cache.js +1 -1
  125. package/dist/commands/setup/cache/cacheHandler.js +15 -9
  126. package/dist/commands/setup/database/database.js +15 -0
  127. package/dist/commands/setup/database/postgres.js +19 -0
  128. package/dist/commands/setup/database/postgresHandler.js +196 -0
  129. package/dist/commands/setup/database/templates/db.ts.template +32 -0
  130. package/dist/commands/setup/deploy/deploy.js +4 -3
  131. package/dist/commands/setup/deploy/helpers/helpers.js +5 -1
  132. package/dist/commands/setup/deploy/helpers/index.js +132 -6
  133. package/dist/commands/setup/deploy/providers/baremetalHandler.js +28 -6
  134. package/dist/commands/setup/deploy/providers/coherence.js +1 -1
  135. package/dist/commands/setup/deploy/providers/coherenceHandler.js +60 -31
  136. package/dist/commands/setup/deploy/providers/flightcontrolHandler.js +69 -51
  137. package/dist/commands/setup/deploy/providers/netlify.js +6 -0
  138. package/dist/commands/setup/deploy/providers/netlifyHandler.js +114 -13
  139. package/dist/commands/setup/deploy/providers/renderHandler.js +44 -41
  140. package/dist/commands/setup/deploy/providers/serverlessHandler.js +7 -5
  141. package/dist/commands/setup/deploy/providers/universal-deploy.js +11 -0
  142. package/dist/commands/setup/deploy/providers/universalDeployHandler.js +186 -0
  143. package/dist/commands/setup/deploy/providers/vercel.js +6 -0
  144. package/dist/commands/setup/deploy/providers/vercelHandler.js +115 -14
  145. package/dist/commands/setup/deploy/templates/baremetal.js +3 -2
  146. package/dist/commands/setup/deploy/templates/flightcontrol.js +60 -49
  147. package/dist/commands/setup/deploy/templates/netlify.js +2 -1
  148. package/dist/commands/setup/deploy/templates/netlifyUD.js +31 -0
  149. package/dist/commands/setup/deploy/templates/render.js +32 -17
  150. package/dist/commands/setup/docker/docker.js +2 -2
  151. package/dist/commands/setup/docker/dockerHandler.js +74 -39
  152. package/dist/commands/setup/docker/templates/Dockerfile.npm +119 -0
  153. package/dist/commands/setup/docker/templates/Dockerfile.pnpm +112 -0
  154. package/dist/commands/setup/docker/templates/{Dockerfile → Dockerfile.yarn} +4 -7
  155. package/dist/commands/setup/docker/templates/docker-compose.dev.yml +3 -3
  156. package/dist/commands/setup/docker/templates/docker-compose.prod.yml +2 -5
  157. package/dist/commands/setup/docker/templates/dockerignore +1 -0
  158. package/dist/commands/setup/generator/generator.js +1 -1
  159. package/dist/commands/setup/generator/generatorHandler.js +5 -4
  160. package/dist/commands/setup/graphql/features/fragments/appGqlConfigTransform.js +6 -3
  161. package/dist/commands/setup/graphql/features/fragments/fragments.js +1 -1
  162. package/dist/commands/setup/graphql/features/fragments/fragmentsHandler.js +5 -7
  163. package/dist/commands/setup/graphql/features/trustedDocuments/trustedDocuments.js +1 -1
  164. package/dist/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.js +4 -3
  165. package/dist/commands/setup/i18n/i18n.js +1 -1
  166. package/dist/commands/setup/i18n/i18nHandler.js +21 -17
  167. package/dist/commands/setup/jobs/jobs.js +1 -1
  168. package/dist/commands/setup/jobs/jobsHandler.js +17 -12
  169. package/dist/commands/setup/mailer/mailer.js +1 -1
  170. package/dist/commands/setup/mailer/mailerHandler.js +13 -11
  171. package/dist/commands/setup/middleware/ogImage/ogImage.js +1 -1
  172. package/dist/commands/setup/middleware/ogImage/ogImageHandler.js +2 -1
  173. package/dist/commands/setup/monitoring/sentry/sentry.js +1 -1
  174. package/dist/commands/setup/monitoring/sentry/sentryHandler.js +18 -12
  175. package/dist/commands/setup/neon/neon.js +35 -0
  176. package/dist/commands/setup/neon/neonHandler.js +264 -0
  177. package/dist/commands/setup/package/package.js +1 -1
  178. package/dist/commands/setup/package/packageHandler.js +18 -14
  179. package/dist/commands/setup/realtime/addRealtimeToGraphql.js +1 -1
  180. package/dist/commands/setup/realtime/realtime.js +1 -1
  181. package/dist/commands/setup/realtime/realtimeHandler.js +26 -37
  182. package/dist/commands/setup/realtime/templates/realtime.ts.template +1 -1
  183. package/dist/commands/setup/realtime/templates/subscriptions/countdown/countdown.ts.template +1 -1
  184. package/dist/commands/setup/realtime/templates/subscriptions/newMessage/newMessage.ts.template +1 -1
  185. package/dist/commands/setup/server-file/serverFile.js +1 -1
  186. package/dist/commands/setup/server-file/serverFileHandler.js +18 -10
  187. package/dist/commands/setup/tenancy/authCodemod.js +66 -0
  188. package/dist/commands/setup/tenancy/dbCodemod.js +64 -0
  189. package/dist/commands/setup/tenancy/graphqlCodemod.js +88 -0
  190. package/dist/commands/setup/tenancy/preflight.js +49 -0
  191. package/dist/commands/setup/tenancy/schemaPrisma.js +81 -0
  192. package/dist/commands/setup/tenancy/signupCodemod.js +153 -0
  193. package/dist/commands/setup/tenancy/templates/InvitePage.tsx.template +63 -0
  194. package/dist/commands/setup/tenancy/templates/OrgScope.tsx.template +40 -0
  195. package/dist/commands/setup/tenancy/templates/ensureDefaultOrganizations.dataMigration.ts.template +39 -0
  196. package/dist/commands/setup/tenancy/templates/organizations.scenarios.ts.template +59 -0
  197. package/dist/commands/setup/tenancy/templates/organizations.sdl.ts.template +89 -0
  198. package/dist/commands/setup/tenancy/templates/organizations.test.ts.template +389 -0
  199. package/dist/commands/setup/tenancy/templates/organizations.ts.template +394 -0
  200. package/dist/commands/setup/tenancy/templates/requireMembership.test.ts.template +35 -0
  201. package/dist/commands/setup/tenancy/templates/requireMembership.ts.template +25 -0
  202. package/dist/commands/setup/tenancy/tenancy.js +30 -0
  203. package/dist/commands/setup/tenancy/tenancyHandler.js +425 -0
  204. package/dist/commands/setup/ui/helpers/helpers.js +5 -1
  205. package/dist/commands/setup/ui/libraries/chakra-uiHandler.js +16 -8
  206. package/dist/commands/setup/ui/libraries/mantineHandler.js +26 -16
  207. package/dist/commands/setup/ui/libraries/tailwindcssHandler.js +40 -29
  208. package/dist/commands/setup/uploads/schemaPrisma.js +41 -0
  209. package/dist/commands/setup/uploads/serverFile.js +151 -0
  210. package/dist/commands/setup/uploads/templates/requireUploadToken.ts.template +15 -0
  211. package/dist/commands/setup/uploads/templates/srcLibUploads.ts.template +23 -24
  212. package/dist/commands/setup/uploads/templates/uploads.sdl.ts.template +79 -0
  213. package/dist/commands/setup/uploads/templates/uploads.ts.template +89 -0
  214. package/dist/commands/setup/uploads/templates/withDataUri.ts.template +14 -0
  215. package/dist/commands/setup/uploads/templates/withSignedUrl.ts.template +16 -0
  216. package/dist/commands/setup/uploads/uploads.js +49 -7
  217. package/dist/commands/setup/uploads/uploadsHandler.js +266 -72
  218. package/dist/commands/setup.js +5 -4
  219. package/dist/commands/studio.js +1 -1
  220. package/dist/commands/studioHandler.js +2 -2
  221. package/dist/commands/test/datasourceWarning.js +42 -0
  222. package/dist/commands/test/testHandler.js +104 -0
  223. package/dist/commands/test/viteVersionCheck.js +75 -0
  224. package/dist/commands/test.js +16 -19
  225. package/dist/commands/type-check.js +2 -1
  226. package/dist/commands/type-checkHandler.js +25 -18
  227. package/dist/commands/upgrade/preUpgradeScripts.js +11 -11
  228. package/dist/commands/upgrade/upgrade.js +4 -2
  229. package/dist/commands/upgrade/upgradeHandler.js +97 -73
  230. package/dist/index.js +15 -11
  231. package/dist/lib/background.js +22 -1
  232. package/dist/lib/configureStorybook.js +2 -2
  233. package/dist/lib/exec.js +68 -63
  234. package/dist/lib/exit.js +20 -5
  235. package/dist/lib/extendFile.js +23 -13
  236. package/dist/lib/generatePrismaClient.js +48 -12
  237. package/dist/lib/index.js +137 -106
  238. package/dist/lib/loadEnvFiles.js +1 -1
  239. package/dist/lib/locking.js +8 -4
  240. package/dist/lib/merge/algorithms.js +4 -1
  241. package/dist/lib/merge/index.js +78 -41
  242. package/dist/lib/merge/semanticIdentity.js +18 -6
  243. package/dist/lib/merge/strategy.js +86 -36
  244. package/dist/lib/packages.js +23 -13
  245. package/dist/lib/plugin.js +13 -7
  246. package/dist/lib/pluralHelpers.js +6 -2
  247. package/dist/lib/project.js +3 -1
  248. package/dist/lib/rollback.js +7 -7
  249. package/dist/lib/schemaHelpers.js +16 -19
  250. package/dist/lib/test.js +20 -5
  251. package/dist/lib/updateCheck.js +47 -18
  252. package/dist/middleware/checkNodeVersion.js +9 -4
  253. package/dist/middleware/{detectProjectRxVersion.js → detectProjectCedarVersion.js} +2 -2
  254. package/dist/plugin.js +18 -12
  255. package/dist/telemetry/exporter.js +12 -5
  256. package/dist/telemetry/index.js +4 -3
  257. package/dist/telemetry/resource.js +9 -12
  258. package/dist/telemetry/send.js +14 -10
  259. package/dist/testLib/cells.js +5 -3
  260. package/package.json +44 -41
  261. package/LICENSE +0 -21
  262. package/dist/commands/consoleHandler.js +0 -68
  263. package/dist/commands/setup/tsconfig/tsconfig.js +0 -25
  264. package/dist/commands/setup/tsconfig/tsconfigHandler.js +0 -59
  265. package/dist/commands/setup/uploads/dbCodemod.js +0 -28
  266. package/dist/commands/setup/uploads/templates/signedUrl.ts.template +0 -21
  267. package/dist/commands/setup/vite/templates/vite.config.ts.template +0 -19
  268. package/dist/commands/setup/vite/vite.js +0 -38
  269. package/dist/commands/setup/vite/viteHandler.js +0 -83
  270. package/dist/commands/testEsm.js +0 -36
  271. package/dist/commands/testHandler.js +0 -137
  272. package/dist/commands/testHandlerEsm.js +0 -85
  273. package/dist/commands/ts-to-js.js +0 -20
  274. package/dist/lib/cedarPluralize.js +0 -56
  275. package/dist/lib/colors.js +0 -18
  276. package/dist/testLib/getFilesWithPattern.js +0 -21
  277. /package/dist/{index.d.js → global.d.js} +0 -0
@@ -0,0 +1,425 @@
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
+ authNotSetUpMessage,
22
+ hasWebAuthFile,
23
+ noUserModelMessage
24
+ } from "./preflight.js";
25
+ import {
26
+ editSchema,
27
+ hasModel,
28
+ MEMBERSHIP_MODEL,
29
+ ORGANIZATION_MODEL
30
+ } from "./schemaPrisma.js";
31
+ const DEFAULT_TENANT_FIELD = "organizationId";
32
+ const AUTH_SNIPPET = `
33
+ export const getCurrentUser = async (session) => {
34
+ return await db.user.findUnique({
35
+ where: { id: session.id },
36
+ select: {
37
+ // ...your existing fields...
38
+ memberships: {
39
+ select: {
40
+ id: true,
41
+ organizationId: true,
42
+ role: true,
43
+ organization: { select: { id: true, slug: true, name: true } },
44
+ },
45
+ },
46
+ },
47
+ })
48
+ }
49
+
50
+ export { hasOrgRole, requireMembership } from '@cedarjs/tenancy'
51
+ `;
52
+ const SIGNUP_SNIPPET = `
53
+ handler: async ({ username, hashedPassword, salt, userAttributes }) => {
54
+ const user = await db.user.create({
55
+ data: { email: username, hashedPassword, salt },
56
+ })
57
+
58
+ await ensureDefaultOrganization({
59
+ currentUser: user,
60
+ invitationToken: userAttributes.invitationToken,
61
+ })
62
+
63
+ return user
64
+ },
65
+ `;
66
+ const handler = async ({ tenantField, force }) => {
67
+ const paths = getPaths();
68
+ if (!hasWebAuthFile(paths.web.src)) {
69
+ console.error(c.error(authNotSetUpMessage()));
70
+ process.exit(1);
71
+ }
72
+ const preflightSchemaPath = await getSchemaPath(paths.api.prismaConfig);
73
+ if (!hasModel(fs.readFileSync(preflightSchemaPath, "utf-8"), "User")) {
74
+ console.error(
75
+ c.error(
76
+ noUserModelMessage(path.relative(paths.base, preflightSchemaPath))
77
+ )
78
+ );
79
+ process.exit(1);
80
+ }
81
+ const projectIsTypescript = isTypeScriptProject();
82
+ const ext = projectIsTypescript ? "ts" : "js";
83
+ const componentExt = projectIsTypescript ? "tsx" : "jsx";
84
+ const packageJson = await import(pathToFileURL(path.join(paths.base, "package.json")).href, { with: { type: "json" } });
85
+ const cedarVersion = packageJson.default.devDependencies["@cedarjs/core"] ?? "latest";
86
+ const authPath = path.join(paths.api.lib, `auth.${ext}`);
87
+ const graphqlPath = path.join(paths.api.functions, `graphql.${ext}`);
88
+ const functionsAuthPath = path.join(paths.api.functions, `auth.${ext}`);
89
+ const isDbAuthProject = fs.existsSync(functionsAuthPath) && fs.readFileSync(functionsAuthPath, "utf-8").includes("DbAuthHandler");
90
+ const writeTemplateFile = async (templateFile, outputPath, replacements = {}) => {
91
+ const dirname = import.meta.dirname;
92
+ const templatePath = path.resolve(dirname, "templates", templateFile);
93
+ let templateContent = fs.readFileSync(templatePath, "utf-8");
94
+ for (const [token, value] of Object.entries(replacements)) {
95
+ templateContent = templateContent.replaceAll(token, value);
96
+ }
97
+ const content = projectIsTypescript ? templateContent : await transformTSToJS(outputPath, templateContent);
98
+ return writeFile(outputPath, content, { overwriteExisting: force });
99
+ };
100
+ const tasks = new Listr(
101
+ [
102
+ {
103
+ ...addApiPackages([`@cedarjs/tenancy@${cedarVersion}`]),
104
+ title: "Adding @cedarjs/tenancy to your api side..."
105
+ },
106
+ {
107
+ ...addWebPackages([`@cedarjs/tenancy@${cedarVersion}`]),
108
+ title: "Adding @cedarjs/tenancy to your web side..."
109
+ },
110
+ {
111
+ title: "Adding Organization and Membership models to schema.prisma...",
112
+ task: async (ctx, task) => {
113
+ const schemaPath = await getSchemaPath(paths.api.prismaConfig);
114
+ const schema = fs.readFileSync(schemaPath, "utf-8");
115
+ let editResult;
116
+ try {
117
+ editResult = editSchema(schema, { force });
118
+ } catch (e) {
119
+ const message = e instanceof Error ? e.message : String(e);
120
+ if (message === "CEDAR_TENANCY_ERR_NO_USER_MODEL") {
121
+ const authSetup = formatCedarCommand(["setup", "auth", "dbAuth"]);
122
+ const tenancySetup = formatCedarCommand(["setup", "tenancy"]);
123
+ throw new Error(
124
+ `No \`User\` model found in schema.prisma. Set up authentication first (e.g. \`${authSetup}\`) before running \`${tenancySetup}\`.`
125
+ );
126
+ }
127
+ throw e;
128
+ }
129
+ ctx.modelsExistOutcome = editResult.outcome;
130
+ fs.writeFileSync(schemaPath, editResult.schema);
131
+ if (editResult.outcome === "skipped") {
132
+ task.output = `\`Organization\` and/or \`Membership\` models already exist in schema.prisma and were left as-is. Add these fields and relations by hand so tenancy can use them:
133
+
134
+ ${ORGANIZATION_MODEL}
135
+
136
+ ${MEMBERSHIP_MODEL}
137
+
138
+ Re-run with --force to have this command append its own versions beside them instead, so you can diff and merge rather than retype.`;
139
+ return;
140
+ }
141
+ try {
142
+ await runTransitiveBin(
143
+ "prisma",
144
+ ["format", "--config", paths.api.prismaConfig],
145
+ { cwd: paths.base }
146
+ );
147
+ } catch {
148
+ if (editResult.outcome === "forced") {
149
+ task.output = '`prisma format` failed because the appended Organization/Membership clash with your existing ones, as requested by --force. Continuing with the rest of the setup; see "Next steps" for how to merge them.';
150
+ return;
151
+ }
152
+ throw new Error(
153
+ "`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."
154
+ );
155
+ }
156
+ const membershipsOccurrences = (schema2) => (schema2.match(/memberships\s+Membership\[\]/g) ?? []).length;
157
+ const formattedSchema = fs.readFileSync(schemaPath, "utf-8");
158
+ if (membershipsOccurrences(formattedSchema) <= membershipsOccurrences(editResult.schema)) {
159
+ if (editResult.outcome === "forced") {
160
+ task.output = 'The `memberships` relation was not added to the `User` model, likely because of the clash from --force. Continuing with the rest of the setup; see "Next steps" for how to merge the appended models by hand.';
161
+ return;
162
+ }
163
+ throw new Error(
164
+ "`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."
165
+ );
166
+ }
167
+ }
168
+ },
169
+ {
170
+ title: "Wrapping api/src/lib/db with the tenancy Prisma extension...",
171
+ task: async () => {
172
+ const dbPath = path.join(paths.api.lib, `db.${ext}`);
173
+ const transformResult = await runTransform({
174
+ transformPath: path.join(import.meta.dirname, "dbCodemod.js"),
175
+ targetPaths: [dbPath],
176
+ options: tenantField !== DEFAULT_TENANT_FIELD ? { tenantField } : {}
177
+ });
178
+ if (transformResult.error) {
179
+ if (transformResult.error === "CEDAR_CODEMOD_ERR_OLD_FORMAT") {
180
+ const tenancySetup = formatCedarCommand(["setup", "tenancy"]);
181
+ throw new Error(
182
+ `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 \`${tenancySetup}\` again.`
183
+ );
184
+ }
185
+ throw new Error(
186
+ "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'] } }))`."
187
+ );
188
+ }
189
+ }
190
+ },
191
+ {
192
+ title: "Adding memberships to getCurrentUser and re-exporting tenancy helpers...",
193
+ task: async (_ctx, task) => {
194
+ if (!fs.existsSync(authPath)) {
195
+ task.skip("No api/src/lib/auth file found; skipping.");
196
+ return;
197
+ }
198
+ const transformResult = await runTransform({
199
+ transformPath: path.join(import.meta.dirname, "authCodemod.js"),
200
+ targetPaths: [authPath]
201
+ });
202
+ if (transformResult.error) {
203
+ task.output = `Could not update api/src/lib/auth automatically. Please add this by hand:
204
+ ${AUTH_SNIPPET}`;
205
+ }
206
+ }
207
+ },
208
+ {
209
+ title: "Wiring api/src/functions/graphql for tenancy...",
210
+ task: async () => {
211
+ const transformResult = await runTransform({
212
+ transformPath: path.join(import.meta.dirname, "graphqlCodemod.js"),
213
+ targetPaths: [graphqlPath]
214
+ });
215
+ if (transformResult.error) {
216
+ if (transformResult.error === "CEDAR_CODEMOD_ERR_GRAPHQL_CONTEXT_EXISTS") {
217
+ throw new Error(
218
+ "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."
219
+ );
220
+ }
221
+ throw new Error(
222
+ "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."
223
+ );
224
+ }
225
+ },
226
+ skip: () => fs.existsSync(graphqlPath) ? false : "No api/src/functions/graphql file found; skipping."
227
+ },
228
+ {
229
+ title: "Adding the dbAuth signup handler for tenancy...",
230
+ task: async (_ctx, task) => {
231
+ const transformResult = await runTransform({
232
+ transformPath: path.join(import.meta.dirname, "signupCodemod.js"),
233
+ targetPaths: [functionsAuthPath]
234
+ });
235
+ if (transformResult.error) {
236
+ task.output = `Could not update the dbAuth signup handler automatically. Please add this to api/src/functions/auth's signupOptions:
237
+ ${SIGNUP_SNIPPET}`;
238
+ }
239
+ },
240
+ skip: () => isDbAuthProject ? false : "Not a dbAuth project; skipping."
241
+ },
242
+ {
243
+ title: "Adding the requireMembership directive...",
244
+ task: async () => {
245
+ const directiveDir = path.join(
246
+ paths.api.directives,
247
+ "requireMembership"
248
+ );
249
+ await writeTemplateFile(
250
+ "requireMembership.ts.template",
251
+ path.join(directiveDir, `requireMembership.${ext}`)
252
+ );
253
+ await writeTemplateFile(
254
+ "requireMembership.test.ts.template",
255
+ path.join(directiveDir, `requireMembership.test.${ext}`)
256
+ );
257
+ }
258
+ },
259
+ {
260
+ title: "Adding the organizations service...",
261
+ task: async () => {
262
+ const serviceDir = path.join(paths.api.services, "organizations");
263
+ await writeTemplateFile(
264
+ "organizations.ts.template",
265
+ path.join(serviceDir, `organizations.${ext}`)
266
+ );
267
+ await writeTemplateFile(
268
+ "organizations.test.ts.template",
269
+ path.join(serviceDir, `organizations.test.${ext}`)
270
+ );
271
+ await writeTemplateFile(
272
+ "organizations.scenarios.ts.template",
273
+ path.join(serviceDir, `organizations.scenarios.${ext}`)
274
+ );
275
+ await writeTemplateFile(
276
+ "organizations.sdl.ts.template",
277
+ path.join(paths.api.graphql, `organizations.sdl.${ext}`)
278
+ );
279
+ }
280
+ },
281
+ {
282
+ title: "Adding a data migration to backfill existing users...",
283
+ task: async () => {
284
+ const dataMigrationsPath = await getDataMigrationsPath(
285
+ paths.api.prismaConfig
286
+ );
287
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().split(".")[0].replace(/\D/g, "");
288
+ await writeTemplateFile(
289
+ "ensureDefaultOrganizations.dataMigration.ts.template",
290
+ path.join(
291
+ dataMigrationsPath,
292
+ `${timestamp}-ensure-default-organizations.${ext}`
293
+ ),
294
+ {
295
+ __DATA_MIGRATE_UP_COMMAND__: formatCedarCommand([
296
+ "data-migrate",
297
+ "up"
298
+ ]),
299
+ __PRISMA_MIGRATE_DEV_COMMAND__: formatCedarCommand([
300
+ "prisma",
301
+ "migrate",
302
+ "dev"
303
+ ])
304
+ }
305
+ );
306
+ }
307
+ },
308
+ {
309
+ title: "Adding OrgScope and the invitation landing page...",
310
+ task: async () => {
311
+ await writeTemplateFile(
312
+ "OrgScope.tsx.template",
313
+ path.join(
314
+ paths.web.components,
315
+ "OrgScope",
316
+ `OrgScope.${componentExt}`
317
+ )
318
+ );
319
+ await writeTemplateFile(
320
+ "InvitePage.tsx.template",
321
+ path.join(
322
+ paths.web.pages,
323
+ "InvitePage",
324
+ `InvitePage.${componentExt}`
325
+ )
326
+ );
327
+ }
328
+ },
329
+ {
330
+ title: "Prettifying changed files",
331
+ task: async (_ctx, task) => {
332
+ const prettifyPaths = [
333
+ path.join(paths.api.lib, "db.js"),
334
+ path.join(paths.api.lib, "db.ts"),
335
+ path.join(paths.api.lib, "auth.js"),
336
+ path.join(paths.api.lib, "auth.ts"),
337
+ path.join(paths.api.functions, "graphql.js"),
338
+ path.join(paths.api.functions, "graphql.ts"),
339
+ path.join(paths.api.functions, "auth.js"),
340
+ path.join(paths.api.functions, "auth.ts")
341
+ ];
342
+ for (const prettifyPath of prettifyPaths) {
343
+ try {
344
+ if (!fs.existsSync(prettifyPath)) {
345
+ continue;
346
+ }
347
+ const source = fs.readFileSync(prettifyPath, "utf-8");
348
+ const prettierOptions = await getPrettierOptions();
349
+ const prettifiedApp = await format(source, {
350
+ ...prettierOptions,
351
+ parser: "babel-ts"
352
+ });
353
+ fs.writeFileSync(prettifyPath, prettifiedApp, "utf-8");
354
+ } catch {
355
+ task.output = "Couldn't prettify the changes. Please reformat the files manually if needed.";
356
+ }
357
+ }
358
+ }
359
+ },
360
+ {
361
+ title: "Next steps...",
362
+ task: (ctx, task) => {
363
+ const migrateCommand = formatCedarCommand([
364
+ "prisma",
365
+ "migrate",
366
+ "dev"
367
+ ]);
368
+ const dataMigrateCommand = formatCedarCommand(["data-migrate", "up"]);
369
+ const modelsExistWarning = ctx.modelsExistOutcome === "forced" ? c.error(
370
+ "\nschema.prisma is currently invalid (as requested by --force): merge the appended Organization/Membership blocks with your existing ones, then run `prisma format`.\n"
371
+ ) : ctx.modelsExistOutcome === "skipped" ? c.warning(
372
+ "\nOrganization/Membership already existed and were left as-is: add the fields and relations printed above by hand before continuing.\n"
373
+ ) : "";
374
+ task.title = `Next steps...
375
+
376
+ ${c.success("\nMulti-tenancy configured!\n")}
377
+ ${modelsExistWarning}
378
+ 1. Run ${c.highlight(migrateCommand)} to create the Organization/Membership
379
+ tables, then ${c.highlight(dataMigrateCommand)} to give every existing
380
+ user a default organization.
381
+ 2. \`db.ts\`'s tenancy extension scopes every model except
382
+ User/Organization/Membership. For each existing model (e.g.
383
+ Contact) whose rows belong to one organization, add ${c.highlight("organizationId String")} plus ${c.highlight("@@index([organizationId])")}
384
+ to it in schema.prisma; for each one that stays global, add it
385
+ to the ${c.highlight("allExcept")} list in api/src/lib/db instead.
386
+ 3. Wrap your organization routes with the generated OrgScope in
387
+ web/src/Routes.tsx:
388
+
389
+ <Set wrap={OrgScope}>
390
+ <Route path="/org/{orgSlug}/projects" page={ProjectsPage} name="projects" />
391
+ </Set>
392
+
393
+ and add the invitation route outside it:
394
+
395
+ <Route path="/invite/{token}" page={InvitePage} name="invite" />
396
+
397
+ 4. Wrap any plain api/src/functions/* handler that touches
398
+ tenant-owned models with ${c.highlight("withTenancy")} from ${c.highlight(
399
+ "@cedarjs/tenancy"
400
+ )}.
401
+
402
+ Check out the docs for more info:
403
+ ${terminalLink("", "https://cedarjs.com/docs/tenancy")}
404
+
405
+ `;
406
+ }
407
+ }
408
+ ],
409
+ {
410
+ rendererOptions: { collapseSubtasks: false }
411
+ }
412
+ );
413
+ try {
414
+ await tasks.run();
415
+ } catch (e) {
416
+ const message = e instanceof Error ? e.message : String(e);
417
+ const exitCode = e instanceof Error && "exitCode" in e && typeof e.exitCode === "number" ? e.exitCode : 1;
418
+ errorTelemetry(process.argv, message);
419
+ console.error(c.error(message));
420
+ process.exit(exitCode);
421
+ }
422
+ };
423
+ export {
424
+ handler
425
+ };
@@ -1,6 +1,10 @@
1
1
  function createHandler(componentName) {
2
2
  return async function handler(argv) {
3
- const { handler: importedHandler } = await import(`../libraries/${componentName}Handler.js`);
3
+ const { existsSync } = await import("node:fs");
4
+ const tsPath = `../libraries/${componentName}Handler.ts`;
5
+ const jsPath = `../libraries/${componentName}Handler.js`;
6
+ const resolvedPath = existsSync(new URL(tsPath, import.meta.url)) ? tsPath : jsPath;
7
+ const { handler: importedHandler } = await import(resolvedPath);
4
8
  return importedHandler(argv);
5
9
  };
6
10
  }
@@ -1,8 +1,8 @@
1
1
  import path from "path";
2
- import execa from "execa";
3
2
  import { Listr } from "listr2";
4
- import { recordTelemetryAttributes } from "@cedarjs/cli-helpers";
5
- import c from "../../../../lib/colors.js";
3
+ import { colors as c } from "@cedarjs/cli-helpers/colors";
4
+ import { addWorkspacePackages } from "@cedarjs/cli-helpers/packageManager/packages";
5
+ import { recordTelemetryAttributes } from "@cedarjs/cli-helpers/telemetry";
6
6
  import extendStorybookConfiguration from "../../../../lib/configureStorybook.js";
7
7
  import { extendJSXFile, fileIncludes } from "../../../../lib/extendFile.js";
8
8
  import { getPaths, writeFile } from "../../../../lib/index.js";
@@ -11,7 +11,10 @@ const CHAKRA_THEME_AND_COMMENTS = `// This object will be used to override Chakr
11
11
  const theme = {}
12
12
  export default theme
13
13
  `;
14
- async function handler({ force, install }) {
14
+ async function handler({
15
+ force,
16
+ install
17
+ }) {
15
18
  recordTelemetryAttributes({
16
19
  command: "setup ui chakra-ui",
17
20
  force,
@@ -35,7 +38,9 @@ async function handler({ force, install }) {
35
38
  {
36
39
  title: `Install ${packages.join(", ")}`,
37
40
  task: async () => {
38
- await execa("yarn", ["workspace", "web", "add", ...packages]);
41
+ await addWorkspacePackages("web", packages, {
42
+ cwd: rwPaths.base
43
+ });
39
44
  }
40
45
  }
41
46
  ],
@@ -50,7 +55,9 @@ async function handler({ force, install }) {
50
55
  insertComponent: {
51
56
  name: "ChakraProvider",
52
57
  props: { theme: "extendedTheme" },
53
- within: "RedwoodProvider",
58
+ // Older projects (created before CedarProvider replaced the
59
+ // deprecated RedwoodProvider) may still use RedwoodProvider.
60
+ within: "CedarProvider|RedwoodProvider",
54
61
  insertBefore: "<ColorModeScript />"
55
62
  },
56
63
  imports: [
@@ -89,8 +96,9 @@ async function handler({ force, install }) {
89
96
  try {
90
97
  await tasks.run();
91
98
  } catch (e) {
92
- console.error(c.error(e.message));
93
- process.exit(e?.exitCode || 1);
99
+ console.error(c.error(e instanceof Error ? e.message : String(e)));
100
+ const exitCode = e instanceof Error && "exitCode" in e && typeof e.exitCode === "number" ? e.exitCode : 1;
101
+ process.exit(exitCode);
94
102
  }
95
103
  }
96
104
  export {
@@ -1,9 +1,9 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import execa from "execa";
4
3
  import { Listr } from "listr2";
5
- import { recordTelemetryAttributes } from "@cedarjs/cli-helpers";
6
- import c from "../../../../lib/colors.js";
4
+ import { colors as c } from "@cedarjs/cli-helpers/colors";
5
+ import { addWorkspacePackages } from "@cedarjs/cli-helpers/packageManager/packages";
6
+ import { recordTelemetryAttributes } from "@cedarjs/cli-helpers/telemetry";
7
7
  import extendStorybookConfiguration from "../../../../lib/configureStorybook.js";
8
8
  import { extendJSXFile, fileIncludes } from "../../../../lib/extendFile.js";
9
9
  import { getPaths, writeFile } from "../../../../lib/index.js";
@@ -31,7 +31,11 @@ const theme = {}
31
31
 
32
32
  export default createTheme(theme)
33
33
  `;
34
- async function handler({ force, install, packages }) {
34
+ async function handler({
35
+ force,
36
+ install,
37
+ packages
38
+ }) {
35
39
  recordTelemetryAttributes({
36
40
  command: "setup ui mantine",
37
41
  force,
@@ -52,14 +56,14 @@ async function handler({ force, install, packages }) {
52
56
  {
53
57
  title: `Install ${installPackages.join(", ")}`,
54
58
  task: async () => {
55
- await execa("yarn", [
56
- "workspace",
57
- "web",
58
- "add",
59
- "-D",
60
- "@emotion/react",
61
- ...installPackages
62
- ]);
59
+ await addWorkspacePackages("web", installPackages, {
60
+ cwd: cedarPaths.base,
61
+ dev: true
62
+ });
63
+ await addWorkspacePackages("web", ["@emotion/react"], {
64
+ cwd: cedarPaths.base,
65
+ dev: true
66
+ });
63
67
  }
64
68
  }
65
69
  ],
@@ -74,7 +78,9 @@ async function handler({ force, install, packages }) {
74
78
  insertComponent: {
75
79
  name: "MantineProvider",
76
80
  props: { theme: "theme" },
77
- within: "RedwoodProvider"
81
+ // Older projects (created before CedarProvider replaced the
82
+ // deprecated RedwoodProvider) may still use RedwoodProvider.
83
+ within: "CedarProvider|RedwoodProvider"
78
84
  },
79
85
  imports: [
80
86
  "import { MantineProvider } from '@mantine/core'",
@@ -114,7 +120,10 @@ async function handler({ force, install, packages }) {
114
120
  },
115
121
  {
116
122
  title: "Configure Storybook...",
117
- skip: () => fileIncludes(cedarPaths.web.storybookPreviewConfig, "withMantine"),
123
+ skip: () => {
124
+ const previewConfig = cedarPaths.web.storybookPreviewConfig;
125
+ return previewConfig != null ? fileIncludes(previewConfig, "withMantine") : false;
126
+ },
118
127
  task: async () => await extendStorybookConfiguration(
119
128
  path.join(
120
129
  import.meta.dirname,
@@ -130,8 +139,9 @@ async function handler({ force, install, packages }) {
130
139
  try {
131
140
  await tasks.run();
132
141
  } catch (e) {
133
- console.error(c.error(e.message));
134
- process.exit(e?.exitCode || 1);
142
+ console.error(c.error(e instanceof Error ? e.message : String(e)));
143
+ const exitCode = e instanceof Error && "exitCode" in e && typeof e.exitCode === "number" ? e.exitCode : 1;
144
+ process.exit(exitCode);
135
145
  }
136
146
  }
137
147
  export {