joist-codegen 2.4.0-next.2 → 2.4.0-next.21

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.
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":["fs"],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync, promises as fs, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nimport { createFromBuffer } from \"@dprint/formatter\";\nimport { getPath } from \"@dprint/json\";\nimport { groupBy } from \"joist-utils\";\nimport { type ParseError, parse } from \"jsonc-parser\";\nimport { z } from \"zod\";\n\nimport { getLatestCodemodVersion } from \"./codemods/index.ts\";\nimport { type DbMetadata, type Entity, type EntityDbMetadata } from \"./EntityDbMetadata.ts\";\nimport { getStiEntities } from \"./inheritance.ts\";\nimport { logger } from \"./logger.ts\";\nimport { fail, sortKeys, trueIfResolved } from \"./utils.ts\";\n\nconst jsonFormatter = createFromBuffer(readFileSync(getPath()));\n\nconst fieldConfig = z\n .object({\n // For getters & ReactiveFields\n derived: z.optional(z.union([z.literal(\"sync\"), z.literal(\"async\")])),\n protected: z.optional(z.boolean()),\n ignore: z.optional(z.boolean()),\n superstruct: z.optional(z.string()),\n zodSchema: z.optional(z.string()),\n type: z.optional(z.string()),\n serde: z.optional(z.string()),\n stiDiscriminator: z.optional(z.record(z.string(), z.string())),\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n // Allow subclasses to mark fields as required\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n // Exclude a (large jsonb/text) column from the default SELECT and expose it as a lazy-loaded LazyField\n lazy: z.optional(z.boolean()),\n })\n .strict();\n\nexport type FieldConfig = z.infer<typeof fieldConfig>;\n\nconst relationConfig = z\n .object({\n // For ReactiveReferences\n derived: z.optional(z.literal(\"async\")),\n polymorphic: z.optional(z.union([z.literal(\"notNull\"), z.literal(true)])),\n large: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n /**\n * Controls whether this collection's `.get`/`.load` hide soft-deleted entities.\n *\n * Defaults to `\"exclude\"` (soft-deleted entities are hidden); set to `\"include\"` to have\n * this specific o2m/m2m always return soft-deleted entities from `.get`/`.load`.\n */\n softDeletes: z.optional(z.union([z.literal(\"include\"), z.literal(\"exclude\")])),\n // Allow pushing m2o/m2m/o2o relations in a base type (Task) down to a subtype (TaskOld)\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n /**\n * Allow specializing a base type relation (SmallPublisher.group: SmallPublisherGroup).\n *\n * Self-referential FKs also support `subType: \"self\"` that means each subtype will point\n * at its own subtype.\n */\n subType: z.optional(z.string()),\n /** Allow skipping self-referential fields getting a `...Recursive` relation. */\n skipRecursiveRelations: z.optional(z.boolean()),\n // Allow marking m2o FKs as required on subclasses\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n })\n .strict();\n\nexport type RelationConfig = z.infer<typeof relationConfig>;\n\nconst uniqueByConfig = z\n .union([z.string(), z.array(z.string()), z.array(z.array(z.string()))])\n .transform(normalizeUniqueByConfig);\n\nconst entityConfig = z\n .object({\n tag: z.string(),\n tableName: z.optional(z.string()),\n fields: z.optional(z.record(z.string(), fieldConfig)),\n relations: z.optional(z.record(z.string(), relationConfig)),\n /** Whether this entity should be abstract, e.g. for inheritance a subtype must be instantiated instead of this type. */\n abstract: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n uniqueBy: z.optional(uniqueByConfig),\n })\n .strict();\n\nexport type EntityConfig = z.infer<typeof entityConfig>;\n\nconst timestampConfig = z\n .object({\n /** The names to check for this timestamp, i.e. `created_at` `created`, etc. */\n names: z.array(z.string()),\n /** Whether this timestamp column is required to consider a table an entity, defaults to `false`. */\n required: z.optional(z.boolean()),\n })\n .strict();\n\nexport type TimestampConfig = z.infer<typeof timestampConfig>;\n\nexport const config = z\n .object({\n /** The _build-time_ database URL for reading database metadata. */\n databaseUrl: z.optional(z.string()),\n /** Your application's request-level `Context` type. */\n contextType: z.optional(z.string()),\n /** Your application's database client's `Transaction` type. */\n transactionType: z.optional(z.string()),\n /**\n * Allows the user to specify the `updated_at` / `created_at` column names to look up, and if they're optional.\n *\n * We default to looking for `updated_at`, `updatedAt`, `created_at`, `createdAt`, and optional to true,\n * e.g. tables are not required to have both timestamp columns to be considered entities.\n *\n * These defaults are the most lenient, to facilitate running Joist against an existing schema and\n * seeing all of your entities, regardless of your previous conventions.\n */\n timestampColumns: z.optional(\n z.object({\n createdAt: z.optional(timestampConfig),\n updatedAt: z.optional(timestampConfig),\n deletedAt: z.optional(timestampConfig),\n }),\n ),\n /**\n * Allows the user to have codegen output `Temporal` types instead of the base JS `Date`\n *\n * Additionally, allows for specifying the default time zone for `Temporal` types when converting dates to/from\n * the database.\n */\n temporal: z.optional(z.union([z.boolean(), z.object({ timeZone: z.string() })])),\n /**\n * By default, we create a `flush_database` function for fast testing.\n *\n * However, if you don't want to use this, or you have your own bespoke function like we do\n * that is more application-aware, then you can disable Joist's out-of-the-box one.\n *\n * If you have more than one test database, you can set `createFlushFunction` to the array\n * of test database names, i.e. `mydb_test_1`, `mydb_test_2`, etc.\n */\n createFlushFunction: z.optional(z.union([z.boolean(), z.array(z.string())])),\n entitiesDirectory: z.string().default(\"./src/entities\"),\n codegenPlugins: z.optional(z.array(z.string())),\n entities: z.record(z.string(), entityConfig).default({}),\n ignoredTables: z.optional(z.array(z.string())),\n /** The type of entity `id` fields; defaults to `tagged-string`. */\n idType: z.optional(z.union([z.literal(\"tagged-string\"), z.literal(\"untagged-string\"), z.literal(\"number\")])),\n /** The separator between entity tags and ids; defaults to `:`, and `\"\"` disables the separator. */\n tagDelimiter: z.optional(z.string()),\n /** How we should support non-deferred foreign keys. */\n nonDeferredForeignKeys: z.optional(z.union([z.literal(\"error\"), z.literal(\"warn\"), z.literal(\"ignore\")])),\n /** Enables esm output. */\n esm: z.optional(z.boolean()),\n /** Controls the style of GraphQL pagination scaffolding. */\n paginationStyle: z.optional(z.union([z.literal(\"cursor\"), z.literal(\"limit\")])).default(\"cursor\"),\n /** Enables documentation syncing between .md files and JSDocs. */\n docs: z.optional(z.boolean()),\n /** Installs Joist's bundled Agent Skills into `.claude/skills` and `.agents/skills`; on by default, set `false` to disable. */\n skills: z.optional(z.boolean()),\n /** Output a metadata-docs.ts file with entity/field documentation available at runtime. */\n outputDocs: z.optional(z.boolean()),\n /** Auto-set by probing the project's `tsconfig.json` file. */\n allowImportingTsExtensions: z.optional(z.boolean()),\n /** The latest Joist codemod counter that has been applied to this project. */\n codemodVersion: z.number().int().min(0).default(0),\n\n /** A list of postgres schemas to use for finding tables */\n schemas: z.optional(z.array(z.string())),\n })\n .strict();\n\nexport type Config = z.infer<typeof config> & {\n // We don't persist this, and instead just use it as a cache\n __tableToEntityName?: Record<string, string>;\n};\n\nexport const ormMaintainedFields = [\"createdAt\", \"updatedAt\"];\n\n/** Ensure the user doesn't have any typos in their config. */\nexport function warnInvalidConfigEntries(config: Config, db: DbMetadata): void {\n const entitiesByName = groupBy(db.entities, (e) => e.name);\n for (const [entityName, entityConfig] of Object.entries(config.entities)) {\n const entities = entitiesByName[entityName];\n if (!entities) {\n logger.warn(`Found config for non-existent entity ${entityName}`);\n continue;\n }\n // We don't have keyBy...\n const [entity] = entities;\n\n // Check fields\n const fields = [...entity.primitives, ...entity.enums];\n for (const [name, config] of Object.entries(entityConfig.fields || {})) {\n if (config.ignore) continue;\n let field = fields.find((f) => f.fieldName === name);\n // STI types might be in the base type\n if (!field && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n field = stiEntities?.flatMap((st) => [...st.primitives, ...st.enums]).find((f) => f.fieldName === name);\n }\n if (!field) logger.warn(`Found config for non-existent field ${entityName}.${name}`);\n }\n\n // Check relations\n const relations = [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.manyToManyEnums,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ];\n for (const [name, _] of Object.entries(entityConfig.relations || {})) {\n let relation = relations.find((r) => r.fieldName === name);\n // STI types might be in the subtypes\n if (!relation && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n relation = stiEntities\n ?.flatMap((entity) => [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ])\n ?.find((f) => f.fieldName === name);\n }\n // CTI subtype specializations (i.e. SmallPublisher.group: SmallPublisherGroup) need to look in the base type\n if (!relation && entity.baseType) {\n const baseType = entity.baseType;\n relation = [\n ...baseType.manyToOnes,\n ...baseType.oneToManys,\n ...baseType.manyToManys,\n ...baseType.oneToOnes,\n ...baseType.largeOneToManys,\n ...baseType.largeManyToManys,\n ...baseType.polymorphics,\n ].find((f) => f.fieldName === name);\n }\n\n if (!relation) logger.warn(`Found config for non-existent relation ${entityName}.${name}`);\n }\n\n const uniqueFields = [\n ...entity.primitives,\n ...entity.enums,\n ...entity.pgEnums,\n ...entity.manyToOnes,\n ...entity.polymorphics,\n ];\n for (const uniqueBy of entityConfig.uniqueBy || []) {\n for (const name of uniqueBy) {\n const field = uniqueFields.find((f) => f.fieldName === name);\n if (!field) {\n logger.warn(`Found uniqueBy for non-existent or non-queryable field ${entityName}.${name}`);\n } else if (field.kind === \"primitive\" && (field.derived || field.isArray || field.customSerde)) {\n logger.warn(`Found uniqueBy for unsupported primitive field ${entityName}.${name}`);\n } else if (field.kind === \"enum\" && (field.derived || field.isArray)) {\n logger.warn(`Found uniqueBy for unsupported enum field ${entityName}.${name}`);\n }\n }\n }\n }\n}\n\nexport function isGetterField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"sync\";\n}\n\nexport function isReactiveField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"async\";\n}\n\nexport function isReactiveReference(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\n/** Returns true if this m2m relation is configured as a ReactiveManyToMany (derived: async). */\nexport function isReactiveManyToMany(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\nexport function isProtected(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.protected === true;\n}\n\n/** Whether a column should be excluded from the default SELECT and exposed as a lazy-loaded `LazyField`. */\nexport function isLazyField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.lazy === true;\n}\n\nexport function serdeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.serde;\n}\n\nexport function superstructConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.superstruct;\n}\n\nexport function zodSchemaConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.zodSchema;\n}\n\nexport function fieldTypeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.type;\n}\n\nexport function isLargeCollection(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.large === true;\n}\n\n/** Whether a collection should include (or exclude) soft-deleted entities from `.get`/`.load`. */\nexport function softDeletesConfig(\n config: Config,\n entity: Entity,\n fieldName: string,\n): \"include\" | \"exclude\" | undefined {\n return config.entities[entity.name]?.relations?.[fieldName]?.softDeletes;\n}\n\nexport function isFieldIgnored(\n config: Config,\n entity: Entity,\n fieldName: string,\n notNull: boolean = false,\n hasDefault: boolean = false,\n): boolean {\n const ignore = config.entities[entity.name]?.fields?.[fieldName]?.ignore === true;\n if (ignore && notNull && !hasDefault) {\n fail(\n `notNull field ${entity.name}.${fieldName} cannot be ignored. Alter the column to be optional or have a default value prior to ignoring it.`,\n );\n }\n return ignore;\n}\n\nexport function isFieldHasDefault(config: Config, entity: Entity, fieldName: string): boolean {\n const entityConfig = config.entities[entity.name] ?? {};\n const fieldConfig = entityConfig.fields?.[fieldName] ?? entityConfig.relations?.[fieldName] ?? {};\n return fieldConfig.hasDefault === true;\n}\n\nconst configPath = \"./joist-config.json\";\n\nexport async function loadConfig(): Promise<Config> {\n const exists = await trueIfResolved(fs.access(configPath));\n if (exists) {\n const content = await fs.readFile(configPath);\n const result = config.safeParse(stripLegacyConfigKeys(JSON.parse(content.toString())));\n if (!result.success) {\n throw new Error(\n `Invalid joist-config.json: ${result.error.issues\n .map((ze) => `${ze.path.map(String).join(\"/\")} ${ze.message}`)\n .join(\"\\n\")}`,\n );\n }\n result.data.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return result.data;\n }\n // Brand-new projects should not be prompted to run historical codemods.\n const initial = config.parse({ codemodVersion: getLatestCodemodVersion() });\n initial.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return initial;\n}\n\n/**\n * Writes the potentially-updated config entry back to `joist-config.json`.\n *\n * We format the output with prettier so it should both a) look nice and b) be deterministic,\n * such that no changes to the config show up as noops to the scm.\n */\nexport async function writeConfig(config: Config): Promise<void> {\n const sorted: Partial<Config> = sortKeys(config);\n delete sorted.__tableToEntityName;\n delete sorted.allowImportingTsExtensions;\n if (sorted.paginationStyle === \"cursor\") {\n delete sorted.paginationStyle;\n }\n const input = JSON.stringify(sorted);\n const content = jsonFormatter.formatText({ filePath: \"test.json\", fileText: input });\n await fs.writeFile(configPath, content);\n}\n\nexport function stripStiPlaceholders(config: Config, entities: EntityDbMetadata[]): void {\n // Defacto (with today's setup) the config of STI entities lives on the base entity,\n // so don't write confusing subtype-specific entries into the config file.\n // ...hopefully we don't have any code accidentally looking for the STI config...\n for (const entity of entities) {\n if (entity.inheritanceType === \"sti\" && entity.stiDiscriminatorValue) {\n delete config.entities[entity.name];\n }\n }\n}\n\n/** Applies defaults to the timestamp config. */\nexport function getTimestampConfig(config: Config): {\n updatedAtConf: Required<TimestampConfig>;\n createdAtConf: Required<TimestampConfig>;\n deletedAtConf: Required<TimestampConfig>;\n} {\n return {\n createdAtConf: {\n names: [\"created_at\", \"createdAt\"],\n required: false,\n ...config?.timestampColumns?.createdAt,\n },\n updatedAtConf: {\n names: [\"updated_at\", \"updatedAt\"],\n required: false,\n ...config?.timestampColumns?.updatedAt,\n },\n deletedAtConf: {\n names: [\"deleted_at\", \"deletedAt\"],\n required: false,\n ...config?.timestampColumns?.deletedAt,\n },\n };\n}\n\nfunction projectIsUsingEsmWithImports(): boolean {\n // Attempt to find the project's tsconfig.json in the current directory or up the directory hierarchy\n const configPath = findTsConfigFile(process.cwd());\n if (!configPath) {\n return false;\n }\n try {\n // Use jsonc-parser to parse the tsconfig.json file (not the old tsc readConfigFile which was\n // dropped in TypeScript 7), allowing for comments and trailing commas.\n const errors: ParseError[] = [];\n const parsed: unknown = parse(readFileSync(configPath, \"utf8\"), errors, { allowTrailingComma: true });\n if (errors.length > 0 || typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n const compilerOptions = (parsed as Record<string, unknown>).compilerOptions;\n return (\n typeof compilerOptions === \"object\" &&\n compilerOptions !== null &&\n !Array.isArray(compilerOptions) &&\n (compilerOptions as Record<string, unknown>).allowImportingTsExtensions === true\n );\n } catch {\n return false;\n }\n}\n\n/** Normalizes `uniqueBy` config sugar into runtime identity candidates. */\nfunction normalizeUniqueByConfig(uniqueBy: string | string[] | string[][]): string[][] {\n if (typeof uniqueBy === \"string\") return [[uniqueBy]];\n if (uniqueBy.every((field) => typeof field === \"string\")) return [uniqueBy];\n return uniqueBy;\n}\n\nfunction stripLegacyConfigKeys(raw: unknown): unknown {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return raw;\n }\n // Accept old configs so the deprecated key disappears on the next write.\n const parsed = { ...(raw as Record<string, unknown>) };\n delete parsed.version;\n return parsed;\n}\n\n/** Finds the nearest `tsconfig.json` in `directory` or one of its ancestors. */\nfunction findTsConfigFile(directory: string): string | undefined {\n while (true) {\n const fileName = join(directory, \"tsconfig.json\");\n if (existsSync(fileName)) return fileName;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,gBAAgB,iBAAiB,aAAa,QAAQ,CAAC,CAAC;AAE9D,MAAM,cAAc,EACjB,OAAO;CAEN,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,QAAQ,MAAM,GAAG,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC;CACpE,WAAW,EAAE,SAAS,EAAE,QAAQ,CAAC;CACjC,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC;CAC9B,aAAa,EAAE,SAAS,EAAE,OAAO,CAAC;CAClC,WAAW,EAAE,SAAS,EAAE,OAAO,CAAC;CAChC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC;CAC3B,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;CAC5B,kBAAkB,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC;CAC7D,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;CAE9D,SAAS,EAAE,SAAS,EAAE,QAAQ,CAAC;CAE/B,YAAY,EAAE,SAAS,EAAE,QAAQ,CAAC;CAElC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC;AAC9B,CAAC,CAAC,CACD,OAAO;AAIV,MAAM,iBAAiB,EACpB,OAAO;CAEN,SAAS,EAAE,SAAS,EAAE,QAAQ,OAAO,CAAC;CACtC,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC,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Y,WAAW,QAAQ,MAAM,QAAQ,MAAM,GAAG,OAAO;EACxG,MAAM,kBAAmB,OAAmC;EAC5D,OACE,OAAO,oBAAoB,YAC3B,oBAAoB,QACpB,CAAC,MAAM,QAAQ,eAAe,KAC7B,gBAA4C,+BAA+B;CAEhF,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAS,wBAAwB,UAAsD;CACrF,IAAI,OAAO,aAAa,UAAU,OAAO,CAAC,CAAC,QAAQ,CAAC;CACpD,IAAI,SAAS,OAAO,UAAU,OAAO,UAAU,QAAQ,GAAG,OAAO,CAAC,QAAQ;CAC1E,OAAO;AACT;AAEA,SAAS,sBAAsB,KAAuB;CACpD,IAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GACtD,OAAO;CAGT,MAAM,SAAS,EAAE,GAAI,IAAgC;CACrD,OAAO,OAAO;CACd,OAAO;AACT;;AAGA,SAAS,iBAAiB,WAAuC;CAC/D,OAAO,MAAM;EACX,MAAM,WAAW,KAAK,WAAW,eAAe;EAChD,IAAI,WAAW,QAAQ,GAAG,OAAO;EACjC,MAAM,SAAS,QAAQ,SAAS;EAChC,IAAI,WAAW,WAAW,OAAO,KAAA;EACjC,YAAY;CACd;AACF"}
1
+ {"version":3,"file":"config.js","names":["fs"],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync, promises as fs, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nimport { createFromBuffer } from \"@dprint/formatter\";\nimport { getPath } from \"@dprint/json\";\nimport { groupBy } from \"joist-utils\";\nimport { type ParseError, parse } from \"jsonc-parser\";\nimport { z } from \"zod\";\n\nimport { getLatestCodemodVersion } from \"./codemods/index.ts\";\nimport { type DbMetadata, type Entity, type EntityDbMetadata } from \"./EntityDbMetadata.ts\";\nimport { getStiEntities } from \"./inheritance.ts\";\nimport { logger } from \"./logger.ts\";\nimport { fail, sortKeys, trueIfResolved } from \"./utils.ts\";\n\nconst jsonFormatter = createFromBuffer(readFileSync(getPath()));\n\nconst fieldConfig = z\n .object({\n // For getters & ReactiveFields\n derived: z.optional(z.union([z.literal(\"sync\"), z.literal(\"async\")])),\n protected: z.optional(z.boolean()),\n ignore: z.optional(z.boolean()),\n superstruct: z.optional(z.string()),\n zodSchema: z.optional(z.string()),\n type: z.optional(z.string()),\n serde: z.optional(z.string()),\n stiDiscriminator: z.optional(z.record(z.string(), z.string())),\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n // Allow subclasses to mark fields as required\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n // Exclude a (large jsonb/text) column from the default SELECT and expose it as a lazy-loaded LazyField\n lazy: z.optional(z.boolean()),\n })\n .strict();\n\nexport type FieldConfig = z.infer<typeof fieldConfig>;\n\nconst relationConfig = z\n .object({\n // For ReactiveReferences\n derived: z.optional(z.literal(\"async\")),\n polymorphic: z.optional(z.union([z.literal(\"notNull\"), z.literal(true)])),\n large: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n /**\n * Controls whether this collection's `.get`/`.load` hide soft-deleted entities.\n *\n * Defaults to `\"exclude\"` (soft-deleted entities are hidden); set to `\"include\"` to have\n * this specific o2m/m2m always return soft-deleted entities from `.get`/`.load`.\n */\n softDeletes: z.optional(z.union([z.literal(\"include\"), z.literal(\"exclude\")])),\n // Allow pushing m2o/m2m/o2o relations in a base type (Task) down to a subtype (TaskOld)\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n /**\n * Allow specializing a base type relation (SmallPublisher.group: SmallPublisherGroup).\n *\n * Self-referential FKs also support `subType: \"self\"` that means each subtype will point\n * at its own subtype.\n */\n subType: z.optional(z.string()),\n /** Allow skipping self-referential fields getting a `...Recursive` relation. */\n skipRecursiveRelations: z.optional(z.boolean()),\n // Allow marking m2o FKs as required on subclasses\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n })\n .strict();\n\nexport type RelationConfig = z.infer<typeof relationConfig>;\n\nconst uniqueByConfig = z\n .union([z.string(), z.array(z.string()), z.array(z.array(z.string()))])\n .transform(normalizeUniqueByConfig);\n\nconst entityConfig = z\n .object({\n tag: z.string(),\n tableName: z.optional(z.string()),\n fields: z.optional(z.record(z.string(), fieldConfig)),\n relations: z.optional(z.record(z.string(), relationConfig)),\n /** Whether this entity should be abstract, e.g. for inheritance a subtype must be instantiated instead of this type. */\n abstract: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n uniqueBy: z.optional(uniqueByConfig),\n })\n .strict();\n\nexport type EntityConfig = z.infer<typeof entityConfig>;\n\nconst timestampConfig = z\n .object({\n /** The names to check for this timestamp, i.e. `created_at` `created`, etc. */\n names: z.array(z.string()),\n /** Whether this timestamp column is required to consider a table an entity, defaults to `false`. */\n required: z.optional(z.boolean()),\n })\n .strict();\n\nexport type TimestampConfig = z.infer<typeof timestampConfig>;\n\nexport const config = z\n .object({\n /** The _build-time_ database URL for reading database metadata. */\n databaseUrl: z.optional(z.string()),\n /** Your application's request-level `Context` type. */\n contextType: z.optional(z.string()),\n /** Your application's database client's `Transaction` type. */\n transactionType: z.optional(z.string()),\n /**\n * Allows the user to specify the `updated_at` / `created_at` column names to look up, and if they're optional.\n *\n * We default to looking for `updated_at`, `updatedAt`, `created_at`, `createdAt`, and optional to true,\n * e.g. tables are not required to have both timestamp columns to be considered entities.\n *\n * These defaults are the most lenient, to facilitate running Joist against an existing schema and\n * seeing all of your entities, regardless of your previous conventions.\n */\n timestampColumns: z.optional(\n z.object({\n createdAt: z.optional(timestampConfig),\n updatedAt: z.optional(timestampConfig),\n deletedAt: z.optional(timestampConfig),\n }),\n ),\n /**\n * Allows the user to have codegen output `Temporal` types instead of the base JS `Date`\n *\n * Additionally, allows for specifying the default time zone for `Temporal` types when converting dates to/from\n * the database.\n */\n temporal: z.optional(z.union([z.boolean(), z.object({ timeZone: z.string() })])),\n /**\n * By default, we create a `flush_database` function for fast testing.\n *\n * However, if you don't want to use this, or you have your own bespoke function like we do\n * that is more application-aware, then you can disable Joist's out-of-the-box one.\n *\n * If you have more than one test database, you can set `createFlushFunction` to the array\n * of test database names, i.e. `mydb_test_1`, `mydb_test_2`, etc.\n */\n createFlushFunction: z.optional(z.union([z.boolean(), z.array(z.string())])),\n entitiesDirectory: z.string().default(\"./src/entities\"),\n codegenPlugins: z.optional(z.array(z.string())),\n entities: z.record(z.string(), entityConfig).default({}),\n ignoredTables: z.optional(z.array(z.string())),\n /** The type of entity `id` fields; defaults to `tagged-string`. */\n idType: z.optional(z.union([z.literal(\"tagged-string\"), z.literal(\"untagged-string\"), z.literal(\"number\")])),\n /** The separator between entity tags and ids; defaults to `:`, and `\"\"` disables the separator. */\n tagDelimiter: z.optional(z.string()),\n /** How we should support non-deferred foreign keys. */\n nonDeferredForeignKeys: z.optional(z.union([z.literal(\"error\"), z.literal(\"warn\"), z.literal(\"ignore\")])),\n /** Enables esm output. */\n esm: z.optional(z.boolean()),\n /** Controls the style of GraphQL pagination scaffolding. */\n paginationStyle: z.optional(z.union([z.literal(\"cursor\"), z.literal(\"limit\")])).default(\"cursor\"),\n /** Enables documentation syncing between .md files and JSDocs. */\n docs: z.optional(z.boolean()),\n /** Installs Joist's bundled Agent Skills into `.claude/skills` and `.agents/skills`; on by default, set `false` to disable. */\n skills: z.optional(z.boolean()),\n /** Output a metadata-docs.ts file with entity/field documentation available at runtime. */\n outputDocs: z.optional(z.boolean()),\n /** Auto-set by probing the project's `tsconfig.json` file. */\n allowImportingTsExtensions: z.optional(z.boolean()),\n /** The latest Joist codemod counter that has been applied to this project. */\n codemodVersion: z.number().int().min(0).default(0),\n\n /** A list of postgres schemas to use for finding tables */\n schemas: z.optional(z.array(z.string())),\n })\n .strict();\n\nexport type Config = z.infer<typeof config> & {\n // We don't persist this, and instead just use it as a cache\n __tableToEntityName?: Record<string, string>;\n};\n\nexport const ormMaintainedFields = [\"createdAt\", \"updatedAt\"];\n\n/** Ensure the user doesn't have any typos in their config. */\nexport function warnInvalidConfigEntries(config: Config, db: DbMetadata): void {\n const entitiesByName = groupBy(db.entities, (e) => e.name);\n for (const [entityName, entityConfig] of Object.entries(config.entities)) {\n const entities = entitiesByName[entityName];\n if (!entities) {\n logger.warn(`Found config for non-existent entity ${entityName}`);\n continue;\n }\n // We don't have keyBy...\n const [entity] = entities;\n\n // Check fields\n const fields = [...entity.primitives, ...entity.enums];\n for (const [name, config] of Object.entries(entityConfig.fields || {})) {\n if (config.ignore) continue;\n let field = fields.find((f) => f.fieldName === name);\n // STI types might be in the base type\n if (!field && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n field = stiEntities?.flatMap((st) => [...st.primitives, ...st.enums]).find((f) => f.fieldName === name);\n }\n if (!field) logger.warn(`Found config for non-existent field ${entityName}.${name}`);\n }\n\n // Check relations\n const relations = [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.manyToManyEnums,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ];\n for (const [name, _] of Object.entries(entityConfig.relations || {})) {\n let relation = relations.find((r) => r.fieldName === name);\n // STI types might be in the subtypes\n if (!relation && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n relation = stiEntities\n ?.flatMap((entity) => [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ])\n ?.find((f) => f.fieldName === name);\n }\n // CTI subtype specializations (i.e. SmallPublisher.group: SmallPublisherGroup) need to look in the base type\n if (!relation && entity.baseType) {\n const baseType = entity.baseType;\n relation = [\n ...baseType.manyToOnes,\n ...baseType.oneToManys,\n ...baseType.manyToManys,\n ...baseType.oneToOnes,\n ...baseType.largeOneToManys,\n ...baseType.largeManyToManys,\n ...baseType.polymorphics,\n ].find((f) => f.fieldName === name);\n }\n\n if (!relation) logger.warn(`Found config for non-existent relation ${entityName}.${name}`);\n }\n\n const uniqueFields = [\n ...entity.primitives,\n ...entity.enums,\n ...entity.pgEnums,\n ...entity.manyToOnes,\n ...entity.polymorphics,\n ];\n for (const uniqueBy of entityConfig.uniqueBy || []) {\n for (const name of uniqueBy) {\n const field = uniqueFields.find((f) => f.fieldName === name);\n if (!field) {\n logger.warn(`Found uniqueBy for non-existent or non-queryable field ${entityName}.${name}`);\n } else if (field.kind === \"primitive\" && (field.derived || field.customSerde)) {\n logger.warn(`Found uniqueBy for unsupported primitive field ${entityName}.${name}`);\n } else if (field.kind === \"enum\" && (field.derived || field.isArray)) {\n logger.warn(`Found uniqueBy for unsupported enum field ${entityName}.${name}`);\n }\n }\n }\n }\n}\n\nexport function isGetterField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"sync\";\n}\n\nexport function isReactiveField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"async\";\n}\n\nexport function isReactiveReference(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\n/** Returns true if this m2m relation is configured as a ReactiveManyToMany (derived: async). */\nexport function isReactiveManyToMany(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\nexport function isProtected(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.protected === true;\n}\n\n/** Whether a column should be excluded from the default SELECT and exposed as a lazy-loaded `LazyField`. */\nexport function isLazyField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.lazy === true;\n}\n\nexport function serdeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.serde;\n}\n\nexport function superstructConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.superstruct;\n}\n\nexport function zodSchemaConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.zodSchema;\n}\n\nexport function fieldTypeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.type;\n}\n\nexport function isLargeCollection(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.large === true;\n}\n\n/** Whether a collection should include (or exclude) soft-deleted entities from `.get`/`.load`. */\nexport function softDeletesConfig(\n config: Config,\n entity: Entity,\n fieldName: string,\n): \"include\" | \"exclude\" | undefined {\n return config.entities[entity.name]?.relations?.[fieldName]?.softDeletes;\n}\n\nexport function isFieldIgnored(\n config: Config,\n entity: Entity,\n fieldName: string,\n notNull: boolean = false,\n hasDefault: boolean = false,\n): boolean {\n const ignore = config.entities[entity.name]?.fields?.[fieldName]?.ignore === true;\n if (ignore && notNull && !hasDefault) {\n fail(\n `notNull field ${entity.name}.${fieldName} cannot be ignored. Alter the column to be optional or have a default value prior to ignoring it.`,\n );\n }\n return ignore;\n}\n\nexport function isFieldHasDefault(config: Config, entity: Entity, fieldName: string): boolean {\n const entityConfig = config.entities[entity.name] ?? {};\n const fieldConfig = entityConfig.fields?.[fieldName] ?? entityConfig.relations?.[fieldName] ?? {};\n return fieldConfig.hasDefault === true;\n}\n\nconst configPath = \"./joist-config.json\";\n\nexport async function loadConfig(): Promise<Config> {\n const exists = await trueIfResolved(fs.access(configPath));\n if (exists) {\n const content = await fs.readFile(configPath);\n const result = config.safeParse(stripLegacyConfigKeys(JSON.parse(content.toString())));\n if (!result.success) {\n throw new Error(\n `Invalid joist-config.json: ${result.error.issues\n .map((ze) => `${ze.path.map(String).join(\"/\")} ${ze.message}`)\n .join(\"\\n\")}`,\n );\n }\n result.data.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return result.data;\n }\n // Brand-new projects should not be prompted to run historical codemods.\n const initial = config.parse({ codemodVersion: getLatestCodemodVersion() });\n initial.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return initial;\n}\n\n/**\n * Writes the potentially-updated config entry back to `joist-config.json`.\n *\n * We format the output with prettier so it should both a) look nice and b) be deterministic,\n * such that no changes to the config show up as noops to the scm.\n */\nexport async function writeConfig(config: Config): Promise<void> {\n const sorted: Partial<Config> = sortKeys(config);\n delete sorted.__tableToEntityName;\n delete sorted.allowImportingTsExtensions;\n if (sorted.paginationStyle === \"cursor\") {\n delete sorted.paginationStyle;\n }\n const input = JSON.stringify(sorted);\n const content = jsonFormatter.formatText({ filePath: \"test.json\", fileText: input });\n await fs.writeFile(configPath, content);\n}\n\nexport function stripStiPlaceholders(config: Config, entities: EntityDbMetadata[]): void {\n // Defacto (with today's setup) the config of STI entities lives on the base entity,\n // so don't write confusing subtype-specific entries into the config file.\n // ...hopefully we don't have any code accidentally looking for the STI config...\n for (const entity of entities) {\n if (entity.inheritanceType === \"sti\" && entity.stiDiscriminatorValue) {\n delete config.entities[entity.name];\n }\n }\n}\n\n/** Applies defaults to the timestamp config. */\nexport function getTimestampConfig(config: Config): {\n updatedAtConf: Required<TimestampConfig>;\n createdAtConf: Required<TimestampConfig>;\n deletedAtConf: Required<TimestampConfig>;\n} {\n return {\n createdAtConf: {\n names: [\"created_at\", \"createdAt\"],\n required: false,\n ...config?.timestampColumns?.createdAt,\n },\n updatedAtConf: {\n names: [\"updated_at\", \"updatedAt\"],\n required: false,\n ...config?.timestampColumns?.updatedAt,\n },\n deletedAtConf: {\n names: [\"deleted_at\", \"deletedAt\"],\n required: false,\n ...config?.timestampColumns?.deletedAt,\n },\n };\n}\n\nfunction projectIsUsingEsmWithImports(): boolean {\n // Attempt to find the project's tsconfig.json in the current directory or up the directory hierarchy\n const configPath = findTsConfigFile(process.cwd());\n if (!configPath) {\n return false;\n }\n try {\n // Use jsonc-parser to parse the tsconfig.json file (not the old tsc readConfigFile which was\n // dropped in TypeScript 7), allowing for comments and trailing commas.\n const errors: ParseError[] = [];\n const parsed: unknown = parse(readFileSync(configPath, \"utf8\"), errors, { allowTrailingComma: true });\n if (errors.length > 0 || typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n const compilerOptions = (parsed as Record<string, unknown>).compilerOptions;\n return (\n typeof compilerOptions === \"object\" &&\n compilerOptions !== null &&\n !Array.isArray(compilerOptions) &&\n (compilerOptions as Record<string, unknown>).allowImportingTsExtensions === true\n );\n } catch {\n return false;\n }\n}\n\n/** Normalizes `uniqueBy` config sugar into runtime identity candidates. */\nfunction normalizeUniqueByConfig(uniqueBy: string | string[] | string[][]): string[][] {\n if (typeof uniqueBy === \"string\") return [[uniqueBy]];\n if (uniqueBy.every((field) => typeof field === \"string\")) return [uniqueBy];\n return uniqueBy;\n}\n\nfunction stripLegacyConfigKeys(raw: unknown): unknown {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return raw;\n }\n // Accept old configs so the deprecated key disappears on the next write.\n const parsed = { ...(raw as Record<string, unknown>) };\n delete parsed.version;\n return parsed;\n}\n\n/** Finds the nearest `tsconfig.json` in `directory` or one of its ancestors. */\nfunction findTsConfigFile(directory: string): string | undefined {\n while (true) {\n const fileName = join(directory, \"tsconfig.json\");\n if (existsSync(fileName)) return fileName;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,gBAAgB,iBAAiB,aAAa,QAAQ,CAAC,CAAC;AAE9D,MAAM,cAAc,EACjB,OAAO;CAEN,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,QAAQ,MAAM,GAAG,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC;CACpE,WAAW,EAAE,SAAS,EAAE,QAAQ,CAAC;CACjC,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC;CAC9B,aAAa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AAM;EACX,MAAM,WAAW,KAAK,WAAW,eAAe;EAChD,IAAI,WAAW,QAAQ,GAAG,OAAO;EACjC,MAAM,SAAS,QAAQ,SAAS;EAChC,IAAI,WAAW,WAAW,OAAO,KAAA;EACjC,YAAY;CACd;AACF"}
@@ -68,6 +68,7 @@ function generateEntityCodegenFile(config, dbMeta, meta, scopeMembers = [], docs
68
68
  const maybeBaseFilter = baseEntity ? ts_poet.code`extends ${(0, ts_poet.imp)("t:" + baseEntity.entity.filterName + "@./entities.ts")}` : "";
69
69
  const maybeBaseGqlFilter = baseEntity ? ts_poet.code`extends ${(0, ts_poet.imp)("t:" + baseEntity.entity.graphqlFilterName + "@./entities.ts")}` : "";
70
70
  const maybeBaseOrder = baseEntity ? ts_poet.code`extends ${baseEntity.entity.orderType}` : "";
71
+ const maybeBaseFactoryExtras = baseEntity ? ts_poet.code`extends ${(0, ts_poet.imp)("t:" + baseEntity.entity.factoryExtrasName + "@./entities.ts")}` : "";
71
72
  meta.abstract && ts_poet.code`
72
73
  if (this.constructor === ${entity.type} && !(em as any).fakeInstance) {
73
74
  throw new Error(\`${entity.type} must be instantiated via a subtype\`);
@@ -111,7 +112,7 @@ function generateEntityCodegenFile(config, dbMeta, meta, scopeMembers = [], docs
111
112
  ${generateOrderFields(meta)}
112
113
  }
113
114
 
114
- export interface ${entity.factoryExtrasName} {
115
+ export interface ${entity.factoryExtrasName} ${maybeBaseFactoryExtras} {
115
116
  ${generateFactoryExtrasType(meta)}
116
117
  }
117
118
 
@@ -355,8 +356,9 @@ function generateFieldsType(meta, idType) {
355
356
  return ts_poet.code`${fieldName}: { kind: "primitive"; type: ${fieldType}; unique: ${unique}; nullable: ${undefinedOrNever(notNull)}, derived: ${derived !== false}; };`;
356
357
  });
357
358
  const enums = meta.enums.map((field) => {
358
- const { fieldName, enumType, notNull, isArray } = field;
359
+ const { fieldName, enumType, notNull, isArray, hasTransitions } = field;
359
360
  if (isArray) return ts_poet.code`${fieldName}: { kind: "enum"; type: ${enumType}[]; nullable: never; };`;
361
+ else if (hasTransitions) return ts_poet.code`${fieldName}: { kind: "enum"; type: ${enumType}; nullable: ${undefinedOrNever(notNull)}; accessors: keyof typeof ${enumType}; };`;
360
362
  else return ts_poet.code`${fieldName}: { kind: "enum"; type: ${enumType}; nullable: ${undefinedOrNever(notNull)}; };`;
361
363
  });
362
364
  const pgEnums = meta.pgEnums.map((field) => {
@@ -599,7 +601,7 @@ function generateFactoryExtrasType(meta) {
599
601
  const { fieldName, fieldType, notNull } = field;
600
602
  return ts_poet.code`${withName(fieldName)}?: ${fieldType}${maybeUnionNull(notNull)};`;
601
603
  });
602
- const enums = meta.enums.filter((f) => f.derived === "async").map((field) => {
604
+ const enums = meta.enums.filter((f) => f.derived === "async" || f.hasTransitions).map((field) => {
603
605
  const { fieldName, enumType, notNull, isArray } = field;
604
606
  if (isArray) return ts_poet.code`${withName(fieldName)}?: ${enumType}[];`;
605
607
  else return ts_poet.code`${withName(fieldName)}?: ${enumType}${maybeUnionNull(notNull)};`;