graphql-codegen-flutter-freezed
Version:
A stand-alone package to generate Freezed models from GraphQL schema based on the flutter-freezed plugin for GraphQL Code Generator
240 lines (239 loc) • 12.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultFreezedConfig = exports.DefaultFreezedPluginConfig = exports.FreezedFactoryBlockRepository = exports.FreezedImportBlock = exports.FreezedConfigValue = exports.transformCustomDecorators = exports.getCustomDecorators = exports.getFreezedConfigValue = exports.transformDefinition = void 0;
const freezed_declaration_blocks_1 = require("./freezed-declaration-blocks");
function transformDefinition(config, freezedFactoryBlockRepository, node) {
var _a;
// ignore these...
if (['Query', 'Mutation', 'Subscription', ...((_a = config === null || config === void 0 ? void 0 : config.ignoreTypes) !== null && _a !== void 0 ? _a : [])].includes(node.name.value)) {
return '';
}
return new freezed_declaration_blocks_1.FreezedDeclarationBlock(config, freezedFactoryBlockRepository, node).init();
}
exports.transformDefinition = transformDefinition;
/**
* returns the value of the FreezedConfig option
* for a specific type if given typeName
* or else fallback to the global FreezedConfig value
*/
function getFreezedConfigValue(option, config, typeName) {
var _a, _b, _c, _d, _e;
if (typeName) {
return (_d = (_c = (_b = (_a = config === null || config === void 0 ? void 0 : config.typeSpecificFreezedConfig) === null || _a === void 0 ? void 0 : _a[typeName]) === null || _b === void 0 ? void 0 : _b.config) === null || _c === void 0 ? void 0 : _c[option]) !== null && _d !== void 0 ? _d : getFreezedConfigValue(option, config);
}
return (_e = config === null || config === void 0 ? void 0 : config.globalFreezedConfig) === null || _e === void 0 ? void 0 : _e[option];
}
exports.getFreezedConfigValue = getFreezedConfigValue;
/**
* @description filters the customDirectives to return those that are applied on a list of blocks
*/
function getCustomDecorators(config, appliesOn, nodeName, fieldName) {
var _a, _b, _c, _d, _e, _f, _g, _h;
const filteredCustomDecorators = {};
const globalCustomDecorators = (_b = (_a = config === null || config === void 0 ? void 0 : config.globalFreezedConfig) === null || _a === void 0 ? void 0 : _a.customDecorators) !== null && _b !== void 0 ? _b : {};
let customDecorators = Object.assign({}, globalCustomDecorators);
if (nodeName) {
const typeConfig = (_c = config === null || config === void 0 ? void 0 : config.typeSpecificFreezedConfig) === null || _c === void 0 ? void 0 : _c[nodeName];
const typeSpecificCustomDecorators = (_e = (_d = typeConfig === null || typeConfig === void 0 ? void 0 : typeConfig.config) === null || _d === void 0 ? void 0 : _d.customDecorators) !== null && _e !== void 0 ? _e : {};
customDecorators = Object.assign(Object.assign({}, customDecorators), typeSpecificCustomDecorators);
if (fieldName) {
const fieldSpecificCustomDecorators = (_h = (_g = (_f = typeConfig === null || typeConfig === void 0 ? void 0 : typeConfig.fields) === null || _f === void 0 ? void 0 : _f[fieldName]) === null || _g === void 0 ? void 0 : _g.customDecorators) !== null && _h !== void 0 ? _h : {};
customDecorators = Object.assign(Object.assign({}, customDecorators), fieldSpecificCustomDecorators);
}
}
Object.entries(customDecorators).forEach(([key, value]) => {
var _a;
return (_a = value === null || value === void 0 ? void 0 : value.applyOn) === null || _a === void 0 ? void 0 : _a.forEach(a => {
if (appliesOn.includes(a)) {
filteredCustomDecorators[key] = value;
}
});
});
return filteredCustomDecorators;
}
exports.getCustomDecorators = getCustomDecorators;
function transformCustomDecorators(customDecorators, node, field) {
var _a, _b;
let result = [];
result = [
...result,
...((_a = node === null || node === void 0 ? void 0 : node.directives) !== null && _a !== void 0 ? _a : [])
.concat((_b = field === null || field === void 0 ? void 0 : field.directives) !== null && _b !== void 0 ? _b : [])
// extract only the directives whose names were specified as keys
// and have values that not undefined or null in the customDecorator record
.filter(d => {
var _a;
const key = d.name.value;
const value = (_a = customDecorators[key]) !== null && _a !== void 0 ? _a : customDecorators[`@${key}`];
if (value && value.mapsToFreezedAs !== 'custom') {
return true;
}
return false;
})
// transform each directive to string
.map(d => directiveToString(d, customDecorators)),
];
// for decorators that mapsToFreezedAs === 'custom'
Object.entries(customDecorators).forEach(([key, value]) => {
if (value.mapsToFreezedAs === 'custom') {
const args = value === null || value === void 0 ? void 0 : value.arguments;
// if the custom directives have arguments,
if (args && args !== []) {
// join them with a comma in the parenthesis
result = [...result, `${key}(${args.join(', ')})`];
}
else {
// else return the customDecorator key just as it is
result = [...result, key];
}
}
});
return result;
}
exports.transformCustomDecorators = transformCustomDecorators;
/**
* transforms the directive into a decorator array
* this decorator array might contain a `final` string which would be filtered out
* and used to mark the parameter block as final
*/
function directiveToString(directive, customDecorators) {
var _a, _b, _c, _d, _e;
const key = directive.name.value;
const value = customDecorators[key];
if (value.mapsToFreezedAs === 'directive') {
// get the directive's arguments
const directiveArgs = (_a = directive === null || directive === void 0 ? void 0 : directive.arguments) !== null && _a !== void 0 ? _a : [];
// extract the directive's argument using the template index: ["$0", "$1", ...]
// specified in the customDecorator.arguments array
const args = (_b = value === null || value === void 0 ? void 0 : value.arguments) === null || _b === void 0 ? void 0 : _b.filter(a => directiveArgs[argToInt(a)]).map(a => directiveArgs[argToInt(a)]).map(a => `${a.name}: ${a.value}`);
// if the args is not empty
if (args !== []) {
// returns "@directiveName(argName: argValue, argName: argValue ...)"
return `@${directive.name.value}(${args === null || args === void 0 ? void 0 : args.join(', ')})`;
}
}
else if (value.mapsToFreezedAs === '@Default') {
const defaultValue = (_c = directive === null || directive === void 0 ? void 0 : directive.arguments) === null || _c === void 0 ? void 0 : _c[argToInt((_e = (_d = value === null || value === void 0 ? void 0 : value.arguments) === null || _d === void 0 ? void 0 : _d[0]) !== null && _e !== void 0 ? _e : '0')];
if (defaultValue) {
return `@Default(value: ${defaultValue})`;
}
}
// returns either "@deprecated" || "final".
// `final` to be filtered from the decorators array when applying the decorators
return value.mapsToFreezedAs;
}
/** transforms string template: "$0" into an integer: 1 */
function argToInt(arg) {
var _a;
const parsedIndex = Number.parseInt((_a = arg.replace('$', '').trim()) !== null && _a !== void 0 ? _a : '0'); // '$1 => 1
return parsedIndex ? parsedIndex : 0;
}
/** a class variant of the getFreezedConfigValue helper function
*
* returns the value of the FreezedConfig option
* for a specific type if given typeName
* or else fallback to the global FreezedConfig value
*/
class FreezedConfigValue {
constructor(_config, _typeName) {
this._config = _config;
this._typeName = _typeName;
this._config = _config;
this._typeName = _typeName;
}
/**
* returns the value of the FreezedConfig option
* for a specific type if given typeName
* or else fallback to the global FreezedConfig value
*/
get(option) {
return getFreezedConfigValue(option, this._config, this._typeName);
}
}
exports.FreezedConfigValue = FreezedConfigValue;
class FreezedImportBlock {
// TODO: the constructor should accept a node, and extract it shape and store it but return itself
constructor(_config, _fileName) {
this._config = _config;
this._fileName = _fileName;
this._importFreezedAnnotation = true;
this._importFoundation = true;
}
string() {
return [
this._importFreezedAnnotation && "import 'package:freezed_annotation/freezed_annotation.dart';",
this._importFoundation && "import 'package:flutter/foundation.dart';",
`part ${this.getFileName(this._fileName)}.dart;`,
this._jsonSerializable && `part '${this.getFileName(this._fileName)}.g.dart';`,
].join('\n');
}
/** TODO: Work on the modularization
* returns the fileName without the extension.
* if modular is set to, returns the value of fileName from the config
*/
getFileName(fileName) {
return this._config.modular ? this._config.fileName : fileName === null || fileName === void 0 ? void 0 : fileName.replace('.dart', '');
}
}
exports.FreezedImportBlock = FreezedImportBlock;
/**
* stores an instance of FreezedFactoryBlock using the node names as the key
* and returns that instance when replacing tokens
* */
class FreezedFactoryBlockRepository {
constructor() {
this._store = {};
}
register(key, value) {
this._store[key] = value;
return value;
}
retrieve(key, appliesOn, name, typeName) {
return this._store[key]
.setDecorators(appliesOn, key)
.setKey(key)
.setName(name)
.setNamedConstructor(typeName)
.init();
}
}
exports.FreezedFactoryBlockRepository = FreezedFactoryBlockRepository;
/** initializes a FreezedPluginConfig with the defaults values */
class DefaultFreezedPluginConfig {
constructor(config = {}) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
Object.assign(this, {
customScalars: (_a = config.customScalars) !== null && _a !== void 0 ? _a : {},
fileName: (_b = config.fileName) !== null && _b !== void 0 ? _b : 'app_models',
globalFreezedConfig: Object.assign(Object.assign({}, new DefaultFreezedConfig()), ((_c = config.globalFreezedConfig) !== null && _c !== void 0 ? _c : {})),
typeSpecificFreezedConfig: (_d = config.typeSpecificFreezedConfig) !== null && _d !== void 0 ? _d : {},
ignoreTypes: (_e = config.ignoreTypes) !== null && _e !== void 0 ? _e : [],
interfaceNamePrefix: (_f = config.interfaceNamePrefix) !== null && _f !== void 0 ? _f : '',
interfaceNameSuffix: (_g = config.interfaceNameSuffix) !== null && _g !== void 0 ? _g : 'Interface',
lowercaseEnums: (_h = config.lowercaseEnums) !== null && _h !== void 0 ? _h : true,
modular: (_j = config.modular) !== null && _j !== void 0 ? _j : true,
});
}
}
exports.DefaultFreezedPluginConfig = DefaultFreezedPluginConfig;
/** initializes a FreezedConfig with the defaults values */
class DefaultFreezedConfig {
constructor() {
Object.assign(this, {
alwaysUseJsonKeyName: false,
copyWith: null,
customDecorators: {},
defaultUnionConstructor: true,
equal: null,
fromJsonToJson: true,
immutable: true,
makeCollectionsUnmodifiable: null,
mergeInputs: [],
mutableInputs: true,
privateEmptyConstructor: true,
unionKey: null,
unionValueCase: null,
});
}
}
exports.DefaultFreezedConfig = DefaultFreezedConfig;