@cedarjs/cli 7.0.0 → 8.0.0-canary.3263
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/dist/commands/build/buildHandler.js +2 -1
- package/dist/commands/build.js +1 -1
- package/dist/commands/check.js +2 -1
- package/dist/commands/deploy/baremetal/baremetalHandler.js +1 -1
- package/dist/commands/deploy/baremetal.js +1 -1
- package/dist/commands/deploy/flightcontrolHandler.js +1 -1
- package/dist/commands/deploy/helpers/deployHandler.js +1 -1
- package/dist/commands/deploy/netlify.js +1 -1
- package/dist/commands/deploy/renderHandler.js +1 -1
- package/dist/commands/deploy/serverlessHandler.js +2 -1
- package/dist/commands/deploy/vercel.js +1 -1
- package/dist/commands/destroy/handlerHelpers.js +1 -1
- package/dist/commands/destroy/page/pageHandler.js +2 -1
- package/dist/commands/destroy/scaffold/scaffoldHandler.js +2 -1
- package/dist/commands/destroy/sdl/sdlHandler.js +2 -1
- package/dist/commands/dev/devHandler.js +3 -4
- package/dist/commands/dev/packageWatchCommands.js +8 -3
- package/dist/commands/dev.js +1 -1
- package/dist/commands/execHandler.js +2 -1
- package/dist/commands/experimental/live-queries/liveQueries.js +1 -1
- package/dist/commands/experimental/live-queries/liveQueriesHandler.js +3 -3
- package/dist/commands/experimental/setupInngest.js +1 -1
- package/dist/commands/experimental/setupInngestHandler.js +1 -1
- package/dist/commands/experimental/setupOpentelemetry.js +1 -1
- package/dist/commands/experimental/setupOpentelemetryHandler.js +2 -1
- package/dist/commands/experimental/setupReactCompiler.js +1 -1
- package/dist/commands/experimental/setupReactCompilerHandler.js +4 -4
- package/dist/commands/experimental/setupRsc.js +1 -1
- package/dist/commands/experimental/setupRscHandler.js +2 -1
- package/dist/commands/experimental/setupStreamingSsr.js +1 -1
- package/dist/commands/experimental/setupStreamingSsrHandler.js +3 -2
- package/dist/commands/generate/cell/cell.js +20 -0
- package/dist/commands/generate/cell/cellHandler.js +68 -20
- package/dist/commands/generate/cell/templates/cell.tsx.template +21 -2
- package/dist/commands/generate/cell/templates/cellFragment.tsx.template +43 -0
- package/dist/commands/generate/cell/templates/cellList.tsx.template +21 -2
- package/dist/commands/generate/cell/templates/storiesFragment.tsx.template +23 -0
- package/dist/commands/generate/cell/templates/test.js.template +1 -1
- package/dist/commands/generate/cell/templates/testFragment.js.template +30 -0
- package/dist/commands/generate/dataMigration/dataMigration.js +2 -1
- package/dist/commands/generate/dbAuth/dbAuthHandler.js +23 -3
- package/dist/commands/generate/dbAuth/templates/login.oauth.tsx.template +164 -0
- package/dist/commands/generate/dbAuth/templates/signup.oauth.tsx.template +147 -0
- package/dist/commands/generate/directive/directiveHandler.js +2 -1
- package/dist/commands/generate/function/functionHandler.js +2 -1
- package/dist/commands/generate/job/jobHandler.js +2 -1
- package/dist/commands/generate/model/modelHandler.js +2 -1
- package/dist/commands/generate/ogImage/ogImageHandler.js +2 -1
- package/dist/commands/generate/package/filesTask.js +9 -12
- package/dist/commands/generate/package/packageHandler.js +3 -4
- package/dist/commands/generate/page/pageHandler.js +2 -1
- package/dist/commands/generate/realtime/realtime.js +1 -1
- package/dist/commands/generate/realtime/realtimeHandler.js +2 -9
- package/dist/commands/generate/realtime/templates/subscriptions/blank/blank.ts.template +1 -1
- package/dist/commands/generate/scaffold/scaffoldHandler.js +10 -5
- package/dist/commands/generate/scaffold/templates/components/NameForm.tsx.template +3 -3
- package/dist/commands/generate/scaffold/templates/lib/formatters.test.tsx.template +11 -0
- package/dist/commands/generate/scaffold/templates/lib/formatters.tsx.template +13 -1
- package/dist/commands/generate/script/scriptHandler.js +2 -1
- package/dist/commands/generate/sdl/sdlHandler.js +2 -1
- package/dist/commands/generate/secret/secret.js +1 -1
- package/dist/commands/generate/service/serviceHandler.js +47 -38
- package/dist/commands/generate/service/templates/service.ts.template +22 -8
- package/dist/commands/generate/service/templates/test.ts.template +1 -1
- package/dist/commands/generate/yargsCommandHelpers.js +1 -1
- package/dist/commands/generate/yargsHandlerHelpers.js +2 -1
- package/dist/commands/generate.js +1 -1
- package/dist/commands/info.js +1 -1
- package/dist/commands/lint.js +1 -1
- package/dist/commands/prerenderHandler.js +11 -4
- package/dist/commands/prismaHandler.js +7 -2
- package/dist/commands/record/init.js +1 -1
- package/dist/commands/serve.js +2 -1
- package/dist/commands/setup/auth/auth.js +2 -4
- package/dist/commands/setup/cache/cache.js +1 -1
- package/dist/commands/setup/cache/cacheHandler.js +2 -1
- package/dist/commands/setup/database/postgres.js +1 -1
- package/dist/commands/setup/database/postgresHandler.js +3 -1
- package/dist/commands/setup/deploy/providers/baremetalHandler.js +2 -1
- package/dist/commands/setup/deploy/providers/coherence.js +1 -1
- package/dist/commands/setup/deploy/providers/coherenceHandler.js +7 -6
- package/dist/commands/setup/deploy/providers/flightcontrolHandler.js +2 -1
- package/dist/commands/setup/deploy/providers/netlifyHandler.js +2 -1
- package/dist/commands/setup/deploy/providers/renderHandler.js +2 -1
- package/dist/commands/setup/deploy/providers/serverlessHandler.js +2 -1
- package/dist/commands/setup/deploy/providers/universalDeployHandler.js +4 -6
- package/dist/commands/setup/deploy/providers/vercelHandler.js +2 -1
- package/dist/commands/setup/docker/docker.js +1 -1
- package/dist/commands/setup/docker/dockerHandler.js +2 -1
- package/dist/commands/setup/generator/generator.js +1 -1
- package/dist/commands/setup/generator/generatorHandler.js +1 -1
- package/dist/commands/setup/graphql/features/fragments/fragments.js +1 -1
- package/dist/commands/setup/graphql/features/fragments/fragmentsHandler.js +3 -5
- package/dist/commands/setup/graphql/features/trustedDocuments/trustedDocuments.js +1 -1
- package/dist/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.js +2 -1
- package/dist/commands/setup/i18n/i18n.js +1 -1
- package/dist/commands/setup/i18n/i18nHandler.js +1 -1
- package/dist/commands/setup/jobs/jobs.js +1 -1
- package/dist/commands/setup/jobs/jobsHandler.js +2 -1
- package/dist/commands/setup/mailer/mailer.js +1 -1
- package/dist/commands/setup/mailer/mailerHandler.js +2 -1
- package/dist/commands/setup/middleware/ogImage/ogImage.js +1 -1
- package/dist/commands/setup/middleware/ogImage/ogImageHandler.js +2 -1
- package/dist/commands/setup/monitoring/sentry/sentry.js +1 -1
- package/dist/commands/setup/monitoring/sentry/sentryHandler.js +8 -7
- package/dist/commands/setup/neon/neon.js +1 -1
- package/dist/commands/setup/neon/neonHandler.js +5 -9
- package/dist/commands/setup/package/package.js +1 -1
- package/dist/commands/setup/package/packageHandler.js +4 -4
- package/dist/commands/setup/realtime/addRealtimeToGraphql.js +1 -1
- package/dist/commands/setup/realtime/realtime.js +1 -1
- package/dist/commands/setup/realtime/realtimeHandler.js +4 -16
- package/dist/commands/setup/realtime/templates/subscriptions/countdown/countdown.ts.template +1 -1
- package/dist/commands/setup/realtime/templates/subscriptions/newMessage/newMessage.ts.template +1 -1
- package/dist/commands/setup/server-file/serverFile.js +1 -1
- package/dist/commands/setup/server-file/serverFileHandler.js +2 -1
- package/dist/commands/setup/tenancy/authCodemod.js +66 -0
- package/dist/commands/setup/tenancy/dbCodemod.js +64 -0
- package/dist/commands/setup/tenancy/graphqlCodemod.js +88 -0
- package/dist/commands/setup/tenancy/preflight.js +49 -0
- package/dist/commands/setup/tenancy/schemaPrisma.js +81 -0
- package/dist/commands/setup/tenancy/signupCodemod.js +153 -0
- package/dist/commands/setup/tenancy/templates/InvitePage.tsx.template +63 -0
- package/dist/commands/setup/tenancy/templates/OrgScope.tsx.template +40 -0
- package/dist/commands/setup/tenancy/templates/ensureDefaultOrganizations.dataMigration.ts.template +39 -0
- package/dist/commands/setup/tenancy/templates/organizations.scenarios.ts.template +59 -0
- package/dist/commands/setup/tenancy/templates/organizations.sdl.ts.template +89 -0
- package/dist/commands/setup/tenancy/templates/organizations.test.ts.template +389 -0
- package/dist/commands/setup/tenancy/templates/organizations.ts.template +394 -0
- package/dist/commands/setup/tenancy/templates/requireMembership.test.ts.template +35 -0
- package/dist/commands/setup/tenancy/templates/requireMembership.ts.template +25 -0
- package/dist/commands/setup/tenancy/tenancy.js +30 -0
- package/dist/commands/setup/tenancy/tenancyHandler.js +425 -0
- package/dist/commands/setup/ui/libraries/chakra-uiHandler.js +2 -1
- package/dist/commands/setup/ui/libraries/mantineHandler.js +2 -1
- package/dist/commands/setup/ui/libraries/tailwindcssHandler.js +2 -1
- package/dist/commands/setup/uploads/schemaPrisma.js +41 -0
- package/dist/commands/setup/uploads/serverFile.js +151 -0
- package/dist/commands/setup/uploads/templates/requireUploadToken.ts.template +15 -0
- package/dist/commands/setup/uploads/templates/srcLibUploads.ts.template +23 -24
- package/dist/commands/setup/uploads/templates/uploads.sdl.ts.template +79 -0
- package/dist/commands/setup/uploads/templates/uploads.ts.template +89 -0
- package/dist/commands/setup/uploads/templates/withDataUri.ts.template +14 -0
- package/dist/commands/setup/uploads/templates/withSignedUrl.ts.template +16 -0
- package/dist/commands/setup/uploads/uploads.js +49 -7
- package/dist/commands/setup/uploads/uploadsHandler.js +256 -69
- package/dist/commands/setup.js +2 -1
- package/dist/commands/studio.js +1 -1
- package/dist/commands/test/testHandler.js +25 -71
- package/dist/commands/test/viteVersionCheck.js +75 -0
- package/dist/commands/test.js +10 -18
- package/dist/commands/type-checkHandler.js +1 -1
- package/dist/commands/upgrade/preUpgradeScripts.js +3 -3
- package/dist/commands/upgrade/upgrade.js +1 -1
- package/dist/commands/upgrade/upgradeHandler.js +2 -1
- package/dist/index.js +5 -8
- package/dist/lib/exit.js +1 -1
- package/dist/lib/index.js +6 -25
- package/dist/lib/loadEnvFiles.js +1 -1
- package/dist/lib/plugin.js +1 -1
- package/dist/lib/test.js +1 -1
- package/dist/lib/updateCheck.js +4 -4
- package/dist/middleware/checkNodeVersion.js +4 -4
- package/package.json +18 -18
- package/dist/commands/setup/uploads/dbCodemod.js +0 -28
- package/dist/commands/setup/uploads/templates/signedUrl.ts.template +0 -21
- package/dist/commands/test/testHandlerEsm.js +0 -109
- package/dist/commands/testEsm.js +0 -41
|
@@ -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,7 +1,8 @@
|
|
|
1
1
|
import path from "path";
|
|
2
2
|
import { Listr } from "listr2";
|
|
3
|
-
import {
|
|
3
|
+
import { colors as c } from "@cedarjs/cli-helpers/colors";
|
|
4
4
|
import { addWorkspacePackages } from "@cedarjs/cli-helpers/packageManager/packages";
|
|
5
|
+
import { recordTelemetryAttributes } from "@cedarjs/cli-helpers/telemetry";
|
|
5
6
|
import extendStorybookConfiguration from "../../../../lib/configureStorybook.js";
|
|
6
7
|
import { extendJSXFile, fileIncludes } from "../../../../lib/extendFile.js";
|
|
7
8
|
import { getPaths, writeFile } from "../../../../lib/index.js";
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { Listr } from "listr2";
|
|
4
|
-
import {
|
|
4
|
+
import { colors as c } from "@cedarjs/cli-helpers/colors";
|
|
5
5
|
import { addWorkspacePackages } from "@cedarjs/cli-helpers/packageManager/packages";
|
|
6
|
+
import { recordTelemetryAttributes } from "@cedarjs/cli-helpers/telemetry";
|
|
6
7
|
import extendStorybookConfiguration from "../../../../lib/configureStorybook.js";
|
|
7
8
|
import { extendJSXFile, fileIncludes } from "../../../../lib/extendFile.js";
|
|
8
9
|
import { getPaths, writeFile } from "../../../../lib/index.js";
|
|
@@ -4,13 +4,14 @@ import { ListrEnquirerPromptAdapter } from "@listr2/prompt-adapter-enquirer";
|
|
|
4
4
|
import execa from "execa";
|
|
5
5
|
import { Listr } from "listr2";
|
|
6
6
|
import { terminalLink } from "termi-link";
|
|
7
|
-
import {
|
|
7
|
+
import { colors as c } from "@cedarjs/cli-helpers/colors";
|
|
8
8
|
import { formatCedarCommand } from "@cedarjs/cli-helpers/packageManager/display";
|
|
9
9
|
import { runBin } from "@cedarjs/cli-helpers/packageManager/exec";
|
|
10
10
|
import {
|
|
11
11
|
addRootPackages,
|
|
12
12
|
addWorkspacePackages
|
|
13
13
|
} from "@cedarjs/cli-helpers/packageManager/packages";
|
|
14
|
+
import { recordTelemetryAttributes } from "@cedarjs/cli-helpers/telemetry";
|
|
14
15
|
import { errorTelemetry } from "@cedarjs/telemetry";
|
|
15
16
|
import { getPaths, usingVSCode } from "../../../../lib/index.js";
|
|
16
17
|
const tailwindDirectives = [
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const UPLOAD_MODEL = `model Upload {
|
|
2
|
+
id String @id @default(cuid())
|
|
3
|
+
/// Name of the storage target, as configured in api/src/lib/uploads
|
|
4
|
+
target String
|
|
5
|
+
/// "pending" | "completed" | "failed"
|
|
6
|
+
status String @default("pending")
|
|
7
|
+
filename String
|
|
8
|
+
mimeType String
|
|
9
|
+
/// Bytes. BigInt because Int caps at 2 GB.
|
|
10
|
+
size BigInt
|
|
11
|
+
/// Provider-specific reference: S3 object key, filename on disk, or null
|
|
12
|
+
/// for files stored inline
|
|
13
|
+
storageKey String?
|
|
14
|
+
/// Inline bytes, only for DB targets
|
|
15
|
+
data Bytes?
|
|
16
|
+
/// The user the file belongs to, when it belongs to one
|
|
17
|
+
userId String?
|
|
18
|
+
/// Id of the upload token that created this row
|
|
19
|
+
tokenId String?
|
|
20
|
+
/// The organization the file belongs to, in multi-tenant apps
|
|
21
|
+
organizationId String?
|
|
22
|
+
createdAt DateTime @default(now())
|
|
23
|
+
updatedAt DateTime @updatedAt
|
|
24
|
+
}`;
|
|
25
|
+
function hasModel(schema, modelName) {
|
|
26
|
+
return new RegExp(`\\bmodel\\s+${modelName}\\s*\\{`).test(schema);
|
|
27
|
+
}
|
|
28
|
+
function addUploadModel(schema) {
|
|
29
|
+
if (hasModel(schema, "Upload")) {
|
|
30
|
+
return schema;
|
|
31
|
+
}
|
|
32
|
+
return `${schema.trimEnd()}
|
|
33
|
+
|
|
34
|
+
${UPLOAD_MODEL}
|
|
35
|
+
`;
|
|
36
|
+
}
|
|
37
|
+
export {
|
|
38
|
+
UPLOAD_MODEL,
|
|
39
|
+
addUploadModel,
|
|
40
|
+
hasModel
|
|
41
|
+
};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
const START_LINE = /^([ \t]*)await server\.start\(\)/m;
|
|
2
|
+
const FACTORY_IMPORT = /import\s*\{[^}]*\bcreateAuthDecoder\b[^}]*\}\s*from\s*['"](@cedarjs\/auth-[a-z0-9-]+-api)['"]/;
|
|
3
|
+
const DECODER_IMPORT = /import\s*\{[^}]*\bauthDecoder\b[^}]*\}\s*from\s*['"](@cedarjs\/auth-[a-z0-9-]+-api)['"]/;
|
|
4
|
+
function detectServerAuth(graphqlSource) {
|
|
5
|
+
const factory = FACTORY_IMPORT.exec(graphqlSource);
|
|
6
|
+
if (factory) {
|
|
7
|
+
return { decoderPackage: factory[1], usesFactory: true };
|
|
8
|
+
}
|
|
9
|
+
const decoder = DECODER_IMPORT.exec(graphqlSource);
|
|
10
|
+
if (decoder) {
|
|
11
|
+
return { decoderPackage: decoder[1], usesFactory: false };
|
|
12
|
+
}
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
function importedBindings(source) {
|
|
16
|
+
const names = /* @__PURE__ */ new Set();
|
|
17
|
+
const statements = source.matchAll(
|
|
18
|
+
/^import\s+(type\s+)?([^;]*?)\s+from\s+['"][^'"]+['"]/gm
|
|
19
|
+
);
|
|
20
|
+
for (const [, typeOnly, clause] of statements) {
|
|
21
|
+
if (typeOnly) {
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const braces = /\{([^}]*)\}/.exec(clause);
|
|
25
|
+
const defaultOrNamespace = clause.replace(/\{[^}]*\}/, "");
|
|
26
|
+
for (const part of defaultOrNamespace.split(",")) {
|
|
27
|
+
const local = part.replace(/^\s*\*\s+as\s+/, "").trim();
|
|
28
|
+
if (local) {
|
|
29
|
+
names.add(local);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
for (const specifier of braces?.[1].split(",") ?? []) {
|
|
33
|
+
const trimmed = specifier.trim();
|
|
34
|
+
if (!trimmed || trimmed.startsWith("type ")) {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const alias = / as (\w+)$/.exec(trimmed);
|
|
38
|
+
names.add(alias ? alias[1] : trimmed);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return names;
|
|
42
|
+
}
|
|
43
|
+
function hasBinding(source, name) {
|
|
44
|
+
const declared = new RegExp(
|
|
45
|
+
`^(?:export\\s+)?(?:const|let|var|function)\\s+${name}\\b`,
|
|
46
|
+
"m"
|
|
47
|
+
);
|
|
48
|
+
return importedBindings(source).has(name) || declared.test(source);
|
|
49
|
+
}
|
|
50
|
+
function uploadsServerImports(source, auth) {
|
|
51
|
+
const packageSpecs = [];
|
|
52
|
+
const srcSpecs = [];
|
|
53
|
+
if (auth) {
|
|
54
|
+
if (auth.usesFactory) {
|
|
55
|
+
if (!hasBinding(source, "authDecoder")) {
|
|
56
|
+
packageSpecs.push({
|
|
57
|
+
names: ["createAuthDecoder"],
|
|
58
|
+
from: auth.decoderPackage
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
} else {
|
|
62
|
+
packageSpecs.push({ names: ["authDecoder"], from: auth.decoderPackage });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
packageSpecs.push({
|
|
66
|
+
names: auth ? ["cedarUploadsPlugin", "createUploadAuthenticator"] : ["cedarUploadsPlugin"],
|
|
67
|
+
from: "@cedarjs/uploads"
|
|
68
|
+
});
|
|
69
|
+
if (auth) {
|
|
70
|
+
const authNames = ["getCurrentUser"];
|
|
71
|
+
if (auth.usesFactory && !hasBinding(source, "authDecoder")) {
|
|
72
|
+
authNames.unshift("cookieName");
|
|
73
|
+
}
|
|
74
|
+
srcSpecs.push({ names: authNames, from: "src/lib/auth" });
|
|
75
|
+
}
|
|
76
|
+
srcSpecs.push({ names: ["db"], from: "src/lib/db" });
|
|
77
|
+
srcSpecs.push({ names: ["targets"], from: "src/lib/uploads" });
|
|
78
|
+
const render = (specs) => specs.map((spec) => ({
|
|
79
|
+
...spec,
|
|
80
|
+
names: spec.names.filter((name) => !hasBinding(source, name))
|
|
81
|
+
})).filter((spec) => spec.names.length > 0).map((spec) => `import { ${spec.names.join(", ")} } from '${spec.from}'`);
|
|
82
|
+
const packageLines = render(packageSpecs);
|
|
83
|
+
const srcLines = render(srcSpecs);
|
|
84
|
+
if (packageLines.length > 0 && srcLines.length > 0) {
|
|
85
|
+
return [...packageLines, "", ...srcLines];
|
|
86
|
+
}
|
|
87
|
+
return [...packageLines, ...srcLines];
|
|
88
|
+
}
|
|
89
|
+
function uploadsServerRegistration(source, auth) {
|
|
90
|
+
if (!auth) {
|
|
91
|
+
return ` await server.register(cedarUploadsPlugin, {
|
|
92
|
+
tokenSecret: process.env.UPLOAD_TOKEN_SECRET,
|
|
93
|
+
targets,
|
|
94
|
+
db,
|
|
95
|
+
// Once the app has auth, bind upload tokens to the logged-in user:
|
|
96
|
+
//
|
|
97
|
+
// authenticate: createUploadAuthenticator({ authDecoder, getCurrentUser }),
|
|
98
|
+
})
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
const decoder = auth.usesFactory && !hasBinding(source, "authDecoder") ? " const authDecoder = createAuthDecoder(cookieName)\n\n" : "";
|
|
102
|
+
return `${decoder} await server.register(cedarUploadsPlugin, {
|
|
103
|
+
tokenSecret: process.env.UPLOAD_TOKEN_SECRET,
|
|
104
|
+
targets,
|
|
105
|
+
db,
|
|
106
|
+
// Binds upload tokens to the logged-in user through the same auth
|
|
107
|
+
// pipeline the GraphQL server uses
|
|
108
|
+
authenticate: createUploadAuthenticator({ authDecoder, getCurrentUser }),
|
|
109
|
+
})
|
|
110
|
+
`;
|
|
111
|
+
}
|
|
112
|
+
function hasUploadsPlugin(source) {
|
|
113
|
+
return /^[ \t]*(?:(?:await|void)\s+|(?:const|let|var)\s+\w+\s*=\s*)?[\w.]+\.register\(\s*cedarUploadsPlugin\b/m.test(
|
|
114
|
+
source
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
function addUploadsPlugin(source, { auth = null } = {}) {
|
|
118
|
+
if (hasUploadsPlugin(source)) {
|
|
119
|
+
return source;
|
|
120
|
+
}
|
|
121
|
+
const start = START_LINE.exec(source);
|
|
122
|
+
if (!start) {
|
|
123
|
+
throw new Error("CEDAR_UPLOADS_ERR_NO_START");
|
|
124
|
+
}
|
|
125
|
+
const lines = source.split("\n");
|
|
126
|
+
let lastImport = -1;
|
|
127
|
+
for (const [index, line] of lines.entries()) {
|
|
128
|
+
if (/^import\s/.test(line)) {
|
|
129
|
+
lastImport = index;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const withImports = [
|
|
133
|
+
...lines.slice(0, lastImport + 1),
|
|
134
|
+
...uploadsServerImports(source, auth),
|
|
135
|
+
...lines.slice(lastImport + 1)
|
|
136
|
+
].join("\n");
|
|
137
|
+
return withImports.replace(
|
|
138
|
+
START_LINE,
|
|
139
|
+
(line) => `${uploadsServerRegistration(source, auth)}
|
|
140
|
+
${line}`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
export {
|
|
144
|
+
addUploadsPlugin,
|
|
145
|
+
detectServerAuth,
|
|
146
|
+
hasBinding,
|
|
147
|
+
hasUploadsPlugin,
|
|
148
|
+
importedBindings,
|
|
149
|
+
uploadsServerImports,
|
|
150
|
+
uploadsServerRegistration
|
|
151
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createRequireUploadTokenDirective } from '@cedarjs/uploads'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Requires a valid upload token in the x-upload-token request header and
|
|
5
|
+
* makes its claims available to the resolver through
|
|
6
|
+
* `getUploadTokenPayload(context)`. The token must have been issued to the
|
|
7
|
+
* requesting user.
|
|
8
|
+
*/
|
|
9
|
+
const requireUploadToken = createRequireUploadTokenDirective({
|
|
10
|
+
secret: process.env.UPLOAD_TOKEN_SECRET ?? '',
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
export const schema = requireUploadToken.schema
|
|
14
|
+
|
|
15
|
+
export default requireUploadToken
|