@cedarjs/cli 6.0.0-canary.2868 → 6.0.0-canary.2870

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.
@@ -23,6 +23,20 @@ const validateName = (name) => {
23
23
  );
24
24
  }
25
25
  };
26
+ const SENSITIVE_FIELDS = [
27
+ "hashedPassword",
28
+ "salt",
29
+ "resetToken",
30
+ "resetTokenExpiresAt",
31
+ "webAuthnChallenge"
32
+ ];
33
+ const redactedModelFields = (fieldNames) => {
34
+ const sensitive = fieldNames.filter((name) => SENSITIVE_FIELDS.includes(name));
35
+ if (sensitive.length === 1 && sensitive[0] === "salt") {
36
+ return [];
37
+ }
38
+ return sensitive;
39
+ };
26
40
  const relationsForModel = (model) => {
27
41
  return model?.fields.filter((f) => f.relationName).map((field) => {
28
42
  return field.name;
@@ -60,11 +74,13 @@ const mapPrismaScalarToPagePropTsType = (scalarType) => {
60
74
  return prismaScalarToTsType[scalarType] || "unknown";
61
75
  };
62
76
  export {
77
+ SENSITIVE_FIELDS,
63
78
  forcePluralizeWord,
64
79
  intForeignKeysForModel,
65
80
  mapPrismaScalarToPagePropTsType,
66
81
  mapRouteParamTypeToTsType,
67
82
  pathName,
83
+ redactedModelFields,
68
84
  relationsForModel,
69
85
  removeGeneratorName,
70
86
  validateName
@@ -19,7 +19,6 @@ import {
19
19
  writeFile,
20
20
  getDefaultArgs,
21
21
  getPaths,
22
- writeFilesTask,
23
22
  addRoutesToRouterTask,
24
23
  addScaffoldImport,
25
24
  transformTSToJS,
@@ -31,12 +30,18 @@ import {
31
30
  } from "../../../lib/rollback.js";
32
31
  import { getSchema, verifyModelName } from "../../../lib/schemaHelpers.js";
33
32
  import {
33
+ redactedModelFields,
34
34
  relationsForModel,
35
35
  intForeignKeysForModel,
36
36
  mapPrismaScalarToPagePropTsType
37
37
  } from "../helpers.js";
38
38
  import { builder as sdlBuilder } from "../sdl/sdl.js";
39
- import { files as sdlFiles } from "../sdl/sdlHandler.js";
39
+ import {
40
+ files as sdlFiles,
41
+ printRedactedFieldsNote,
42
+ redactedSensitiveFields
43
+ } from "../sdl/sdlHandler.js";
44
+ import { writeFilesWithStubsTask } from "../sdl/stubFiles.js";
40
45
  import { builder as serviceBuilder } from "../service/service.js";
41
46
  import { files as serviceFiles } from "../service/serviceHandler.js";
42
47
  import { customOrDefaultTemplatePath } from "../yargsHandlerHelpers.js";
@@ -273,7 +278,10 @@ const modelRelatedVariables = (model) => {
273
278
  }
274
279
  };
275
280
  const relations = relationsForModel(model)?.map((relation) => relation);
276
- const columns = model.fields.filter((field) => field.kind !== "object").map((column) => {
281
+ const redactedFields = redactedModelFields(
282
+ model.fields.map((field) => field.name)
283
+ );
284
+ const columns = model.fields.filter((field) => field.kind !== "object").filter((field) => !redactedFields.includes(field.name)).map((column) => {
277
285
  let validation;
278
286
  const meta = componentMetadata[column.type];
279
287
  const validationDef = meta?.validation;
@@ -638,7 +646,7 @@ const tasks = ({
638
646
  tailwind,
639
647
  force
640
648
  });
641
- return writeFilesTask(f, { overwriteExisting: force });
649
+ return writeFilesWithStubsTask(f, { overwriteExisting: force });
642
650
  }
643
651
  },
644
652
  {
@@ -716,6 +724,7 @@ const handler = async ({
716
724
  prepareForRollback(t);
717
725
  }
718
726
  await t.run();
727
+ printRedactedFieldsNote(await redactedSensitiveFields([name]));
719
728
  } catch (e) {
720
729
  const message = e instanceof Error ? e.message : String(e);
721
730
  const exitCode = e instanceof Error && "exitCode" in e ? e.exitCode ?? 1 : 1;
@@ -7,7 +7,7 @@ import { generate as generateTypes } from "@cedarjs/internal/dist/generate/gener
7
7
  import { getConfig } from "@cedarjs/project-config";
8
8
  import { errorTelemetry } from "@cedarjs/telemetry";
9
9
  import { pluralize } from "@cedarjs/utils/cedarPluralize";
10
- import { transformTSToJS, writeFilesTask } from "../../../lib/index.js";
10
+ import { transformTSToJS } from "../../../lib/index.js";
11
11
  import {
12
12
  prepareForRollback,
13
13
  addFunctionToRollback
@@ -17,9 +17,14 @@ import {
17
17
  getEnum,
18
18
  verifyModelName
19
19
  } from "../../../lib/schemaHelpers.js";
20
- import { relationsForModel } from "../helpers.js";
20
+ import { redactedModelFields, relationsForModel } from "../helpers.js";
21
21
  import { files as serviceFiles } from "../service/serviceHandler.js";
22
22
  import { templateForFile } from "../yargsHandlerHelpers.js";
23
+ import {
24
+ addStubHeader,
25
+ missingRelatedModels,
26
+ writeFilesWithStubsTask
27
+ } from "./stubFiles.js";
23
28
  const DEFAULT_IGNORE_FIELDS_FOR_INPUT = ["createdAt", "updatedAt"];
24
29
  const missingIdConsoleMessage = () => {
25
30
  const line1 = ansis.bold.yellow("WARNING") + ": Cannot generate CRUD SDL without an `@id` database column.";
@@ -63,16 +68,23 @@ const modelFieldToSDL = ({
63
68
  return fieldContent;
64
69
  }
65
70
  };
71
+ const modelRedactedFields = (model) => {
72
+ return redactedModelFields(model.fields.map((field) => field.name));
73
+ };
66
74
  const querySDL = (model, docs = false) => {
67
- return model.fields.map((field) => modelFieldToSDL({ field, docs }));
75
+ const redactedFields = modelRedactedFields(model);
76
+ return model.fields.filter((field) => !redactedFields.includes(field.name)).map((field) => modelFieldToSDL({ field, docs }));
68
77
  };
69
78
  const inputSDL = (model, required, docs = false) => {
70
- const ignoredFields = DEFAULT_IGNORE_FIELDS_FOR_INPUT;
79
+ const ignoredFields = [
80
+ ...DEFAULT_IGNORE_FIELDS_FOR_INPUT,
81
+ ...modelRedactedFields(model)
82
+ ];
83
+ const idField = model.fields.find((field) => field.isId);
84
+ if (idField?.default !== void 0) {
85
+ ignoredFields.push(idField.name);
86
+ }
71
87
  return model.fields.filter((field) => {
72
- const idField = model.fields.find((field2) => field2.isId);
73
- if (idField?.default) {
74
- ignoredFields.push(idField.name);
75
- }
76
88
  return !ignoredFields.includes(field.name) && field.kind !== "object";
77
89
  }).map((field) => modelFieldToSDL({ field, required, docs }));
78
90
  };
@@ -174,6 +186,55 @@ const files = async ({
174
186
  })
175
187
  };
176
188
  };
189
+ const stubFiles = async (models, generatedFor, { docs = false, typescript }) => {
190
+ const generatedFiles = {};
191
+ for (const stubModel of models) {
192
+ const stubModelFiles = await files({
193
+ name: stubModel,
194
+ crud: false,
195
+ docs,
196
+ tests: false,
197
+ typescript
198
+ });
199
+ for (const [stubPath, stubContent] of Object.entries(stubModelFiles)) {
200
+ generatedFiles[stubPath] = addStubHeader({
201
+ content: stubContent,
202
+ stubModel,
203
+ generatedFor
204
+ });
205
+ }
206
+ }
207
+ return generatedFiles;
208
+ };
209
+ const redactedSensitiveFields = async (modelNames) => {
210
+ const redacted = [];
211
+ for (const modelName of modelNames) {
212
+ const model = await getSchema(modelName);
213
+ if (!model || !("fields" in model)) {
214
+ continue;
215
+ }
216
+ for (const fieldName of modelRedactedFields(model)) {
217
+ redacted.push(`${model.name}.${fieldName}`);
218
+ }
219
+ }
220
+ return redacted;
221
+ };
222
+ const printRedactedFieldsNote = (redactedFields) => {
223
+ if (redactedFields.length === 0) {
224
+ return;
225
+ }
226
+ console.log();
227
+ console.log(
228
+ c.warning(
229
+ `The following fields were excluded from the generated SDL because they may contain sensitive data: ${redactedFields.join(", ")}`
230
+ )
231
+ );
232
+ console.log(
233
+ c.warning(
234
+ "If you want to expose any of them through your GraphQL API you can add them to the SDL file manually."
235
+ )
236
+ );
237
+ };
177
238
  const handler = async ({
178
239
  model,
179
240
  crud,
@@ -197,13 +258,21 @@ const handler = async ({
197
258
  });
198
259
  try {
199
260
  const { name } = await verifyModelName({ name: model });
261
+ const missingModels = await missingRelatedModels(name);
262
+ const redactedFields = await redactedSensitiveFields([
263
+ name,
264
+ ...missingModels
265
+ ]);
200
266
  const tasks = new Listr(
201
267
  [
202
268
  {
203
269
  title: "Generating SDL files...",
204
270
  task: async () => {
205
- const f = await files({ name, tests, crud, typescript, docs });
206
- return writeFilesTask(f, { overwriteExisting: force });
271
+ const f = {
272
+ ...await files({ name, tests, crud, typescript, docs }),
273
+ ...await stubFiles(missingModels, name, { typescript, docs })
274
+ };
275
+ return writeFilesWithStubsTask(f, { overwriteExisting: force });
207
276
  }
208
277
  },
209
278
  {
@@ -230,6 +299,24 @@ const handler = async ({
230
299
  prepareForRollback(tasks);
231
300
  }
232
301
  await tasks.run();
302
+ if (missingModels.length > 0) {
303
+ console.log();
304
+ console.log(
305
+ c.info(
306
+ `${name} has relations to models that don't have SDL files of their own yet: ${missingModels.join(", ")}`
307
+ )
308
+ );
309
+ console.log(
310
+ c.info(
311
+ "Read-only SDL stubs were generated for them, since GraphQL type generation fails otherwise."
312
+ )
313
+ );
314
+ console.log(c.info("To replace a stub with a full SDL and service, run"));
315
+ for (const stubModel of missingModels) {
316
+ console.log(c.info(` yarn cedar generate sdl ${stubModel}`));
317
+ }
318
+ }
319
+ printRedactedFieldsNote(redactedFields);
233
320
  } catch (e) {
234
321
  const message = e instanceof Error ? e.message : String(e);
235
322
  const exitCode = e instanceof Error && "exitCode" in e && typeof e.exitCode === "number" ? e.exitCode : 1;
@@ -240,5 +327,8 @@ const handler = async ({
240
327
  };
241
328
  export {
242
329
  files,
243
- handler
330
+ handler,
331
+ printRedactedFieldsNote,
332
+ redactedSensitiveFields,
333
+ stubFiles
244
334
  };
@@ -0,0 +1,132 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { Listr } from "listr2";
5
+ import { getPaths } from "@cedarjs/project-config";
6
+ import { writeFile } from "../../../lib/index.js";
7
+ import { getSchema } from "../../../lib/schemaHelpers.js";
8
+ const STUB_HASH_MARKER = "@cedar-generator-stub-hash";
9
+ const STUB_HASH_MARKER_REGEX = new RegExp(
10
+ `^// ${STUB_HASH_MARKER} ([0-9a-f]+)$`,
11
+ "m"
12
+ );
13
+ function stubHash(contents) {
14
+ return crypto.createHash("sha256").update(contents).digest("hex").slice(0, 16);
15
+ }
16
+ function addStubHeader({
17
+ content,
18
+ stubModel,
19
+ generatedFor
20
+ }) {
21
+ const body = "\n\n" + content;
22
+ const marker = `// ${STUB_HASH_MARKER} PLACEHOLDER`;
23
+ const header = [
24
+ `// Generated as a read-only stub by \`cedar generate sdl ${generatedFor}\`,`,
25
+ `// because ${generatedFor} has a relation to ${stubModel}, which had no SDL yet.`,
26
+ `// Run \`cedar generate sdl ${stubModel}\` to replace this stub with the real thing.`,
27
+ `// If you edit this file, the hash below will stop matching and you'll`,
28
+ `// need to pass \`--force\` to overwrite it.`,
29
+ marker
30
+ ].join("\n");
31
+ const contentToHash = header + body;
32
+ const hash = stubHash(contentToHash);
33
+ const finalMarker = `// ${STUB_HASH_MARKER} ${hash}`;
34
+ return (header + body).replace(marker, finalMarker);
35
+ }
36
+ function isPristineStub(contents) {
37
+ const match = STUB_HASH_MARKER_REGEX.exec(contents);
38
+ if (!match) {
39
+ return false;
40
+ }
41
+ const contentToHash = contents.replace(
42
+ match[0],
43
+ `// ${STUB_HASH_MARKER} PLACEHOLDER`
44
+ );
45
+ return stubHash(contentToHash) === match[1];
46
+ }
47
+ function readExistingSdlFiles() {
48
+ const graphqlDir = getPaths().api.graphql;
49
+ if (!fs.existsSync(graphqlDir)) {
50
+ return [];
51
+ }
52
+ const contents = [];
53
+ const dirsToWalk = [graphqlDir];
54
+ while (dirsToWalk.length > 0) {
55
+ const dir = dirsToWalk.shift();
56
+ if (!dir) {
57
+ break;
58
+ }
59
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
60
+ const entryPath = path.join(dir, entry.name);
61
+ if (entry.isDirectory()) {
62
+ dirsToWalk.push(entryPath);
63
+ } else if (/\.sdl\.(js|ts)$/.test(entry.name)) {
64
+ contents.push(fs.readFileSync(entryPath, "utf-8"));
65
+ }
66
+ }
67
+ }
68
+ return contents;
69
+ }
70
+ async function missingRelatedModels(modelName) {
71
+ const existingSdls = readExistingSdlFiles();
72
+ const isDefined = (typeName) => existingSdls.some(
73
+ (sdl) => new RegExp(`\\btype\\s+${typeName}\\b`).test(sdl)
74
+ );
75
+ const seen = /* @__PURE__ */ new Set([modelName]);
76
+ const missing = [];
77
+ const queue = [modelName];
78
+ while (queue.length > 0) {
79
+ const current = queue.shift();
80
+ if (!current) {
81
+ break;
82
+ }
83
+ const model = await getSchema(current);
84
+ if (!model || !("fields" in model)) {
85
+ continue;
86
+ }
87
+ for (const field of model.fields) {
88
+ if (!field.relationName || seen.has(field.type)) {
89
+ continue;
90
+ }
91
+ seen.add(field.type);
92
+ queue.push(field.type);
93
+ if (!isDefined(field.type)) {
94
+ missing.push(field.type);
95
+ }
96
+ }
97
+ }
98
+ return missing;
99
+ }
100
+ function writeFilesWithStubsTask(files, { overwriteExisting = false } = {}) {
101
+ const { base } = getPaths();
102
+ return new Listr(
103
+ Object.entries(files).map(([file, contents]) => ({
104
+ title: `...waiting to write file \`./${path.relative(base, file)}\`...`,
105
+ task: (_ctx, task) => {
106
+ let canOverwrite = overwriteExisting;
107
+ if (!canOverwrite && fs.existsSync(file)) {
108
+ const existingContents = fs.readFileSync(file, "utf-8");
109
+ if (isPristineStub(existingContents)) {
110
+ canOverwrite = true;
111
+ } else if (STUB_HASH_MARKER_REGEX.test(existingContents)) {
112
+ throw new Error(
113
+ `${file} started out as a generated stub, but has since been edited. Use \`--force\` to overwrite it.`
114
+ );
115
+ }
116
+ }
117
+ return writeFile(
118
+ file,
119
+ contents,
120
+ { overwriteExisting: canOverwrite },
121
+ task
122
+ );
123
+ }
124
+ }))
125
+ );
126
+ }
127
+ export {
128
+ addStubHeader,
129
+ isPristineStub,
130
+ missingRelatedModels,
131
+ writeFilesWithStubsTask
132
+ };
@@ -3,7 +3,7 @@ import camelcase from "camelcase";
3
3
  import { pluralize, singularize } from "@cedarjs/utils/cedarPluralize";
4
4
  import { transformTSToJS } from "../../../lib/index.js";
5
5
  import { getSchema, verifyModelName } from "../../../lib/schemaHelpers.js";
6
- import { relationsForModel } from "../helpers.js";
6
+ import { redactedModelFields, relationsForModel } from "../helpers.js";
7
7
  import { createHandler, templateForFile } from "../yargsHandlerHelpers.js";
8
8
  function isServiceModel(schema) {
9
9
  return typeof schema === "object" && schema !== null && "fields" in schema && "name" in schema;
@@ -32,7 +32,10 @@ const parseSchema = async (model) => {
32
32
  return field.isRequired && !field.hasDefaultValue && // don't include fields that the database will default
33
33
  !field.relationName;
34
34
  });
35
- return { scalarFields, relations, foreignKeys };
35
+ const redactedFields = redactedModelFields(
36
+ schema.fields.map((field) => field.name)
37
+ );
38
+ return { scalarFields, relations, foreignKeys, redactedFields };
36
39
  };
37
40
  function scenarioFieldValue(field) {
38
41
  const randFloat = Math.random() * 1e7;
@@ -145,9 +148,14 @@ const fieldTypes = async (model) => {
145
148
  );
146
149
  };
147
150
  const fieldsToInput = async (model) => {
148
- const { scalarFields, foreignKeys } = await parseSchema(model);
151
+ const { scalarFields, foreignKeys, redactedFields } = await parseSchema(model);
149
152
  const modelName = camelcase(singularize(model));
150
153
  const inputObj = {};
154
+ if (scalarFields.some(
155
+ (field) => redactedFields.includes(field.name)
156
+ )) {
157
+ return false;
158
+ }
151
159
  scalarFields.forEach((field) => {
152
160
  if (foreignKeys.includes(field.name)) {
153
161
  inputObj[field.name] = `scenario.${modelName}.two.${field.name}`;
@@ -162,14 +170,17 @@ const fieldsToInput = async (model) => {
162
170
  }
163
171
  };
164
172
  const fieldsToUpdate = async (model) => {
165
- const { scalarFields, relations, foreignKeys } = await parseSchema(model);
173
+ const { scalarFields, relations, foreignKeys, redactedFields } = await parseSchema(model);
166
174
  const modelName = camelcase(singularize(model));
167
175
  let field, newValue, fieldName;
168
- field = scalarFields.find(
176
+ const updatableFields = scalarFields.filter(
177
+ (scalar) => !redactedFields.includes(scalar.name)
178
+ );
179
+ field = updatableFields.find(
169
180
  (scalar) => !foreignKeys.includes(scalar.name)
170
181
  );
171
182
  if (!field) {
172
- field = scalarFields[0];
183
+ field = updatableFields[0];
173
184
  }
174
185
  if (!field) {
175
186
  return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cedarjs/cli",
3
- "version": "6.0.0-canary.2868",
3
+ "version": "6.0.0-canary.2870",
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.7",
38
38
  "@babel/types": "7.29.7",
39
- "@cedarjs/api-server": "6.0.0-canary.2868",
40
- "@cedarjs/babel-config": "6.0.0-canary.2868",
41
- "@cedarjs/cli-helpers": "6.0.0-canary.2868",
42
- "@cedarjs/internal": "6.0.0-canary.2868",
43
- "@cedarjs/prerender": "6.0.0-canary.2868",
44
- "@cedarjs/project-config": "6.0.0-canary.2868",
45
- "@cedarjs/structure": "6.0.0-canary.2868",
46
- "@cedarjs/telemetry": "6.0.0-canary.2868",
47
- "@cedarjs/utils": "6.0.0-canary.2868",
48
- "@cedarjs/vite": "6.0.0-canary.2868",
49
- "@cedarjs/web-server": "6.0.0-canary.2868",
39
+ "@cedarjs/api-server": "6.0.0-canary.2870",
40
+ "@cedarjs/babel-config": "6.0.0-canary.2870",
41
+ "@cedarjs/cli-helpers": "6.0.0-canary.2870",
42
+ "@cedarjs/internal": "6.0.0-canary.2870",
43
+ "@cedarjs/prerender": "6.0.0-canary.2870",
44
+ "@cedarjs/project-config": "6.0.0-canary.2870",
45
+ "@cedarjs/structure": "6.0.0-canary.2870",
46
+ "@cedarjs/telemetry": "6.0.0-canary.2870",
47
+ "@cedarjs/utils": "6.0.0-canary.2870",
48
+ "@cedarjs/vite": "6.0.0-canary.2870",
49
+ "@cedarjs/web-server": "6.0.0-canary.2870",
50
50
  "@listr2/prompt-adapter-enquirer": "4.3.0",
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": "6.0.0-canary.2868",
97
+ "@cedarjs/framework-tools": "6.0.0-canary.2870",
98
98
  "@prisma/dmmf": "7.8.0",
99
99
  "@types/archiver": "^7.0.0",
100
100
  "memfs": "4.64.0",