{"version":3,"sources":["webpack:///./node_modules/miragejs/dist/mirage-esm.js"],"names":["ownKeys","object","enumerableOnly","keys","Object","getOwnPropertySymbols","symbols","filter","sym","getOwnPropertyDescriptor","enumerable","push","apply","_typeof","obj","Symbol","iterator","constructor","prototype","_classCallCheck","instance","Constructor","TypeError","_defineProperties","target","props","i","length","descriptor","configurable","writable","defineProperty","key","_createClass","protoProps","staticProps","_defineProperty","value","_inherits","subClass","superClass","create","_setPrototypeOf","_getPrototypeOf","o","setPrototypeOf","getPrototypeOf","__proto__","p","_isNativeReflectConstruct","Reflect","construct","sham","Proxy","Boolean","valueOf","call","e","_construct","Parent","args","Class","a","Function","bind","arguments","_assertThisInitialized","self","ReferenceError","_possibleConstructorReturn","_createSuper","Derived","hasNativeReflectConstruct","result","Super","NewTarget","this","_slicedToArray","arr","Array","isArray","_arrayWithHoles","_i","_s","_e","_arr","_n","_d","next","done","err","_iterableToArrayLimit","_unsupportedIterableToArray","_nonIterableRest","_toConsumableArray","_arrayLikeToArray","_arrayWithoutHoles","iter","from","_iterableToArray","_nonIterableSpread","minLen","n","toString","slice","name","test","len","arr2","Factory","build","sequence","_this","topLevelAttrs","assign","attrs","afterCreate","forEach","attr","isTrait","property","refs","get","set","newValue","edges","nodes","cursor","sorted","visited","visit","node","predecessors","indexOf","Error","concat","JSON","stringify","outgoing","edge","preds","child","reverse","referenceSort","sortAttrs","buildAttrs","_buildSingleValue","map","extend","newAttrs","Subclass","extractAfterCreateCallbacks","_this2","_ref","undefined","traits","afterCreateCallbacks","extension","attrName","__isTrait__","IdentityManager","_nextId","_ids","uniqueIdentifier","nextValue","id","inc","warn","console","Response","code","headers","data","hasOwnProperty","camelizeCache","dasherizeCache","underscoreCache","capitalizeCache","camelize","word","camelized","underscore","split","join","dasherize","dasherized","underscored","capitalize","capitalized","isAssociation","__isAssociation__","errorProps","assert","bool","text","MirageError","replace","message","stack","tmp","idx","prop","Association","modelName","opts","ownerModelName","schema","isExplicitReflexive","inverse","isImplicitReflexive","polymorphic","getForeignKey","identifierCache$1","BelongsTo","_Association","_super","identifier","foreignKey","ModelClass","modelPrototype","association","associationHash","belongsToAssociations","belongsToAssociationFks","addDependentAssociation","associationKeys","add","associationIdKeys","_tempAssociations","tempParent","isPolymorphic","type","toCollectionName","find","foreignKeyId","model","hasInverseFor","inverseFor","associate","parent","save","reload","fk","owner","where","potentialOwner","models","dependent","disassociate","duplicate","DbCollection","initialData","_records","identityManager","insert","_insertRecord","ids","_findRecords","record","_findRecord","query","_findRecordBy","_findRecordsWhere","attributesForCreate","queryResult","_queryResult","mergedAttributes","createdRecord","records","changedRecords","oldRecord","_updateRecord","_this3","reset","index","splice","queryFunction","every","String","fetch","targetId","currentId","Db","identityManagers","_collections","registerIdentityManagers","loadData","createCollection","reduce","collection","all","_IdentityManager","identityManagerFor","newCollection","recordsCopy","method","_len","collections","_key","c","remove","_identityManagers","_container","inflector","singularize","application","Collection","match","m","some","f","filteredModels","sortedModels","sort","_this$models","slicedModels","PolymorphicCollection","identifierCache","HasMany","hasManyAssociations","hasManyAssociationFks","tempChildren","el","_ref2","children","currentIds","pathModelClassCache","BaseRouteHandler","fullPath","lastPath","path","segment","request","jsonApiDoc","params","body","requestBody","parse","serializerOrRegistry","normalize","json","_getJsonApiDocForRequest","_getIdForRequest","attributes","relationships","sum","relationshipName","valueForRelationship","relationship","modelClassFor","associationFor","url","rel","urlEncodedPart","_urlEncodedPart$split2","decodeURIComponent","FunctionRouteHandler","_BaseRouteHandler","userFunction","server","response","serializerType","serializerFor","explicit","serialize","requestHeaders","lowerCaseHeaders","header","toLowerCase","_getAttrsForFormRequest","getModelClassFromPath","hasModelForModelName","_getAttrsForRequest","ObjectRouteHandler","BaseShorthandRouteHandler","shorthand","options","modelClass","handle","handleStringShorthand","modelClasses","handleArrayShorthand","GetShorthandRouteHandler","_BaseShorthandRouteHa","camelizedModelName","coalesce","getCoalescedIds","PostShorthandRouteHandler","PutShorthandRouteHandler","update","DeleteShorthandRouteHandler","destroy","pluralize","HeadShorthandRouteHandler","queryParams","_model","DEFAULT_CODES","put","post","RouteHandler","verb","rawHandler","customizedCode","handler","createHandler","_getMirageResponseForRequest","then","mirageResponse","serializedMirageResponse","toRackResponse","setRequest","_toMirageResponse","Promise","resolve","reject","_getCodeForResponse","Child","_protoProps$construct","Model","fks","_schema","_validateAttr","_setupAttr","_setupRelationship","toInternalCollectionName","isNew","db","_definePlainAttribute","isSaving","_saveAssociations","val","has","isSaved","_disassociateFromDependents","hasDbRecord","collectionName","source","getOwnPropertyDescriptors","defineProperties","_objectSpread2","associationsFor","associations","_explicitInverseFor","_implicitInverseFor","_checkForMultipleExplicitInverses","candidate","matchingPolymorphic","matchingInverse","modelMatches","inverseKeyMatches","candidateInverse","candidateIsImplicitInverse","candidateIsExplicitInverse","associatedModelOrCollection","includes","alreadyAssociatedWith","found","existingProperty","isFk","_validateForeignKeyExistsInDatabase","isNull","isCollection","isArrayOfModels","item","endsWith","isModelOrCollection","_isArrayOfModels","modelOrCollection","foreignKeyName","foreignKeys","foreignKeyLabel","_found","_association","_foreignKeyLabel","_saveBelongsToAssociations","_saveHasManyAssociations","_this4","_disassociateFromOldInverses","_saveNewAssociates","_associateWithNewInverses","_this5","_disassociateFromHasManyInverses","_disassociateFromBelongsToInverse","_this6","tempAssociation","associateIds","_ref3","associateId","_updateInDb","_this7","dependentAssociationsFor","disassociateAllDependentsFromTarget","tempAssociate","__isSavingNewChildren","equals","fkValue","_syncTempAssociations","_this8","_associateModelWithInverse","_this9","inverseFk","ownerId","newId","_newId","inverseCollection","currentIdsForInverse","newIdsForInverse","_this10","idLabel","findBelongsToAssociation","associationType","Serializer","registry","include","root","embed","serializeIds","primaryResource","buildPayload","toInclude","didSerialize","_this$getHashForPrima2","getHashForPrimaryResource","resourceHash","newIncludes","newDidSerialize","nextIncludedResource","shift","_this$getHashForInclu2","getHashForIncludedResource","_resourceHash","newToInclude","resource","_newDidSerialize","newJson","mergePayloads","hashWithRoot","_this$getHashForResou2","getHashForResource","hash","addToIncludes","keyForResource","serializer","_serializer$getHashFo2","newModels","rootKey","keyForRelationship","removeForeignKeys","lookupSerializer","isModel","_hashForModel","modelSerializer","getKeysForIncluded","resourceHashKey","keyForModel","keyForCollection","_attrsForModel","associatedResource","associatedResourceHash","formattedKey","keyForEmbeddedRelationship","_maybeAddAssociationIds","memo","_formatAttributeKeys","newHash","keyForRelationshipIds","formattedTypeKey","keyForPolymorphicForeignKeyType","formattedIdKey","keyForPolymorphicForeignKeyId","_formattedKey","keyForForeignKey","_formattedKey2","attributeName","formattedAttrs","keyForAttribute","JSONAPISerializer","_Serializer","alwaysIncludeLinkageData","_createRequestedIncludesGraph","getAddToIncludesForResource","included","hasQueryParamIncludes","getResourceObjectForModel","relationshipPaths","getAddToIncludesForResourceAndPaths","relationshipNames","getIncludesForResourceAndPath","names","nameForCurrentResource","modelsToAdd","typeKeyForModel","_maybeAddRelationshipsToResourceObjectForModel","relationshipKey","relationshipHash","hasLinksForRelationship","links","shouldIncludeLinkageData","_relationshipIsIncludedForModel","graphResource","graph","_includesGraph","graphKey","_graphKeyForModel","primaryResourceKey","_addPrimaryModelToRequestedIncludesGraph","getQueryParamIncludes","trim","includesPath","relationshipKeys","graphRelationshipKey","normalizedRelationshipKey","relationshipData","_addResourceToRequestedIncludesGraph","_addModelToRequestedIncludesGraph","resourceKey","_addResourceRelationshipsToRequestedIncludesGraph","SerializerRegistry","serializerMap","_serializerMap","payload","_isModelOrCollection","_isCollection","_ref$explicit","SerializerForResponse","_isModel","newSerializerMaps","currentSerializerMap","collectionNameCache","internalCollectionNameCache","modelNameCache","Schema","modelsMap","_registry","_dependentAssociations","registerModels","registerModel","Set","dependentAssociations","fksAddedFromThisModel","associationProperty","toModelName","setSchema","_association$getForei2","getForeignKeyArray","fkHolder","_addForeignKeyToRegistry","addMethodsToModelClass","findBy","findOrCreateBy","none","first","_instantiateModel","collectionForType","_hydrate","directDependents","polymorphicAssociations","modelFor","internalCollectionName","_modelFor","_foreignKeysFor","classes","defaultInflector$1","Container","className","defaultContainer","isPluralForModelCache","createPretender","window","passthroughRequest","shouldLog","log","toUpperCase","handledRequest","groupCollapsed","status","loggedRequest","loggedResponse","responseText","groupEnd","originalCheckPassthrough","checkPassthrough","shouldPassthrough","passthroughChecks","passthroughCheck","substr","passthrough","unhandledRequest","decodeURI","trackRequests","shouldTrackRequests","defaultRouteOptions","timing","defaultInflector","defaultPassthroughs","extractRouteArguments","lastArg","option","allOptions","optionKeys","isOption","t","Server","config","_config","didOverrideConfig","environment","routes","baseConfig","seeds","scenarios","namespace","register","urlPrefix","logging","testConfig","_defineRouteHandlerHelpers","registerSerializers","serializers","hasFactories","_hasModulesOfType","hasDefaultScenario","didOverridePretenderConfig","pretender","loadConfig","isTest","loadFactories","factories","loadFixtures","useDefaultPassthroughs","_configureDefaultPassthroughs","paths","verbs","pop","_getFullPath","fixtures","_len2","_key2","camelizedArgs","missingKeys","factoryMap","currentFactoryMap","_factoryMap","camelizedType","_len3","traitsAndOverrides","_key3","arg","overrides","factorySequences","OriginalFactory","factoryFor","_validateTraits","mergedExtensions","_mergeExtensions","_mapAssociationsFromAttributes","factory","amount","list","_len4","_key4","buildArgs","_modelOrFactoryExistsForType","_len5","_key5","modelOrRecord","collectionFromCreateList","_len6","_key6","createArguments","shutdown","resourceName","only","except","actionsMethodsAndsPathsMappings","methods","show","allActions","actions","action","methodsWithPath","alias","_len7","_key7","_extractRouteArgument","_extractRouteArgument2","_registerRouteHandler","routeHandler","_mirageResponse","_serialize","modules","modulesOfType","substring","namespaceSub","passthroughUrl","typeOrCollectionName","modelOrFactoryExists","_modelOrFactoryExistsForTypeOrCollectionName","isPlural","isUncountable","isPluralForModel","modelExists","dbCollectionExists","_typeIsPluralForModel","traitName","allExtensions","accum","factoryAssociation","normalizeIds","belongsToKeys","hasManyKeys","jsonApiPayload","associationModel","_associationModel"],"mappings":"4FAAA,ukBA4BA,SAASA,EAAQC,EAAQC,GACvB,IAAIC,EAAOC,OAAOD,KAAKF,GAEv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D5B,OAAOD,KAAKqV,GAAe7T,SAC7BgxB,EAAe/nB,KAAK4K,cAAgBA,GAG/Bmd,GAETza,gBAAiB,SAAyBtD,GACxC,OAAOA,EAAQ8D,aAAe9D,EAAQ8D,YAAY1I,OAGX5G,OAAO,CAChDgX,aAAc,SACdsC,YAAa,SAAqBnU,GAChC,OAAOrD,GAASqD,IAElBwV,gBAAiB,SAAyBzc,GACxC,OAAO4D,GAAS5D,IAElB4a,mBAAoB,SAA4B3T,GAC9C,OAAOrD,GAAStG,KAAKkO,WAAWC,UAAUyF,UAAUjK,KAEtDyU,2BAA4B,SAAoCa,GAC9D,OAAO3Y,GAAS2Y,IAElBR,sBAAuB,SAA+B9U,GACpD,OAAOrD,GAAStG,KAAKkO,WAAWC,UAAUyF,UAAUjK,KAEtDoV,iBAAkB,SAA0BjO,GAC1C,OAAOxK,GAAStG,KAAKkO,WAAWC,UAAUC,YAAY0C,KAExDwC,gBAAiB,SAAyBtD,GACxC,OAAOA,EAAQ8D,aAAe9D,EAAQ8D,YAAY1I","file":"2ca616f1-e0bb7f6e6fc4f832c1bf.js","sourcesContent":["import \"core-js/modules/es.array.reduce.js\";\nimport \"core-js/modules/es.array.sort.js\";\nimport isPlainObject from 'lodash.isplainobject';\nimport isFunction from 'lodash.isfunction';\nimport mapValues from 'lodash.mapvalues';\nimport uniq from 'lodash.uniq';\nimport flatten from 'lodash.flatten';\nimport '@miragejs/pretender-node-polyfill/before';\nimport Pretender from 'pretender';\nimport '@miragejs/pretender-node-polyfill/after';\nimport { camelize as camelize$1, dasherize as dasherize$1, underscore as underscore$1, capitalize as capitalize$1, singularize, pluralize } from 'inflected';\nimport lowerFirst from 'lodash.lowerfirst';\nimport isEqual from 'lodash.isequal';\nimport map from 'lodash.map';\nimport cloneDeep from 'lodash.clonedeep';\nimport invokeMap from 'lodash.invokemap';\nimport compact from 'lodash.compact';\nimport has from 'lodash.has';\nimport values from 'lodash.values';\nimport isEmpty from 'lodash.isempty';\nimport get from 'lodash.get';\nimport uniqBy from 'lodash.uniqby';\nimport forIn from 'lodash.forin';\nimport pick from 'lodash.pick';\nimport assign from 'lodash.assign';\nimport find from 'lodash.find';\nimport isInteger from 'lodash.isinteger';\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n\n if (enumerableOnly) {\n symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n }\n\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n}\n\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function _typeof(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n}\n\nfunction _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}\n\nfunction _construct(Parent, args, Class) {\n if (_isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) _setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}\n\nfunction _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (typeof call === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n\n return _assertThisInitialized(self);\n}\n\nfunction _createSuper(Derived) {\n var hasNativeReflectConstruct = _isNativeReflectConstruct();\n\n return function _createSuperInternal() {\n var Super = _getPrototypeOf(Derived),\n result;\n\n if (hasNativeReflectConstruct) {\n var NewTarget = _getPrototypeOf(this).constructor;\n\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n\n return _possibleConstructorReturn(this, result);\n };\n}\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();\n}\n\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\n\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"];\n\n if (_i == null) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n\n var _s, _e;\n\n try {\n for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n} // jscs:disable disallowVar, requireArrayDestructuring\n\n/**\n @hide\n*/\n\n\nfunction referenceSort(edges) {\n var nodes = uniq(flatten(edges));\n var cursor = nodes.length;\n var sorted = new Array(cursor);\n var visited = {};\n var i = cursor;\n\n var visit = function visit(node, i, predecessors) {\n if (predecessors.indexOf(node) >= 0) {\n throw new Error(\"Cyclic dependency in properties \".concat(JSON.stringify(predecessors)));\n }\n\n if (visited[i]) {\n return;\n } else {\n visited[i] = true;\n }\n\n var outgoing = edges.filter(function (edge) {\n return edge && edge[0] === node;\n });\n i = outgoing.length;\n\n if (i) {\n var preds = predecessors.concat(node);\n\n do {\n var pair = outgoing[--i];\n var child = pair[1];\n\n if (child) {\n visit(child, nodes.indexOf(child), preds);\n }\n } while (i);\n }\n\n sorted[--cursor] = node;\n };\n\n while (i--) {\n if (!visited[i]) {\n visit(nodes[i], i, []);\n }\n }\n\n return sorted.reverse();\n}\n\nvar Factory = function Factory() {\n this.build = function (sequence) {\n var _this = this;\n\n var object = {};\n var topLevelAttrs = Object.assign({}, this.attrs);\n delete topLevelAttrs.afterCreate;\n Object.keys(topLevelAttrs).forEach(function (attr) {\n if (Factory.isTrait.call(_this, attr)) {\n delete topLevelAttrs[attr];\n }\n });\n var keys = sortAttrs(topLevelAttrs, sequence);\n keys.forEach(function (key) {\n var buildAttrs, _buildSingleValue;\n\n buildAttrs = function buildAttrs(attrs) {\n return mapValues(attrs, _buildSingleValue);\n };\n\n _buildSingleValue = function buildSingleValue(value) {\n if (Array.isArray(value)) {\n return value.map(_buildSingleValue);\n } else if (isPlainObject(value)) {\n return buildAttrs(value);\n } else if (isFunction(value)) {\n return value.call(topLevelAttrs, sequence);\n } else {\n return value;\n }\n };\n\n var value = topLevelAttrs[key];\n\n if (isFunction(value)) {\n object[key] = value.call(object, sequence);\n } else {\n object[key] = _buildSingleValue(value);\n }\n });\n return object;\n };\n};\n\nFactory.extend = function (attrs) {\n // Merge the new attributes with existing ones. If conflict, new ones win.\n var newAttrs = Object.assign({}, this.attrs, attrs);\n\n var Subclass = function Subclass() {\n this.attrs = newAttrs;\n Factory.call(this);\n }; // Copy extend\n\n\n Subclass.extend = Factory.extend;\n Subclass.extractAfterCreateCallbacks = Factory.extractAfterCreateCallbacks;\n Subclass.isTrait = Factory.isTrait; // Store a reference on the class for future subclasses\n\n Subclass.attrs = newAttrs;\n return Subclass;\n};\n\nFactory.extractAfterCreateCallbacks = function () {\n var _this2 = this;\n\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n traits = _ref.traits;\n\n var afterCreateCallbacks = [];\n var attrs = this.attrs || {};\n var traitCandidates;\n\n if (attrs.afterCreate) {\n afterCreateCallbacks.push(attrs.afterCreate);\n }\n\n if (Array.isArray(traits)) {\n traitCandidates = traits;\n } else {\n traitCandidates = Object.keys(attrs);\n }\n\n traitCandidates.filter(function (attr) {\n return _this2.isTrait(attr) && attrs[attr].extension.afterCreate;\n }).forEach(function (attr) {\n afterCreateCallbacks.push(attrs[attr].extension.afterCreate);\n });\n return afterCreateCallbacks;\n};\n\nFactory.isTrait = function (attrName) {\n var attrs = this.attrs;\n return isPlainObject(attrs[attrName]) && attrs[attrName].__isTrait__ === true;\n};\n\nfunction sortAttrs(attrs, sequence) {\n var Temp = function Temp() {};\n\n var obj = new Temp();\n var refs = [];\n var property;\n Object.keys(attrs).forEach(function (key) {\n var value;\n Object.defineProperty(obj.constructor.prototype, key, {\n get: function get() {\n refs.push([property, key]);\n return value;\n },\n set: function set(newValue) {\n value = newValue;\n },\n enumerable: false,\n configurable: true\n });\n });\n Object.keys(attrs).forEach(function (key) {\n var value = attrs[key];\n\n if (typeof value !== \"function\") {\n obj[key] = value;\n }\n });\n Object.keys(attrs).forEach(function (key) {\n var value = attrs[key];\n property = key;\n\n if (typeof value === \"function\") {\n obj[key] = value.call(obj, sequence);\n }\n\n refs.push([key]);\n });\n return referenceSort(refs);\n}\n\nfunction isNumber(n) {\n return (+n).toString() === n.toString();\n}\n/**\n By default Mirage uses autoincrementing numbers starting with `1` as IDs for records. This can be customized by implementing one or more IdentityManagers for your application.\n\n An IdentityManager is a class that's responsible for generating unique identifiers. You can define a custom identity manager for your entire application, as well as on a per-model basis.\n\n A custom IdentityManager must implement these methods:\n\n - `fetch`, which must return an identifier not yet used\n - `set`, which is called with an `id` of a record being insert into Mirage's database\n - `reset`, which should reset database to initial state\n\n Check out the advanced guide on Mocking UUIDs to see a complete example of a custom IdentityManager.\n\n @class IdentityManager\n @constructor\n @public\n*/\n\n\nvar IdentityManager = /*#__PURE__*/function () {\n function IdentityManager() {\n _classCallCheck(this, IdentityManager);\n\n this._nextId = 1;\n this._ids = {};\n }\n /**\n @method get\n @hide\n @private\n */\n\n\n _createClass(IdentityManager, [{\n key: \"get\",\n value: function get() {\n return this._nextId;\n }\n /**\n Registers `uniqueIdentifier` as used.\n This method should throw is `uniqueIdentifier` has already been taken.\n @method set\n @param {String|Number} uniqueIdentifier\n @public\n */\n\n }, {\n key: \"set\",\n value: function set(uniqueIdentifier) {\n if (this._ids[uniqueIdentifier]) {\n throw new Error(\"Attempting to use the ID \".concat(uniqueIdentifier, \", but it's already been used\"));\n }\n\n if (isNumber(uniqueIdentifier) && +uniqueIdentifier >= this._nextId) {\n this._nextId = +uniqueIdentifier + 1;\n }\n\n this._ids[uniqueIdentifier] = true;\n }\n /**\n @method inc\n @hide\n @private\n */\n\n }, {\n key: \"inc\",\n value: function inc() {\n var nextValue = this.get() + 1;\n this._nextId = nextValue;\n return nextValue;\n }\n /**\n Returns the next unique identifier.\n @method fetch\n @return {String} Unique identifier\n @public\n */\n\n }, {\n key: \"fetch\",\n value: function fetch() {\n var id = this.get();\n this._ids[id] = true;\n this.inc();\n return id.toString();\n }\n /**\n Resets the identity manager, marking all unique identifiers as available.\n @method reset\n @public\n */\n\n }, {\n key: \"reset\",\n value: function reset() {\n this._nextId = 1;\n this._ids = {};\n }\n }]);\n\n return IdentityManager;\n}();\n/**\n @hide\n*/\n\n\nvar association = function association() {\n var __isAssociation__ = true;\n\n for (var _len = arguments.length, traitsAndOverrides = new Array(_len), _key = 0; _key < _len; _key++) {\n traitsAndOverrides[_key] = arguments[_key];\n }\n\n return {\n __isAssociation__: __isAssociation__,\n traitsAndOverrides: traitsAndOverrides\n };\n};\n\nvar trait = function trait(extension) {\n var __isTrait__ = true;\n return {\n extension: extension,\n __isTrait__: __isTrait__\n };\n};\n\nvar warn = console.warn; // eslint-disable-line no-console\n\n/**\n You can use this class when you want more control over your route handlers response.\n\n Pass the `code`, `headers` and `data` into the constructor and return an instance from any route handler.\n\n ```js\n import { Response } from 'miragejs';\n\n this.get('/users', () => {\n return new Response(400, { some: 'header' }, { errors: [ 'name cannot be blank'] });\n });\n ```\n*/\n\nvar Response = /*#__PURE__*/function () {\n function Response(code) {\n var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var data = arguments.length > 2 ? arguments[2] : undefined;\n\n _classCallCheck(this, Response);\n\n this.code = code;\n this.headers = headers; // Default data for \"undefined 204\" responses to empty string (no content)\n\n if (code === 204) {\n if (data !== undefined && data !== \"\") {\n warn(\"Mirage: One of your route handlers is returning a custom\\n 204 Response that has data, but this is a violation of the HTTP spec\\n and could lead to unexpected behavior. 204 responses should have no\\n content (an empty string) as their body.\");\n } else {\n this.data = \"\";\n } // Default data for \"empty untyped\" responses to empty JSON object\n\n } else if ((data === undefined || data === \"\") && !Object.prototype.hasOwnProperty.call(this.headers, \"Content-Type\")) {\n this.data = {};\n } else {\n this.data = data;\n } // Default \"untyped\" responses to application/json\n\n\n if (code !== 204 && !Object.prototype.hasOwnProperty.call(this.headers, \"Content-Type\")) {\n this.headers[\"Content-Type\"] = \"application/json\";\n }\n }\n\n _createClass(Response, [{\n key: \"toRackResponse\",\n value: function toRackResponse() {\n return [this.code, this.headers, this.data];\n }\n }]);\n\n return Response;\n}();\n\nvar camelizeCache = {};\nvar dasherizeCache = {};\nvar underscoreCache = {};\nvar capitalizeCache = {};\n/**\n * @param {String} word\n * @hide\n */\n\nfunction camelize(word) {\n if (typeof camelizeCache[word] !== \"string\") {\n var camelizedWord = camelize$1(underscore(word), false);\n /*\n The `ember-inflector` package's version of camelize lower-cases the first\n word after a slash, e.g.\n camelize('my-things/nice-watch'); // 'myThings/niceWatch'\n The `inflected` package doesn't, so we make that change here to not break\n existing functionality. (This affects the name of the schema collections.)\n */\n\n var camelized = camelizedWord.split(\"/\").map(lowerFirst).join(\"/\");\n camelizeCache[word] = camelized;\n }\n\n return camelizeCache[word];\n}\n/**\n * @param {String} word\n * @hide\n */\n\n\nfunction dasherize(word) {\n if (typeof dasherizeCache[word] !== \"string\") {\n var dasherized = dasherize$1(underscore(word));\n dasherizeCache[word] = dasherized;\n }\n\n return dasherizeCache[word];\n}\n\nfunction underscore(word) {\n if (typeof underscoreCache[word] !== \"string\") {\n var underscored = underscore$1(word);\n underscoreCache[word] = underscored;\n }\n\n return underscoreCache[word];\n}\n\nfunction capitalize(word) {\n if (typeof capitalizeCache[word] !== \"string\") {\n var capitalized = capitalize$1(word);\n capitalizeCache[word] = capitalized;\n }\n\n return capitalizeCache[word];\n}\n/**\n @hide\n*/\n\n\nfunction isAssociation(object) {\n return isPlainObject(object) && object.__isAssociation__ === true;\n}\n/* eslint no-console: 0 */\n\n\nvar errorProps = [\"description\", \"fileName\", \"lineNumber\", \"message\", \"name\", \"number\", \"stack\"];\n/**\n @hide\n*/\n\nfunction assert(bool, text) {\n if (typeof bool === \"string\" && !text) {\n // console.error(`Mirage: ${bool}`);\n throw new MirageError(bool);\n }\n\n if (!bool) {\n // console.error(`Mirage: ${text}`);\n throw new MirageError(text.replace(/^ +/gm, \"\") || \"Assertion failed\");\n }\n}\n/**\n @public\n @hide\n Copied from ember-metal/error\n*/\n\n\nfunction MirageError(message, stack) {\n var tmp = Error(message);\n\n if (stack) {\n tmp.stack = stack;\n }\n\n for (var idx = 0; idx < errorProps.length; idx++) {\n var prop = errorProps[idx];\n\n if ([\"description\", \"message\", \"stack\"].indexOf(prop) > -1) {\n this[prop] = \"Mirage: \".concat(tmp[prop]);\n } else {\n this[prop] = tmp[prop];\n }\n }\n}\n\nMirageError.prototype = Object.create(Error.prototype);\n/**\n Associations represent relationships between your Models.\n\n The `hasMany` and `belongsTo` helpers are how you actually define relationships:\n \n ```js\n import { createServer, Model, hasMany, belongsTo }\n\n createServer({\n models: {\n user: Model.extend({\n comments: hasMany()\n }),\n comments: Model.extend({\n user: belongsTo()\n })\n }\n })\n ```\n\n View [the Relationships](https://miragejs.com/docs/main-concepts/relationships/) guide to learn more about setting up relationships.\n\n Each usage of the helper registers an Association (either a `HasMany` association or `BelongsTo` association) with your server's `Schema`. You can access these associations using either the `schema.associationsFor()` method, or the `associations` property on individual model instances.\n\n You can then introspect the associations to do things like dynamically build up your JSON response in your serializers.\n\n @class Association\n @constructor\n @public\n*/\n\nvar Association = /*#__PURE__*/function () {\n function Association(modelName, opts) {\n _classCallCheck(this, Association);\n /**\n The modelName of the associated model.\n For example, given this configuration\n \n ```js\n createServer({\n models: {\n user: Model,\n comment: Model.extend({\n user: belongsTo()\n })\n }\n })\n ```\n the association's `modelName` would be `user`.\n Note that an association's `modelName` and the `name` can be different. This is because Mirage supports multiple relationships of the same type:\n ```js\n createServer({\n models: {\n user: Model,\n comment: Model.extend({\n author: belongsTo('user'),\n reviewer: belongsTo('user')\n })\n }\n })\n ```\n For both these relationships, the `modelName` is `user`, but the first association has a `name` of `author` while the second has a `name` of `reviewer`.\n @property\n @type {String}\n @public\n */\n\n\n this.modelName = undefined; // hack to add ESDOC info. Any better way?\n\n if (_typeof(modelName) === \"object\") {\n // Received opts only\n this.modelName = undefined;\n this.opts = modelName;\n } else {\n // The modelName of the association. (Might not be passed in - set later\n // by schema).\n this.modelName = modelName ? dasherize(modelName) : \"\";\n this.opts = opts || {};\n }\n /**\n The name of the association, which comes from the property name that was used to define it.\n For example, given this server definition\n \n ```js\n createServer({\n models: {\n user: Model,\n comment: Model.extend({\n author: belongsTo('user')\n })\n }\n })\n ```\n the association's `name` would be `author`.\n \n The name is used by Mirage to define foreign keys on the model (`comment.authorId` in this case), among other things.\n @property\n @type {String}\n @public\n */\n\n\n this.name = \"\"; // The modelName that owns this association\n\n this.ownerModelName = \"\";\n }\n /**\n A setter for schema, since we don't have a reference at constuction time.\n @method setSchema\n @public\n @hide\n */\n\n\n _createClass(Association, [{\n key: \"setSchema\",\n value: function setSchema(schema) {\n this.schema = schema;\n }\n /**\n Returns a Boolean that's true if the association is self-referential, i.e. if a model has an association with itself.\n For example, given\n ```js\n createServer({\n models: {\n user: Model.extend({\n friends: hasMany('user')\n })\n }\n })\n ```\n then\n ```js\n server.schema.associationsFor('user').friends.isReflexive // true\n ```\n @method isReflexive\n @return {Boolean}\n @public\n */\n\n }, {\n key: \"isReflexive\",\n value: function isReflexive() {\n var isExplicitReflexive = !!(this.modelName === this.ownerModelName && this.opts.inverse);\n var isImplicitReflexive = !!(this.opts.inverse === undefined && this.ownerModelName === this.modelName);\n return isExplicitReflexive || isImplicitReflexive;\n }\n /**\n Returns a Boolean that's true if the association is polymorphic:\n For example, given\n ```js\n createServer({\n models: {\n comment: Model.extend({\n commentable: belongsTo({ polymorphic: true })\n })\n }\n })\n ```\n then\n ```js\n server.schema.associationsFor('comment').commentable.isPolymorphic // true\n ```\n Check out [the guides on polymorphic associations](https://miragejs.com/docs/main-concepts/relationships/#polymorphic) to learn more.\n @accessor isPolymorphic\n @type {Boolean}\n @public\n */\n\n }, {\n key: \"isPolymorphic\",\n get: function get() {\n return this.opts.polymorphic;\n }\n /**\n Returns either the string `\"hasMany\"` or `\"belongsTo\"`, based on the association type.\n \n @accessor\n @type {String}\n @public\n */\n\n }, {\n key: \"type\",\n get: function get() {\n throw new Error(\"Subclasses of Association must implement a getter for type\");\n }\n /**\n Returns the name used for the association's foreign key.\n ```js\n let server = createServer({\n models: {\n user: Model,\n post: Model.extend({\n fineAuthor: belongsTo(\"user\"),\n comments: hasMany()\n }),\n comment: Model\n }\n });\n let associations = server.associationsFor('post')\n associations.fineAuthor.foreignKey // fineAuthorId\n associations.comments.foreignKey // commentIds\n ```\n \n @accessor\n @type {String}\n @public\n */\n\n }, {\n key: \"foreignKey\",\n get: function get() {\n return this.getForeignKey();\n }\n /**\n @hide\n */\n\n }, {\n key: \"identifier\",\n get: function get() {\n throw new Error(\"Subclasses of Association must implement a getter for identifier\");\n }\n }]);\n\n return Association;\n}();\n\nvar identifierCache$1 = {};\n/**\n * The belongsTo association adds a fk to the owner of the association\n *\n * @class BelongsTo\n * @extends Association\n * @constructor\n * @public\n * @hide\n */\n\nvar BelongsTo = /*#__PURE__*/function (_Association) {\n _inherits(BelongsTo, _Association);\n\n var _super = _createSuper(BelongsTo);\n\n function BelongsTo() {\n _classCallCheck(this, BelongsTo);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(BelongsTo, [{\n key: \"identifier\",\n get: function get() {\n if (typeof identifierCache$1[this.name] !== \"string\") {\n var identifier = \"\".concat(camelize(this.name), \"Id\");\n identifierCache$1[this.name] = identifier;\n }\n\n return identifierCache$1[this.name];\n }\n }, {\n key: \"type\",\n get: function get() {\n return \"belongsTo\";\n }\n /**\n * @method getForeignKeyArray\n * @return {Array} Array of camelized name of the model owning the association\n * and foreign key for the association\n * @public\n */\n\n }, {\n key: \"getForeignKeyArray\",\n value: function getForeignKeyArray() {\n return [camelize(this.ownerModelName), this.getForeignKey()];\n }\n /**\n * @method getForeignKey\n * @return {String} Foreign key for the association\n * @public\n */\n\n }, {\n key: \"getForeignKey\",\n value: function getForeignKey() {\n // we reuse identifierCache because it's the same logic as get identifier\n if (typeof identifierCache$1[this.name] !== \"string\") {\n var foreignKey = \"\".concat(camelize(this.name), \"Id\");\n identifierCache$1[this.name] = foreignKey;\n }\n\n return identifierCache$1[this.name];\n }\n /**\n * Registers belongs-to association defined by given key on given model,\n * defines getters / setters for associated parent and associated parent's id,\n * adds methods for creating unsaved parent record and creating a saved one\n *\n * @method addMethodsToModelClass\n * @param {Function} ModelClass\n * @param {String} key the named key for the association\n * @public\n */\n\n }, {\n key: \"addMethodsToModelClass\",\n value: function addMethodsToModelClass(ModelClass, key) {\n var modelPrototype = ModelClass.prototype;\n var association = this;\n var foreignKey = this.getForeignKey();\n\n var associationHash = _defineProperty({}, key, this);\n\n modelPrototype.belongsToAssociations = Object.assign(modelPrototype.belongsToAssociations, associationHash); // update belongsToAssociationFks\n\n Object.keys(modelPrototype.belongsToAssociations).forEach(function (key) {\n var value = modelPrototype.belongsToAssociations[key];\n modelPrototype.belongsToAssociationFks[value.getForeignKey()] = value;\n }); // Add to target's dependent associations array\n\n this.schema.addDependentAssociation(this, this.modelName); // TODO: look how this is used. Are these necessary, seems like they could be gotten from the above?\n // Or we could use a single data structure to store this information?\n\n modelPrototype.associationKeys.add(key);\n modelPrototype.associationIdKeys.add(foreignKey);\n Object.defineProperty(modelPrototype, foreignKey, {\n /*\n object.parentId\n - returns the associated parent's id\n */\n get: function get() {\n this._tempAssociations = this._tempAssociations || {};\n var tempParent = this._tempAssociations[key];\n var id;\n\n if (tempParent === null) {\n id = null;\n } else {\n if (association.isPolymorphic) {\n if (tempParent) {\n id = {\n id: tempParent.id,\n type: tempParent.modelName\n };\n } else {\n id = this.attrs[foreignKey];\n }\n } else {\n if (tempParent) {\n id = tempParent.id;\n } else {\n id = this.attrs[foreignKey];\n }\n }\n }\n\n return id;\n },\n\n /*\n object.parentId = (parentId)\n - sets the associated parent via id\n */\n set: function set(id) {\n var tempParent;\n\n if (id === null) {\n tempParent = null;\n } else if (id !== undefined) {\n if (association.isPolymorphic) {\n assert(_typeof(id) === \"object\", \"You're setting an ID on the polymorphic association '\".concat(association.name, \"' but you didn't pass in an object. Polymorphic IDs need to be in the form { type, id }.\"));\n tempParent = association.schema[association.schema.toCollectionName(id.type)].find(id.id);\n } else {\n tempParent = association.schema[association.schema.toCollectionName(association.modelName)].find(id);\n assert(tempParent, \"Couldn't find \".concat(association.modelName, \" with id = \").concat(id));\n }\n }\n\n this[key] = tempParent;\n }\n });\n Object.defineProperty(modelPrototype, key, {\n /*\n object.parent\n - returns the associated parent\n */\n get: function get() {\n this._tempAssociations = this._tempAssociations || {};\n var tempParent = this._tempAssociations[key];\n var foreignKeyId = this[foreignKey];\n var model = null;\n\n if (tempParent) {\n model = tempParent;\n } else if (foreignKeyId !== null) {\n if (association.isPolymorphic) {\n model = association.schema[association.schema.toCollectionName(foreignKeyId.type)].find(foreignKeyId.id);\n } else {\n model = association.schema[association.schema.toCollectionName(association.modelName)].find(foreignKeyId);\n }\n }\n\n return model;\n },\n\n /*\n object.parent = (parentModel)\n - sets the associated parent via model\n I want to jot some notes about hasInverseFor. There used to be an\n association.inverse() check, but adding polymorphic associations\n complicated this. `comment.commentable`, you can't easily check for an\n inverse since `comments: hasMany()` could be on any model.\n Instead of making it very complex and looking for an inverse on the\n association in isoaltion, it was much simpler to ask the model being\n passed in if it had an inverse for the setting model and with its\n association.\n */\n set: function set(model) {\n this._tempAssociations = this._tempAssociations || {};\n this._tempAssociations[key] = model;\n\n if (model && model.hasInverseFor(association)) {\n var inverse = model.inverseFor(association);\n model.associate(this, inverse);\n }\n }\n });\n /*\n object.newParent\n - creates a new unsaved associated parent\n TODO: document polymorphic\n */\n\n modelPrototype[\"new\".concat(capitalize(key))] = function () {\n var modelName, attrs;\n\n if (association.isPolymorphic) {\n modelName = arguments.length <= 0 ? undefined : arguments[0];\n attrs = arguments.length <= 1 ? undefined : arguments[1];\n } else {\n modelName = association.modelName;\n attrs = arguments.length <= 0 ? undefined : arguments[0];\n }\n\n var parent = association.schema[association.schema.toCollectionName(modelName)][\"new\"](attrs);\n this[key] = parent;\n return parent;\n };\n /*\n object.createParent\n - creates a new saved associated parent, and immediately persists both models\n TODO: document polymorphic\n */\n\n\n modelPrototype[\"create\".concat(capitalize(key))] = function () {\n var modelName, attrs;\n\n if (association.isPolymorphic) {\n modelName = arguments.length <= 0 ? undefined : arguments[0];\n attrs = arguments.length <= 1 ? undefined : arguments[1];\n } else {\n modelName = association.modelName;\n attrs = arguments.length <= 0 ? undefined : arguments[0];\n }\n\n var parent = association.schema[association.schema.toCollectionName(modelName)].create(attrs);\n this[key] = parent;\n this.save();\n return parent.reload();\n };\n }\n /**\n *\n *\n * @public\n */\n\n }, {\n key: \"disassociateAllDependentsFromTarget\",\n value: function disassociateAllDependentsFromTarget(model) {\n var _this = this;\n\n var owner = this.ownerModelName;\n var fk;\n\n if (this.isPolymorphic) {\n fk = {\n type: model.modelName,\n id: model.id\n };\n } else {\n fk = model.id;\n }\n\n var dependents = this.schema[this.schema.toCollectionName(owner)].where(function (potentialOwner) {\n var id = potentialOwner[_this.getForeignKey()];\n\n if (!id) {\n return false;\n }\n\n if (_typeof(id) === \"object\") {\n return id.type === fk.type && id.id === fk.id;\n } else {\n return id === fk;\n }\n });\n dependents.models.forEach(function (dependent) {\n dependent.disassociate(model, _this);\n dependent.save();\n });\n }\n }]);\n\n return BelongsTo;\n}(Association);\n\nfunction duplicate(data) {\n if (Array.isArray(data)) {\n return data.map(duplicate);\n } else {\n return Object.assign({}, data);\n }\n}\n/**\n Mirage's `Db` has many `DbCollections`, which are equivalent to tables from traditional databases. They store specific types of data, for example `users` and `posts`.\n\n `DbCollections` have names, like `users`, which you use to access the collection from the `Db` object.\n\n Suppose you had a `user` model defined, and the following data had been inserted into your database (either through factories or fixtures):\n\n ```js\n export default [\n { id: 1, name: 'Zelda' },\n { id: 2, name: 'Link' }\n ];\n ```\n\n Then `db.contacts` would return this array.\n\n @class DbCollection\n @constructor\n @public\n */\n\n\nvar DbCollection = /*#__PURE__*/function () {\n function DbCollection(name, initialData, IdentityManager) {\n _classCallCheck(this, DbCollection);\n\n this.name = name;\n this._records = [];\n this.identityManager = new IdentityManager();\n\n if (initialData) {\n this.insert(initialData);\n }\n }\n /**\n * Returns a copy of the data, to prevent inadvertent data manipulation.\n * @method all\n * @public\n * @hide\n */\n\n\n _createClass(DbCollection, [{\n key: \"all\",\n value: function all() {\n return duplicate(this._records);\n }\n /**\n Inserts `data` into the collection. `data` can be a single object\n or an array of objects. Returns the inserted record.\n ```js\n // Insert a single record\n let link = db.users.insert({ name: 'Link', age: 173 });\n link; // { id: 1, name: 'Link', age: 173 }\n // Insert an array\n let users = db.users.insert([\n { name: 'Zelda', age: 142 },\n { name: 'Epona', age: 58 },\n ]);\n users; // [ { id: 2, name: 'Zelda', age: 142 }, { id: 3, name: 'Epona', age: 58 } ]\n ```\n @method insert\n @param data\n @public\n */\n\n }, {\n key: \"insert\",\n value: function insert(data) {\n var _this = this;\n\n if (!Array.isArray(data)) {\n return this._insertRecord(data);\n } else {\n return map(data, function (attrs) {\n return _this._insertRecord(attrs);\n });\n }\n }\n /**\n Returns a single record from the `collection` if `ids` is a single\n id, or an array of records if `ids` is an array of ids. Note\n each id can be an int or a string, but integer ids as strings\n (e.g. the string “1”) will be treated as integers.\n ```js\n // Given users = [{id: 1, name: 'Link'}, {id: 2, name: 'Zelda'}]\n db.users.find(1); // {id: 1, name: 'Link'}\n db.users.find([1, 2]); // [{id: 1, name: 'Link'}, {id: 2, name: 'Zelda'}]\n ```\n @method find\n @param ids\n @public\n */\n\n }, {\n key: \"find\",\n value: function find(ids) {\n if (Array.isArray(ids)) {\n var records = this._findRecords(ids).filter(Boolean).map(duplicate); // Return a copy\n\n\n return records;\n } else {\n var record = this._findRecord(ids);\n\n if (!record) {\n return null;\n } // Return a copy\n\n\n return duplicate(record);\n }\n }\n /**\n Returns the first model from `collection` that matches the\n key-value pairs in the `query` object. Note that a string\n comparison is used. `query` is a POJO.\n ```js\n // Given users = [ { id: 1, name: 'Link' }, { id: 2, name: 'Zelda' } ]\n db.users.findBy({ name: 'Link' }); // { id: 1, name: 'Link' }\n ```\n @method find\n @param query\n @public\n */\n\n }, {\n key: \"findBy\",\n value: function findBy(query) {\n var record = this._findRecordBy(query);\n\n if (!record) {\n return null;\n } // Return a copy\n\n\n return duplicate(record);\n }\n /**\n Returns an array of models from `collection` that match the\n key-value pairs in the `query` object. Note that a string\n comparison is used. `query` is a POJO.\n ```js\n // Given users = [ { id: 1, name: 'Link' }, { id: 2, name: 'Zelda' } ]\n db.users.where({ name: 'Zelda' }); // [ { id: 2, name: 'Zelda' } ]\n ```\n @method where\n @param query\n @public\n */\n\n }, {\n key: \"where\",\n value: function where(query) {\n return this._findRecordsWhere(query).map(duplicate);\n }\n /**\n Finds the first record matching the provided _query_ in\n `collection`, or creates a new record using a merge of the\n `query` and optional `attributesForCreate`.\n Often times you may have a pattern like the following in your API stub:\n ```js\n // Given users = [\n // { id: 1, name: 'Link' },\n // { id: 2, name: 'Zelda' }\n // ]\n // Create Link if he doesn't yet exist\n let records = db.users.where({ name: 'Link' });\n let record;\n if (records.length > 0) {\n record = records[0];\n } else {\n record = db.users.insert({ name: 'Link' });\n }\n ```\n You can now replace this with the following:\n ```js\n let record = db.users.firstOrCreate({ name: 'Link' });\n ```\n An extended example using *attributesForCreate*:\n ```js\n let record = db.users.firstOrCreate({ name: 'Link' }, { evil: false });\n ```\n @method firstOrCreate\n @param query\n @param attributesForCreate\n @public\n */\n\n }, {\n key: \"firstOrCreate\",\n value: function firstOrCreate(query) {\n var attributesForCreate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var queryResult = this.where(query);\n\n var _queryResult = _slicedToArray(queryResult, 1),\n record = _queryResult[0];\n\n if (record) {\n return record;\n } else {\n var mergedAttributes = Object.assign(attributesForCreate, query);\n var createdRecord = this.insert(mergedAttributes);\n return createdRecord;\n }\n }\n /**\n Updates one or more records in the collection.\n If *attrs* is the only arg present, updates all records in the collection according to the key-value pairs in *attrs*.\n If *target* is present, restricts updates to those that match *target*. If *target* is a number or string, finds a single record whose id is *target* to update. If *target* is a POJO, queries *collection* for records that match the key-value pairs in *target*, and updates their *attrs*.\n Returns the updated record or records.\n ```js\n // Given users = [\n // {id: 1, name: 'Link'},\n // {id: 2, name: 'Zelda'}\n // ]\n db.users.update({name: 'Ganon'}); // db.users = [{id: 1, name: 'Ganon'}, {id: 2, name: 'Ganon'}]\n db.users.update(1, {name: 'Young Link'}); // db.users = [{id: 1, name: 'Young Link'}, {id: 2, name: 'Zelda'}]\n db.users.update({name: 'Link'}, {name: 'Epona'}); // db.users = [{id: 1, name: 'Epona'}, {id: 2, name: 'Zelda'}]\n ```\n @method update\n @param target\n @param attrs\n @public\n */\n\n }, {\n key: \"update\",\n value: function update(target, attrs) {\n var _this2 = this;\n\n var records;\n\n if (typeof attrs === \"undefined\") {\n attrs = target;\n var changedRecords = [];\n\n this._records.forEach(function (record) {\n var oldRecord = Object.assign({}, record);\n\n _this2._updateRecord(record, attrs);\n\n if (!isEqual(oldRecord, record)) {\n changedRecords.push(record);\n }\n });\n\n return changedRecords;\n } else if (typeof target === \"number\" || typeof target === \"string\") {\n var id = target;\n\n var record = this._findRecord(id);\n\n this._updateRecord(record, attrs);\n\n return record;\n } else if (Array.isArray(target)) {\n var ids = target;\n records = this._findRecords(ids);\n records.forEach(function (record) {\n _this2._updateRecord(record, attrs);\n });\n return records;\n } else if (_typeof(target) === \"object\") {\n var query = target;\n records = this._findRecordsWhere(query);\n records.forEach(function (record) {\n _this2._updateRecord(record, attrs);\n });\n return records;\n }\n }\n /**\n Removes one or more records in *collection*.\n If *target* is undefined, removes all records. If *target* is a number or string, removes a single record using *target* as id. If *target* is a POJO, queries *collection* for records that match the key-value pairs in *target*, and removes them from the collection.\n ```js\n // Given users = [\n // {id: 1, name: 'Link'},\n // {id: 2, name: 'Zelda'}\n // ]\n db.users.remove(); // db.users = []\n db.users.remove(1); // db.users = [{id: 2, name: 'Zelda'}]\n db.users.remove({name: 'Zelda'}); // db.users = [{id: 1, name: 'Link'}]\n ```\n @method remove\n @param target\n @public\n */\n\n }, {\n key: \"remove\",\n value: function remove(target) {\n var _this3 = this;\n\n var records;\n\n if (typeof target === \"undefined\") {\n this._records = [];\n this.identityManager.reset();\n } else if (typeof target === \"number\" || typeof target === \"string\") {\n var record = this._findRecord(target);\n\n var index = this._records.indexOf(record);\n\n this._records.splice(index, 1);\n } else if (Array.isArray(target)) {\n records = this._findRecords(target);\n records.forEach(function (record) {\n var index = _this3._records.indexOf(record);\n\n _this3._records.splice(index, 1);\n });\n } else if (_typeof(target) === \"object\") {\n records = this._findRecordsWhere(target);\n records.forEach(function (record) {\n var index = _this3._records.indexOf(record);\n\n _this3._records.splice(index, 1);\n });\n }\n }\n /*\n Private methods.\n These return the actual db objects, whereas the public\n API query methods return copies.\n */\n\n /**\n @method _findRecord\n @param id\n @private\n @hide\n */\n\n }, {\n key: \"_findRecord\",\n value: function _findRecord(id) {\n id = id.toString();\n return this._records.find(function (obj) {\n return obj.id === id;\n });\n }\n /**\n @method _findRecordBy\n @param query\n @private\n @hide\n */\n\n }, {\n key: \"_findRecordBy\",\n value: function _findRecordBy(query) {\n return this._findRecordsWhere(query)[0];\n }\n /**\n @method _findRecords\n @param ids\n @private\n @hide\n */\n\n }, {\n key: \"_findRecords\",\n value: function _findRecords(ids) {\n return ids.map(this._findRecord, this);\n }\n /**\n @method _findRecordsWhere\n @param query\n @private\n @hide\n */\n\n }, {\n key: \"_findRecordsWhere\",\n value: function _findRecordsWhere(query) {\n var records = this._records;\n\n function defaultQueryFunction(record) {\n var keys = Object.keys(query);\n return keys.every(function (key) {\n return String(record[key]) === String(query[key]);\n });\n }\n\n var queryFunction = _typeof(query) === \"object\" ? defaultQueryFunction : query;\n return records.filter(queryFunction);\n }\n /**\n @method _insertRecord\n @param data\n @private\n @hide\n */\n\n }, {\n key: \"_insertRecord\",\n value: function _insertRecord(data) {\n var attrs = duplicate(data);\n\n if (attrs && (attrs.id === undefined || attrs.id === null)) {\n attrs.id = this.identityManager.fetch(attrs);\n } else {\n attrs.id = attrs.id.toString();\n this.identityManager.set(attrs.id);\n }\n\n this._records.push(attrs);\n\n return duplicate(attrs);\n }\n /**\n @method _updateRecord\n @param record\n @param attrs\n @private\n @hide\n */\n\n }, {\n key: \"_updateRecord\",\n value: function _updateRecord(record, attrs) {\n var targetId = attrs && Object.prototype.hasOwnProperty.call(attrs, \"id\") ? attrs.id.toString() : null;\n var currentId = record.id;\n\n if (targetId && currentId !== targetId) {\n throw new Error(\"Updating the ID of a record is not permitted\");\n }\n\n for (var attr in attrs) {\n if (attr === \"id\") {\n continue;\n }\n\n record[attr] = attrs[attr];\n }\n }\n }]);\n\n return DbCollection;\n}();\n/**\n Your Mirage server has a database which you can interact with in your route handlers. You’ll typically use models to interact with your database data, but you can always reach into the db directly in the event you want more control.\n\n Access the db from your route handlers via `schema.db`.\n\n You can access individual DbCollections by using `schema.db.name`:\n\n ```js\n schema.db.users // would return, e.g., [ { id: 1, name: 'Yehuda' }, { id: 2, name: 'Tom '} ]\n ```\n\n @class Db\n @constructor\n @public\n */\n\n\nvar Db = /*#__PURE__*/function () {\n function Db(initialData, identityManagers) {\n _classCallCheck(this, Db);\n\n this._collections = [];\n this.registerIdentityManagers(identityManagers);\n\n if (initialData) {\n this.loadData(initialData);\n }\n }\n /**\n Loads an object of data into Mirage's database.\n The keys of the object correspond to the DbCollections, and the values are arrays of records.\n ```js\n server.db.loadData({\n users: [\n { name: 'Yehuda' },\n { name: 'Tom' }\n ]\n });\n ```\n As with `db.collection.insert`, IDs will automatically be created for records that don't have them.\n @method loadData\n @param {Object} data - Data to load\n @public\n */\n\n\n _createClass(Db, [{\n key: \"loadData\",\n value: function loadData(data) {\n for (var key in data) {\n this.createCollection(key, cloneDeep(data[key]));\n }\n }\n /**\n Logs out the contents of the Db.\n ```js\n server.db.dump() // { users: [ name: 'Yehuda', ...\n ```\n @method dump\n @public\n */\n\n }, {\n key: \"dump\",\n value: function dump() {\n return this._collections.reduce(function (data, collection) {\n data[collection.name] = collection.all();\n return data;\n }, {});\n }\n /**\n Add an empty collection named _name_ to your database. Typically you won’t need to do this yourself, since collections are automatically created for any models you have defined.\n @method createCollection\n @param name\n @param initialData (optional)\n @public\n */\n\n }, {\n key: \"createCollection\",\n value: function createCollection(name, initialData) {\n if (!this[name]) {\n var _IdentityManager = this.identityManagerFor(name);\n\n var newCollection = new DbCollection(name, initialData, _IdentityManager); // Public API has a convenient array interface. It comes at the cost of\n // returning a copy of all records to avoid accidental mutations.\n\n Object.defineProperty(this, name, {\n get: function get() {\n var recordsCopy = newCollection.all();\n [\"insert\", \"find\", \"findBy\", \"where\", \"update\", \"remove\", \"firstOrCreate\"].forEach(function (method) {\n recordsCopy[method] = function () {\n return newCollection[method].apply(newCollection, arguments);\n };\n });\n return recordsCopy;\n }\n }); // Private API does not have the array interface. This means internally, only\n // db-collection methods can be used. This is so records aren't copied redundantly\n // internally, which leads to accidental O(n^2) operations (e.g., createList).\n\n Object.defineProperty(this, \"_\".concat(name), {\n get: function get() {\n var recordsCopy = [];\n [\"insert\", \"find\", \"findBy\", \"where\", \"update\", \"remove\", \"firstOrCreate\"].forEach(function (method) {\n recordsCopy[method] = function () {\n return newCollection[method].apply(newCollection, arguments);\n };\n });\n return recordsCopy;\n }\n });\n\n this._collections.push(newCollection);\n } else if (initialData) {\n this[name].insert(initialData);\n }\n\n return this;\n }\n /**\n @method createCollections\n @param ...collections\n @public\n @hide\n */\n\n }, {\n key: \"createCollections\",\n value: function createCollections() {\n var _this = this;\n\n for (var _len = arguments.length, collections = new Array(_len), _key = 0; _key < _len; _key++) {\n collections[_key] = arguments[_key];\n }\n\n collections.forEach(function (c) {\n return _this.createCollection(c);\n });\n }\n /**\n Removes all data from Mirage's database.\n @method emptyData\n @public\n */\n\n }, {\n key: \"emptyData\",\n value: function emptyData() {\n this._collections.forEach(function (c) {\n return c.remove();\n });\n }\n /**\n @method identityManagerFor\n @param name\n @public\n @hide\n */\n\n }, {\n key: \"identityManagerFor\",\n value: function identityManagerFor(name) {\n return this._identityManagers[this._container.inflector.singularize(name)] || this._identityManagers.application || IdentityManager;\n }\n /**\n @method registerIdentityManagers\n @public\n @hide\n */\n\n }, {\n key: \"registerIdentityManagers\",\n value: function registerIdentityManagers(identityManagers) {\n this._identityManagers = identityManagers || {};\n }\n }]);\n\n return Db;\n}();\n/**\n Collections represent arrays of models. They are returned by a hasMany association, or by one of the ModelClass query methods:\n\n ```js\n let posts = user.blogPosts;\n let posts = schema.blogPosts.all();\n let posts = schema.blogPosts.find([1, 2, 4]);\n let posts = schema.blogPosts.where({ published: true });\n ```\n\n Note that there is also a `PolymorphicCollection` class that is identical to `Collection`, except it can contain a heterogeneous array of models. Thus, it has no `modelName` property. This lets serializers and other parts of the system interact with it differently.\n\n @class Collection\n @constructor\n @public\n*/\n\n\nvar Collection = /*#__PURE__*/function () {\n function Collection(modelName) {\n var models = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n\n _classCallCheck(this, Collection);\n\n assert(modelName && typeof modelName === \"string\", \"You must pass a `modelName` into a Collection\");\n /**\n The dasherized model name this Collection represents.\n ```js\n let posts = user.blogPosts;\n posts.modelName; // \"blog-post\"\n ```\n The model name is separate from the actual models, since Collections can be empty.\n @property modelName\n @type {String}\n @public\n */\n\n this.modelName = modelName;\n /**\n The underlying plain JavaScript array of Models in this Collection.\n ```js\n posts.models // [ post:1, post:2, ... ]\n ```\n While Collections have many array-ish methods like `filter` and `sort`, it\n can be useful to work with the plain array if you want to work with methods\n like `map`, or use the `[]` accessor.\n For example, in testing you might want to assert against a model from the\n collection:\n ```js\n let newPost = user.posts.models[0].title;\n assert.equal(newPost, \"My first post\");\n ```\n @property models\n @type {Array}\n @public\n */\n\n this.models = models;\n }\n /**\n The number of models in the collection.\n ```js\n user.posts.length; // 2\n ```\n @property length\n @type {Integer}\n @public\n */\n\n\n _createClass(Collection, [{\n key: \"length\",\n get: function get() {\n return this.models.length;\n }\n /**\n Updates each model in the collection, and immediately persists all changes to the db.\n ```js\n let posts = user.blogPosts;\n posts.update('published', true); // the db was updated for all posts\n ```\n @method update\n @param key\n @param val\n @return this\n @public\n */\n\n }, {\n key: \"update\",\n value: function update() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n invokeMap.apply(void 0, [this.models, \"update\"].concat(args));\n return this;\n }\n /**\n Saves all models in the collection.\n ```js\n let posts = user.blogPosts;\n posts.models[0].published = true;\n posts.save(); // all posts saved to db\n ```\n @method save\n @return this\n @public\n */\n\n }, {\n key: \"save\",\n value: function save() {\n invokeMap(this.models, \"save\");\n return this;\n }\n /**\n Reloads each model in the collection.\n ```js\n let posts = author.blogPosts;\n // ...\n posts.reload(); // reloads data for each post from the db\n ```\n @method reload\n @return this\n @public\n */\n\n }, {\n key: \"reload\",\n value: function reload() {\n invokeMap(this.models, \"reload\");\n return this;\n }\n /**\n Destroys the db record for all models in the collection.\n ```js\n let posts = user.blogPosts;\n posts.destroy(); // all posts removed from db\n ```\n @method destroy\n @return this\n @public\n */\n\n }, {\n key: \"destroy\",\n value: function destroy() {\n invokeMap(this.models, \"destroy\");\n return this;\n }\n /**\n Adds a model to this collection.\n ```js\n posts.length; // 1\n posts.add(newPost);\n posts.length; // 2\n ```\n @method add\n @param {Model} model\n @return this\n @public\n */\n\n }, {\n key: \"add\",\n value: function add(model) {\n this.models.push(model);\n return this;\n }\n /**\n Removes a model from this collection.\n ```js\n posts.length; // 5\n let firstPost = posts.models[0];\n posts.remove(firstPost);\n posts.save();\n posts.length; // 4\n ```\n @method remove\n @param {Model} model\n @return this\n @public\n */\n\n }, {\n key: \"remove\",\n value: function remove(model) {\n var match = this.models.find(function (m) {\n return m.toString() === model.toString();\n });\n\n if (match) {\n var i = this.models.indexOf(match);\n this.models.splice(i, 1);\n }\n\n return this;\n }\n /**\n Checks if the Collection includes the given model.\n ```js\n posts.includes(newPost);\n ```\n Works by checking if the given model name and id exists in the Collection,\n making it a bit more flexible than strict object equality.\n ```js\n let post = server.create('post');\n let programming = server.create('tag', { text: 'Programming' });\n visit(`/posts/${post.id}`);\n click('.tag-selector');\n click('.tag:contains(Programming)');\n post.reload();\n assert.ok(post.tags.includes(programming));\n ```\n @method includes\n @return {Boolean}\n @public\n */\n\n }, {\n key: \"includes\",\n value: function includes(model) {\n return this.models.some(function (m) {\n return m.toString() === model.toString();\n });\n }\n /**\n Returns a new Collection with its models filtered according to the provided [callback function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).\n ```js\n let publishedPosts = user.posts.filter(post => post.isPublished);\n ```\n @method filter\n @param {Function} f\n @return {Collection}\n @public\n */\n\n }, {\n key: \"filter\",\n value: function filter(f) {\n var filteredModels = this.models.filter(f);\n return new Collection(this.modelName, filteredModels);\n }\n /**\n Returns a new Collection with its models sorted according to the provided [compare function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters).\n ```js\n let postsByTitleAsc = user.posts.sort((a, b) => a.title > b.title ? 1 : -1 );\n ```\n @method sort\n @param {Function} f\n @return {Collection}\n @public\n */\n\n }, {\n key: \"sort\",\n value: function sort(f) {\n var sortedModels = this.models.concat().sort(f);\n return new Collection(this.modelName, sortedModels);\n }\n /**\n Returns a new Collection with a subset of its models selected from `begin` to `end`.\n ```js\n let firstThreePosts = user.posts.slice(0, 3);\n ```\n @method slice\n @param {Integer} begin\n @param {Integer} end\n @return {Collection}\n @public\n */\n\n }, {\n key: \"slice\",\n value: function slice() {\n var _this$models;\n\n var slicedModels = (_this$models = this.models).slice.apply(_this$models, arguments);\n\n return new Collection(this.modelName, slicedModels);\n }\n /**\n Modifies the Collection by merging the models from another collection.\n ```js\n user.posts.mergeCollection(newPosts);\n user.posts.save();\n ```\n @method mergeCollection\n @param {Collection} collection\n @return this\n @public\n */\n\n }, {\n key: \"mergeCollection\",\n value: function mergeCollection(collection) {\n this.models = this.models.concat(collection.models);\n return this;\n }\n /**\n Simple string representation of the collection and id.\n ```js\n user.posts.toString(); // collection:post(post:1,post:4)\n ```\n @method toString\n @return {String}\n @public\n */\n\n }, {\n key: \"toString\",\n value: function toString() {\n return \"collection:\".concat(this.modelName, \"(\").concat(this.models.map(function (m) {\n return m.id;\n }).join(\",\"), \")\");\n }\n }]);\n\n return Collection;\n}();\n/**\n * An array of models, returned from one of the schema query\n * methods (all, find, where). Knows how to update and destroy its models.\n *\n * Identical to Collection except it can contain a heterogeneous array of\n * models. Thus, it has no `modelName` property. This lets serializers and\n * other parts of the system interact with it differently.\n *\n * @class PolymorphicCollection\n * @constructor\n * @public\n * @hide\n */\n\n\nvar PolymorphicCollection = /*#__PURE__*/function () {\n function PolymorphicCollection() {\n var models = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n\n _classCallCheck(this, PolymorphicCollection);\n\n this.models = models;\n }\n /**\n * Number of models in the collection.\n *\n * @property length\n * @type Number\n * @public\n */\n\n\n _createClass(PolymorphicCollection, [{\n key: \"length\",\n get: function get() {\n return this.models.length;\n }\n /**\n * Updates each model in the collection (persisting immediately to the db).\n * @method update\n * @param key\n * @param val\n * @return this\n * @public\n */\n\n }, {\n key: \"update\",\n value: function update() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n invokeMap.apply(void 0, [this.models, \"update\"].concat(args));\n return this;\n }\n /**\n * Destroys the db record for all models in the collection.\n * @method destroy\n * @return this\n * @public\n */\n\n }, {\n key: \"destroy\",\n value: function destroy() {\n invokeMap(this.models, \"destroy\");\n return this;\n }\n /**\n * Saves all models in the collection.\n * @method save\n * @return this\n * @public\n */\n\n }, {\n key: \"save\",\n value: function save() {\n invokeMap(this.models, \"save\");\n return this;\n }\n /**\n * Reloads each model in the collection.\n * @method reload\n * @return this\n * @public\n */\n\n }, {\n key: \"reload\",\n value: function reload() {\n invokeMap(this.models, \"reload\");\n return this;\n }\n /**\n * Adds a model to this collection\n *\n * @method add\n * @return this\n * @public\n */\n\n }, {\n key: \"add\",\n value: function add(model) {\n this.models.push(model);\n return this;\n }\n /**\n * Removes a model to this collection\n *\n * @method remove\n * @return this\n * @public\n */\n\n }, {\n key: \"remove\",\n value: function remove(model) {\n var match = this.models.find(function (m) {\n return isEqual(m.attrs, model.attrs);\n });\n\n if (match) {\n var i = this.models.indexOf(match);\n this.models.splice(i, 1);\n }\n\n return this;\n }\n /**\n * Checks if the collection includes the model\n *\n * @method includes\n * @return boolean\n * @public\n */\n\n }, {\n key: \"includes\",\n value: function includes(model) {\n return this.models.some(function (m) {\n return isEqual(m.attrs, model.attrs);\n });\n }\n /**\n * @method filter\n * @param f\n * @return {Collection}\n * @public\n */\n\n }, {\n key: \"filter\",\n value: function filter(f) {\n var filteredModels = this.models.filter(f);\n return new PolymorphicCollection(filteredModels);\n }\n /**\n * @method sort\n * @param f\n * @return {Collection}\n * @public\n */\n\n }, {\n key: \"sort\",\n value: function sort(f) {\n var sortedModels = this.models.concat().sort(f);\n return new PolymorphicCollection(sortedModels);\n }\n /**\n * @method slice\n * @param {Integer} begin\n * @param {Integer} end\n * @return {Collection}\n * @public\n */\n\n }, {\n key: \"slice\",\n value: function slice() {\n var _this$models;\n\n var slicedModels = (_this$models = this.models).slice.apply(_this$models, arguments);\n\n return new PolymorphicCollection(slicedModels);\n }\n /**\n * @method mergeCollection\n * @param collection\n * @return this\n * @public\n */\n\n }, {\n key: \"mergeCollection\",\n value: function mergeCollection(collection) {\n this.models = this.models.concat(collection.models);\n return this;\n }\n /**\n * Simple string representation of the collection and id.\n * @method toString\n * @return {String}\n * @public\n */\n\n }, {\n key: \"toString\",\n value: function toString() {\n return \"collection:\".concat(this.modelName, \"(\").concat(this.models.map(function (m) {\n return m.id;\n }).join(\",\"), \")\");\n }\n }]);\n\n return PolymorphicCollection;\n}();\n\nvar identifierCache = {};\n/**\n * @class HasMany\n * @extends Association\n * @constructor\n * @public\n * @hide\n */\n\nvar HasMany = /*#__PURE__*/function (_Association) {\n _inherits(HasMany, _Association);\n\n var _super = _createSuper(HasMany);\n\n function HasMany() {\n _classCallCheck(this, HasMany);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(HasMany, [{\n key: \"identifier\",\n get: function get() {\n if (typeof identifierCache[this.name] !== \"string\") {\n var identifier = \"\".concat(camelize(this._container.inflector.singularize(this.name)), \"Ids\");\n identifierCache[this.name] = identifier;\n }\n\n return identifierCache[this.name];\n }\n }, {\n key: \"type\",\n get: function get() {\n return \"hasMany\";\n }\n /**\n * @method getForeignKeyArray\n * @return {Array} Array of camelized model name of associated objects\n * and foreign key for the object owning the association\n * @public\n */\n\n }, {\n key: \"getForeignKeyArray\",\n value: function getForeignKeyArray() {\n return [camelize(this.ownerModelName), this.getForeignKey()];\n }\n /**\n * @method getForeignKey\n * @return {String} Foreign key for the object owning the association\n * @public\n */\n\n }, {\n key: \"getForeignKey\",\n value: function getForeignKey() {\n // we reuse identifierCache because it's the same logic as get identifier\n if (typeof identifierCache[this.name] !== \"string\") {\n var foreignKey = \"\".concat(this._container.inflector.singularize(camelize(this.name)), \"Ids\");\n identifierCache[this.name] = foreignKey;\n }\n\n return identifierCache[this.name];\n }\n /**\n * Registers has-many association defined by given key on given model,\n * defines getters / setters for associated records and associated records' ids,\n * adds methods for creating unsaved child records and creating saved ones\n *\n * @method addMethodsToModelClass\n * @param {Function} ModelClass\n * @param {String} key\n * @public\n */\n\n }, {\n key: \"addMethodsToModelClass\",\n value: function addMethodsToModelClass(ModelClass, key) {\n var modelPrototype = ModelClass.prototype;\n var association = this;\n var foreignKey = this.getForeignKey();\n\n var associationHash = _defineProperty({}, key, this);\n\n modelPrototype.hasManyAssociations = Object.assign(modelPrototype.hasManyAssociations, associationHash); // update hasManyAssociationFks\n\n Object.keys(modelPrototype.hasManyAssociations).forEach(function (key) {\n var value = modelPrototype.hasManyAssociations[key];\n modelPrototype.hasManyAssociationFks[value.getForeignKey()] = value;\n }); // Add to target's dependent associations array\n\n this.schema.addDependentAssociation(this, this.modelName); // TODO: look how this is used. Are these necessary, seems like they could be gotten from the above?\n // Or we could use a single data structure to store this information?\n\n modelPrototype.associationKeys.add(key);\n modelPrototype.associationIdKeys.add(foreignKey);\n Object.defineProperty(modelPrototype, foreignKey, {\n /*\n object.childrenIds\n - returns an array of the associated children's ids\n */\n get: function get() {\n this._tempAssociations = this._tempAssociations || {};\n var tempChildren = this._tempAssociations[key];\n var ids = [];\n\n if (tempChildren) {\n if (association.isPolymorphic) {\n ids = tempChildren.models.map(function (model) {\n return {\n type: model.modelName,\n id: model.id\n };\n });\n } else {\n ids = tempChildren.models.map(function (model) {\n return model.id;\n });\n }\n } else {\n ids = this.attrs[foreignKey] || [];\n }\n\n return ids;\n },\n\n /*\n object.childrenIds = ([childrenIds...])\n - sets the associated children (via id)\n */\n set: function set(ids) {\n var tempChildren;\n\n if (ids === null) {\n tempChildren = [];\n } else if (ids !== undefined) {\n assert(Array.isArray(ids), \"You must pass an array in when setting \".concat(foreignKey, \" on \").concat(this));\n\n if (association.isPolymorphic) {\n assert(ids.every(function (el) {\n return _typeof(el) === \"object\" && _typeof(el.type) !== undefined && _typeof(el.id) !== undefined;\n }), \"You must pass in an array of polymorphic identifiers (objects of shape { type, id }) when setting \".concat(foreignKey, \" on \").concat(this));\n var models = ids.map(function (_ref) {\n var type = _ref.type,\n id = _ref.id;\n return association.schema[association.schema.toCollectionName(type)].find(id);\n });\n tempChildren = new PolymorphicCollection(models);\n } else {\n tempChildren = association.schema[association.schema.toCollectionName(association.modelName)].find(ids);\n }\n }\n\n this[key] = tempChildren;\n }\n });\n Object.defineProperty(modelPrototype, key, {\n /*\n object.children\n - returns an array of associated children\n */\n get: function get() {\n this._tempAssociations = this._tempAssociations || {};\n var collection = null;\n\n if (this._tempAssociations[key]) {\n collection = this._tempAssociations[key];\n } else {\n if (association.isPolymorphic) {\n if (this[foreignKey]) {\n var polymorphicIds = this[foreignKey];\n var models = polymorphicIds.map(function (_ref2) {\n var type = _ref2.type,\n id = _ref2.id;\n return association.schema[association.schema.toCollectionName(type)].find(id);\n });\n collection = new PolymorphicCollection(models);\n } else {\n collection = new PolymorphicCollection(association.modelName);\n }\n } else {\n if (this[foreignKey]) {\n collection = association.schema[association.schema.toCollectionName(association.modelName)].find(this[foreignKey]);\n } else {\n collection = new Collection(association.modelName);\n }\n }\n\n this._tempAssociations[key] = collection;\n }\n\n return collection;\n },\n\n /*\n object.children = [model1, model2, ...]\n - sets the associated children (via array of models or Collection)\n */\n set: function set(models) {\n var _this = this;\n\n if (models instanceof Collection || models instanceof PolymorphicCollection) {\n models = models.models;\n }\n\n models = models ? compact(models) : [];\n this._tempAssociations = this._tempAssociations || {};\n var collection;\n\n if (association.isPolymorphic) {\n collection = new PolymorphicCollection(models);\n } else {\n collection = new Collection(association.modelName, models);\n }\n\n this._tempAssociations[key] = collection;\n models.forEach(function (model) {\n if (model.hasInverseFor(association)) {\n var inverse = model.inverseFor(association);\n model.associate(_this, inverse);\n }\n });\n }\n });\n /*\n object.newChild\n - creates a new unsaved associated child\n */\n\n modelPrototype[\"new\".concat(capitalize(camelize(this._container.inflector.singularize(association.name))))] = function () {\n var modelName, attrs;\n\n if (association.isPolymorphic) {\n modelName = arguments.length <= 0 ? undefined : arguments[0];\n attrs = arguments.length <= 1 ? undefined : arguments[1];\n } else {\n modelName = association.modelName;\n attrs = arguments.length <= 0 ? undefined : arguments[0];\n }\n\n var child = association.schema[association.schema.toCollectionName(modelName)][\"new\"](attrs);\n var children = this[key].models;\n children.push(child);\n this[key] = children;\n return child;\n };\n /*\n object.createChild\n - creates a new saved associated child, and immediately persists both models\n TODO: forgot why this[key].add(child) doesn't work, most likely\n because these external APIs trigger saving cascades. Should probably\n have an internal method like this[key]._add.\n */\n\n\n modelPrototype[\"create\".concat(capitalize(camelize(this._container.inflector.singularize(association.name))))] = function () {\n var modelName, attrs;\n\n if (association.isPolymorphic) {\n modelName = arguments.length <= 0 ? undefined : arguments[0];\n attrs = arguments.length <= 1 ? undefined : arguments[1];\n } else {\n modelName = association.modelName;\n attrs = arguments.length <= 0 ? undefined : arguments[0];\n }\n\n var child = association.schema[association.schema.toCollectionName(modelName)].create(attrs);\n var children = this[key].models;\n children.push(child);\n this[key] = children;\n this.save();\n return child.reload();\n };\n }\n /**\n *\n *\n * @public\n */\n\n }, {\n key: \"disassociateAllDependentsFromTarget\",\n value: function disassociateAllDependentsFromTarget(model) {\n var _this2 = this;\n\n var owner = this.ownerModelName;\n var fk;\n\n if (this.isPolymorphic) {\n fk = {\n type: model.modelName,\n id: model.id\n };\n } else {\n fk = model.id;\n }\n\n var dependents = this.schema[this.schema.toCollectionName(owner)].where(function (potentialOwner) {\n var currentIds = potentialOwner[_this2.getForeignKey()]; // Need this check because currentIds could be null\n\n\n return currentIds && currentIds.find(function (id) {\n if (_typeof(id) === \"object\") {\n return id.type === fk.type && id.id === fk.id;\n } else {\n return id === fk;\n }\n });\n });\n dependents.models.forEach(function (dependent) {\n dependent.disassociate(model, _this2);\n dependent.save();\n });\n }\n }]);\n\n return HasMany;\n}(Association);\n\nvar pathModelClassCache = {};\n/**\n @hide\n*/\n\nvar BaseRouteHandler = /*#__PURE__*/function () {\n function BaseRouteHandler() {\n _classCallCheck(this, BaseRouteHandler);\n }\n\n _createClass(BaseRouteHandler, [{\n key: \"getModelClassFromPath\",\n value: function getModelClassFromPath(fullPath) {\n if (!fullPath) {\n return;\n }\n\n if (typeof pathModelClassCache[fullPath] !== \"string\") {\n var path = fullPath.split(\"/\");\n var lastPath;\n\n for (var i = path.length - 1; i >= 0; i--) {\n var segment = path[i];\n\n if (segment.length && segment[0] !== \":\") {\n lastPath = segment;\n break;\n }\n }\n\n pathModelClassCache[fullPath] = dasherize(camelize(this._container.inflector.singularize(lastPath)));\n }\n\n return pathModelClassCache[fullPath];\n }\n }, {\n key: \"_getIdForRequest\",\n value: function _getIdForRequest(request, jsonApiDoc) {\n var id;\n\n if (request && request.params && request.params.id) {\n id = request.params.id;\n } else if (jsonApiDoc && jsonApiDoc.data && jsonApiDoc.data.id) {\n id = jsonApiDoc.data.id;\n }\n\n return id;\n }\n }, {\n key: \"_getJsonApiDocForRequest\",\n value: function _getJsonApiDocForRequest(request, modelName) {\n var body;\n\n if (request && request.requestBody) {\n body = JSON.parse(request.requestBody);\n }\n\n return this.serializerOrRegistry.normalize(body, modelName);\n }\n }, {\n key: \"_getAttrsForRequest\",\n value: function _getAttrsForRequest(request, modelName) {\n var _this = this;\n\n var json = this._getJsonApiDocForRequest(request, modelName);\n\n var id = this._getIdForRequest(request, json);\n\n var attrs = {};\n assert(json.data && (json.data.attributes || json.data.type || json.data.relationships), \"You're using a shorthand or #normalizedRequestAttrs, but your serializer's normalize function did not return a valid JSON:API document. Consult the docs for the normalize hook on the Serializer class.\");\n\n if (json.data.attributes) {\n attrs = Object.keys(json.data.attributes).reduce(function (sum, key) {\n sum[camelize(key)] = json.data.attributes[key];\n return sum;\n }, {});\n }\n\n if (json.data.relationships) {\n Object.keys(json.data.relationships).forEach(function (relationshipName) {\n var relationship = json.data.relationships[relationshipName];\n\n var modelClass = _this.schema.modelClassFor(modelName);\n\n var association = modelClass.associationFor(camelize(relationshipName));\n var valueForRelationship;\n assert(association, \"You're passing the relationship '\".concat(relationshipName, \"' to the '\").concat(modelName, \"' model via a \").concat(request.method, \" to '\").concat(request.url, \"', but you did not define the '\").concat(relationshipName, \"' association on the '\").concat(modelName, \"' model.\"));\n\n if (association.isPolymorphic) {\n valueForRelationship = relationship.data;\n } else if (association instanceof HasMany) {\n valueForRelationship = relationship.data && relationship.data.map(function (rel) {\n return rel.id;\n });\n } else {\n valueForRelationship = relationship.data && relationship.data.id;\n }\n\n attrs[association.identifier] = valueForRelationship;\n }, {});\n }\n\n if (id) {\n attrs.id = id;\n }\n\n return attrs;\n }\n }, {\n key: \"_getAttrsForFormRequest\",\n value: function _getAttrsForFormRequest(_ref) {\n var requestBody = _ref.requestBody;\n var attrs;\n var urlEncodedParts = [];\n assert(requestBody && typeof requestBody === \"string\", \"You're using the helper method #normalizedFormData, but the request body is empty or not a valid url encoded string.\");\n urlEncodedParts = requestBody.split(\"&\");\n attrs = urlEncodedParts.reduce(function (a, urlEncodedPart) {\n var _urlEncodedPart$split = urlEncodedPart.split(\"=\"),\n _urlEncodedPart$split2 = _slicedToArray(_urlEncodedPart$split, 2),\n key = _urlEncodedPart$split2[0],\n value = _urlEncodedPart$split2[1];\n\n a[key] = decodeURIComponent(value.replace(/\\+/g, \" \"));\n return a;\n }, {});\n return attrs;\n }\n }]);\n\n return BaseRouteHandler;\n}();\n/**\n * @hide\n */\n\n\nvar FunctionRouteHandler = /*#__PURE__*/function (_BaseRouteHandler) {\n _inherits(FunctionRouteHandler, _BaseRouteHandler);\n\n var _super = _createSuper(FunctionRouteHandler);\n\n function FunctionRouteHandler(schema, serializerOrRegistry, userFunction, path, server) {\n var _this;\n\n _classCallCheck(this, FunctionRouteHandler);\n\n _this = _super.call(this, server);\n _this.schema = schema;\n _this.serializerOrRegistry = serializerOrRegistry;\n _this.userFunction = userFunction;\n _this.path = path;\n return _this;\n }\n\n _createClass(FunctionRouteHandler, [{\n key: \"handle\",\n value: function handle(request) {\n return this.userFunction(this.schema, request);\n }\n }, {\n key: \"setRequest\",\n value: function setRequest(request) {\n this.request = request;\n }\n }, {\n key: \"serialize\",\n value: function serialize(response, serializerType) {\n var serializer;\n\n if (serializerType) {\n serializer = this.serializerOrRegistry.serializerFor(serializerType, {\n explicit: true\n });\n } else {\n serializer = this.serializerOrRegistry;\n }\n\n return serializer.serialize(response, this.request);\n }\n }, {\n key: \"normalizedRequestAttrs\",\n value: function normalizedRequestAttrs() {\n var modelName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n var path = this.path,\n request = this.request,\n requestHeaders = this.request.requestHeaders;\n var attrs;\n var lowerCaseHeaders = {};\n\n for (var header in requestHeaders) {\n lowerCaseHeaders[header.toLowerCase()] = requestHeaders[header];\n }\n\n if (/x-www-form-urlencoded/.test(lowerCaseHeaders[\"content-type\"])) {\n attrs = this._getAttrsForFormRequest(request);\n } else {\n if (modelName) {\n assert(dasherize(modelName) === modelName, \"You called normalizedRequestAttrs('\".concat(modelName, \"'), but normalizedRequestAttrs was intended to be used with the dasherized version of the model type. Please change this to normalizedRequestAttrs('\").concat(dasherize(modelName), \"').\"));\n } else {\n modelName = this.getModelClassFromPath(path);\n }\n\n assert(this.schema.hasModelForModelName(modelName), \"You're using a shorthand or the #normalizedRequestAttrs helper but the detected model of '\".concat(modelName, \"' does not exist. You might need to pass in the correct modelName as the first argument to #normalizedRequestAttrs.\"));\n attrs = this._getAttrsForRequest(request, modelName);\n }\n\n return attrs;\n }\n }]);\n\n return FunctionRouteHandler;\n}(BaseRouteHandler);\n/**\n * @hide\n */\n\n\nvar ObjectRouteHandler = /*#__PURE__*/function () {\n function ObjectRouteHandler(schema, serializerOrRegistry, object) {\n _classCallCheck(this, ObjectRouteHandler);\n\n this.schema = schema;\n this.serializerOrRegistry = serializerOrRegistry;\n this.object = object;\n }\n\n _createClass(ObjectRouteHandler, [{\n key: \"handle\",\n value: function handle() {\n return this.object;\n }\n }]);\n\n return ObjectRouteHandler;\n}();\n/**\n @hide\n*/\n\n\nvar BaseShorthandRouteHandler = /*#__PURE__*/function (_BaseRouteHandler) {\n _inherits(BaseShorthandRouteHandler, _BaseRouteHandler);\n\n var _super = _createSuper(BaseShorthandRouteHandler);\n\n function BaseShorthandRouteHandler(schema, serializerOrRegistry, shorthand, path) {\n var _this;\n\n var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};\n\n _classCallCheck(this, BaseShorthandRouteHandler);\n\n _this = _super.call(this);\n shorthand = shorthand || _this.getModelClassFromPath(path);\n _this.schema = schema;\n _this.serializerOrRegistry = serializerOrRegistry;\n _this.shorthand = shorthand;\n _this.options = options;\n var type = Array.isArray(shorthand) ? \"array\" : _typeof(shorthand);\n\n if (type === \"string\") {\n var modelClass = _this.schema[_this.schema.toCollectionName(shorthand)];\n\n _this.handle = function (request) {\n return _this.handleStringShorthand(request, modelClass);\n };\n } else if (type === \"array\") {\n var modelClasses = shorthand.map(function (modelName) {\n return _this.schema[_this.schema.toCollectionName(modelName)];\n });\n\n _this.handle = function (request) {\n return _this.handleArrayShorthand(request, modelClasses);\n };\n }\n\n return _this;\n } // handleStringShorthand() {\n //\n // }\n //\n // handleArrayShorthand() {\n //\n // }\n\n\n return BaseShorthandRouteHandler;\n}(BaseRouteHandler);\n/**\n * @hide\n */\n\n\nvar GetShorthandRouteHandler = /*#__PURE__*/function (_BaseShorthandRouteHa) {\n _inherits(GetShorthandRouteHandler, _BaseShorthandRouteHa);\n\n var _super = _createSuper(GetShorthandRouteHandler);\n\n function GetShorthandRouteHandler() {\n _classCallCheck(this, GetShorthandRouteHandler);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(GetShorthandRouteHandler, [{\n key: \"handleStringShorthand\",\n value:\n /*\n Retrieve a model/collection from the db.\n Examples:\n this.get('/contacts', 'contact');\n this.get('/contacts/:id', 'contact');\n */\n function handleStringShorthand(request, modelClass) {\n var modelName = this.shorthand;\n var camelizedModelName = camelize(modelName);\n assert(modelClass, \"The route handler for \".concat(request.url, \" is trying to access the \").concat(camelizedModelName, \" model, but that model doesn't exist.\"));\n\n var id = this._getIdForRequest(request);\n\n if (id) {\n var model = modelClass.find(id);\n\n if (!model) {\n return new Response(404);\n } else {\n return model;\n }\n } else if (this.options.coalesce) {\n var ids = this.serializerOrRegistry.getCoalescedIds(request, camelizedModelName);\n\n if (ids) {\n return modelClass.find(ids);\n }\n }\n\n return modelClass.all();\n }\n /*\n Retrieve an array of collections from the db.\n Ex: this.get('/home', ['contacts', 'pictures']);\n */\n\n }, {\n key: \"handleArrayShorthand\",\n value: function handleArrayShorthand(request, modelClasses) {\n var keys = this.shorthand;\n\n var id = this._getIdForRequest(request);\n /*\n If the first key is singular and we have an id param in\n the request, we're dealing with the version of the shorthand\n that has a parent model and several has-many relationships.\n We throw an error, because the serializer is the appropriate\n place for this now.\n */\n\n\n assert(!id || this._container.inflector.singularize(keys[0]) !== keys[0], \"It looks like you're using the \\\"Single record with\\n related records\\\" version of the array shorthand, in addition to opting\\n in to the model layer. This shorthand was made when there was no\\n serializer layer. Now that you're using models, please ensure your\\n relationships are defined, and create a serializer for the parent\\n model, adding the relationships there.\");\n return modelClasses.map(function (modelClass) {\n return modelClass.all();\n });\n }\n }]);\n\n return GetShorthandRouteHandler;\n}(BaseShorthandRouteHandler);\n/**\n * @hide\n */\n\n\nvar PostShorthandRouteHandler = /*#__PURE__*/function (_BaseShorthandRouteHa) {\n _inherits(PostShorthandRouteHandler, _BaseShorthandRouteHa);\n\n var _super = _createSuper(PostShorthandRouteHandler);\n\n function PostShorthandRouteHandler() {\n _classCallCheck(this, PostShorthandRouteHandler);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(PostShorthandRouteHandler, [{\n key: \"handleStringShorthand\",\n value:\n /*\n Push a new model of type *camelizedModelName* to the db.\n For example, this will push a 'user':\n this.post('/contacts', 'user');\n */\n function handleStringShorthand(request, modelClass) {\n var modelName = this.shorthand;\n var camelizedModelName = camelize(modelName);\n assert(modelClass, \"The route handler for \".concat(request.url, \" is trying to access the \").concat(camelizedModelName, \" model, but that model doesn't exist.\"));\n\n var attrs = this._getAttrsForRequest(request, modelClass.camelizedModelName);\n\n return modelClass.create(attrs);\n }\n }]);\n\n return PostShorthandRouteHandler;\n}(BaseShorthandRouteHandler);\n/**\n * @hide\n */\n\n\nvar PutShorthandRouteHandler = /*#__PURE__*/function (_BaseShorthandRouteHa) {\n _inherits(PutShorthandRouteHandler, _BaseShorthandRouteHa);\n\n var _super = _createSuper(PutShorthandRouteHandler);\n\n function PutShorthandRouteHandler() {\n _classCallCheck(this, PutShorthandRouteHandler);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(PutShorthandRouteHandler, [{\n key: \"handleStringShorthand\",\n value:\n /*\n Update an object from the db, specifying the type.\n this.put('/contacts/:id', 'user');\n */\n function handleStringShorthand(request, modelClass) {\n var modelName = this.shorthand;\n var camelizedModelName = camelize(modelName);\n assert(modelClass, \"The route handler for \".concat(request.url, \" is trying to access the \").concat(camelizedModelName, \" model, but that model doesn't exist.\"));\n\n var id = this._getIdForRequest(request);\n\n var model = modelClass.find(id);\n\n if (!model) {\n return new Response(404);\n }\n\n var attrs = this._getAttrsForRequest(request, modelClass.camelizedModelName);\n\n return model.update(attrs);\n }\n }]);\n\n return PutShorthandRouteHandler;\n}(BaseShorthandRouteHandler);\n/**\n * @hide\n */\n\n\nvar DeleteShorthandRouteHandler = /*#__PURE__*/function (_BaseShorthandRouteHa) {\n _inherits(DeleteShorthandRouteHandler, _BaseShorthandRouteHa);\n\n var _super = _createSuper(DeleteShorthandRouteHandler);\n\n function DeleteShorthandRouteHandler() {\n _classCallCheck(this, DeleteShorthandRouteHandler);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(DeleteShorthandRouteHandler, [{\n key: \"handleStringShorthand\",\n value:\n /*\n Remove the model from the db of type *camelizedModelName*.\n This would remove the user with id :id:\n Ex: this.del('/contacts/:id', 'user');\n */\n function handleStringShorthand(request, modelClass) {\n var modelName = this.shorthand;\n var camelizedModelName = camelize(modelName);\n assert(modelClass, \"The route handler for \".concat(request.url, \" is trying to access the \").concat(camelizedModelName, \" model, but that model doesn't exist.\"));\n\n var id = this._getIdForRequest(request);\n\n var model = modelClass.find(id);\n\n if (!model) {\n return new Response(404);\n }\n\n model.destroy();\n }\n /*\n Remove the model and child related models from the db.\n This would remove the contact with id `:id`, as well\n as this contact's addresses and phone numbers.\n Ex: this.del('/contacts/:id', ['contact', 'addresses', 'numbers');\n */\n\n }, {\n key: \"handleArrayShorthand\",\n value: function handleArrayShorthand(request, modelClasses) {\n var _this = this;\n\n var id = this._getIdForRequest(request);\n\n var parent = modelClasses[0].find(id);\n var childTypes = modelClasses.slice(1).map(function (modelClass) {\n return _this._container.inflector.pluralize(modelClass.camelizedModelName);\n }); // Delete related children\n\n childTypes.forEach(function (type) {\n return parent[type].destroy();\n });\n parent.destroy();\n }\n }]);\n\n return DeleteShorthandRouteHandler;\n}(BaseShorthandRouteHandler);\n/**\n * @hide\n */\n\n\nvar HeadShorthandRouteHandler = /*#__PURE__*/function (_BaseShorthandRouteHa) {\n _inherits(HeadShorthandRouteHandler, _BaseShorthandRouteHa);\n\n var _super = _createSuper(HeadShorthandRouteHandler);\n\n function HeadShorthandRouteHandler() {\n _classCallCheck(this, HeadShorthandRouteHandler);\n\n return _super.apply(this, arguments);\n }\n\n _createClass(HeadShorthandRouteHandler, [{\n key: \"handleStringShorthand\",\n value:\n /*\n Retrieve a model/collection from the db.\n Examples:\n this.head('/contacts', 'contact');\n this.head('/contacts/:id', 'contact');\n */\n function handleStringShorthand(request, modelClass) {\n var modelName = this.shorthand;\n var camelizedModelName = camelize(modelName);\n assert(modelClass, \"The route handler for \".concat(request.url, \" is trying to access the \").concat(camelizedModelName, \" model, but that model doesn't exist.\"));\n\n var id = this._getIdForRequest(request);\n\n if (id) {\n var model = modelClass.find(id);\n\n if (!model) {\n return new Response(404);\n } else {\n return new Response(204);\n }\n } else if (this.options.coalesce && request.queryParams && request.queryParams.ids) {\n var _model = modelClass.find(request.queryParams.ids);\n\n if (!_model) {\n return new Response(404);\n } else {\n return new Response(204);\n }\n } else {\n return new Response(204);\n }\n }\n }]);\n\n return HeadShorthandRouteHandler;\n}(BaseShorthandRouteHandler);\n\nvar DEFAULT_CODES = {\n get: 200,\n put: 204,\n post: 201,\n \"delete\": 204\n};\n\nfunction createHandler(_ref) {\n var verb = _ref.verb,\n schema = _ref.schema,\n serializerOrRegistry = _ref.serializerOrRegistry,\n path = _ref.path,\n rawHandler = _ref.rawHandler,\n options = _ref.options;\n var handler;\n var args = [schema, serializerOrRegistry, rawHandler, path, options];\n\n var type = _typeof(rawHandler);\n\n if (type === \"function\") {\n handler = _construct(FunctionRouteHandler, args);\n } else if (type === \"object\" && rawHandler) {\n handler = _construct(ObjectRouteHandler, args);\n } else if (verb === \"get\") {\n handler = _construct(GetShorthandRouteHandler, args);\n } else if (verb === \"post\") {\n handler = _construct(PostShorthandRouteHandler, args);\n } else if (verb === \"put\" || verb === \"patch\") {\n handler = _construct(PutShorthandRouteHandler, args);\n } else if (verb === \"delete\") {\n handler = _construct(DeleteShorthandRouteHandler, args);\n } else if (verb === \"head\") {\n handler = _construct(HeadShorthandRouteHandler, args);\n }\n\n return handler;\n}\n/**\n * @hide\n */\n\n\nvar RouteHandler = /*#__PURE__*/function () {\n function RouteHandler(_ref2) {\n var schema = _ref2.schema,\n verb = _ref2.verb,\n rawHandler = _ref2.rawHandler,\n customizedCode = _ref2.customizedCode,\n options = _ref2.options,\n path = _ref2.path,\n serializerOrRegistry = _ref2.serializerOrRegistry;\n\n _classCallCheck(this, RouteHandler);\n\n this.verb = verb;\n this.customizedCode = customizedCode;\n this.serializerOrRegistry = serializerOrRegistry;\n this.handler = createHandler({\n verb: verb,\n schema: schema,\n path: path,\n serializerOrRegistry: serializerOrRegistry,\n rawHandler: rawHandler,\n options: options\n });\n }\n\n _createClass(RouteHandler, [{\n key: \"handle\",\n value: function handle(request) {\n var _this = this;\n\n return this._getMirageResponseForRequest(request).then(function (mirageResponse) {\n return _this.serialize(mirageResponse, request);\n }).then(function (serializedMirageResponse) {\n return serializedMirageResponse.toRackResponse();\n });\n }\n }, {\n key: \"_getMirageResponseForRequest\",\n value: function _getMirageResponseForRequest(request) {\n var result;\n\n try {\n /*\n We need to do this for the #serialize convenience method. Probably is\n a better way.\n */\n if (this.handler instanceof FunctionRouteHandler) {\n this.handler.setRequest(request);\n }\n\n result = this.handler.handle(request);\n } catch (e) {\n if (e instanceof MirageError) {\n result = new Response(500, {}, e);\n } else {\n var message = e.message || e;\n result = new Response(500, {}, {\n message: message,\n stack: \"Mirage: Your \".concat(request.method, \" handler for the url \").concat(request.url, \" threw an error:\\n\\n\").concat(e.stack || e)\n });\n }\n }\n\n return this._toMirageResponse(result);\n }\n }, {\n key: \"_toMirageResponse\",\n value: function _toMirageResponse(result) {\n var _this2 = this;\n\n var mirageResponse;\n return new Promise(function (resolve, reject) {\n Promise.resolve(result).then(function (response) {\n if (response instanceof Response) {\n mirageResponse = result;\n } else {\n var code = _this2._getCodeForResponse(response);\n\n mirageResponse = new Response(code, {}, response);\n }\n\n resolve(mirageResponse);\n })[\"catch\"](reject);\n });\n }\n }, {\n key: \"_getCodeForResponse\",\n value: function _getCodeForResponse(response) {\n var code;\n\n if (this.customizedCode) {\n code = this.customizedCode;\n } else {\n code = DEFAULT_CODES[this.verb]; // Returning any data for a 204 is invalid\n\n if (code === 204 && response !== undefined && response !== \"\") {\n code = 200;\n }\n }\n\n return code;\n }\n }, {\n key: \"serialize\",\n value: function serialize(mirageResponse, request) {\n mirageResponse.data = this.serializerOrRegistry.serialize(mirageResponse.data, request);\n return mirageResponse;\n }\n }]);\n\n return RouteHandler;\n}();\n/**\n @hide\n*/\n\n\nfunction extend(protoProps, staticProps) {\n var Child = /*#__PURE__*/function (_this) {\n _inherits(Child, _this);\n\n var _super = _createSuper(Child);\n\n function Child() {\n var _this2;\n\n _classCallCheck(this, Child);\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this2 = _super.call.apply(_super, [this].concat(args)); // The constructor function for the new subclass is optionally defined by you\n // in your `extend` definition\n\n if (protoProps && has(protoProps, \"constructor\")) {\n var _protoProps$construct;\n\n (_protoProps$construct = protoProps.constructor).call.apply(_protoProps$construct, [_assertThisInitialized(_this2)].concat(args));\n }\n\n return _this2;\n }\n\n return Child;\n }(this); // Add static properties to the constructor function, if supplied.\n\n\n Object.assign(Child, this, staticProps); // Add prototype properties (instance properties) to the subclass,\n // if supplied.\n\n if (protoProps) {\n Object.assign(Child.prototype, protoProps);\n }\n\n return Child;\n}\n/**\n Models wrap your database, and allow you to define relationships.\n\n **Class vs. instance methods**\n\n The methods documented below apply to _instances_ of models, but you'll typically use the `Schema` to access the model _class_, which can be used to find or create instances.\n\n You can find the Class methods documented under the `Schema` API docs.\n\n **Accessing properties and relationships**\n\n You can access properites (fields) and relationships directly off of models.\n\n ```js\n user.name; // 'Sam'\n user.team; // Team model\n user.teamId; // Team id (foreign key)\n ```\n\n Mirage Models are schemaless in their attributes, but their relationship schema is known.\n\n For example,\n\n ```js\n let user = schema.users.create();\n user.attrs // { }\n user.name // undefined\n\n let user = schema.users.create({ name: 'Sam' });\n user.attrs // { name: 'Sam' }\n user.name // 'Sam'\n ```\n\n However, if a `user` has a `posts` relationships defined,\n\n ```js\n let user = schema.users.create();\n user.posts // returns an empty Posts Collection\n ```\n\n @class Model\n @constructor\n @public\n */\n\n\nvar Model = /*#__PURE__*/function () {\n // TODO: schema and modelName now set statically at registration, need to remove\n\n /*\n Notes:\n - We need to pass in modelName, because models are created with\n .extend and anonymous functions, so you cannot use\n reflection to find the name of the constructor.\n */\n function Model(schema, modelName, attrs, fks) {\n var _this = this;\n\n _classCallCheck(this, Model);\n\n assert(schema, \"A model requires a schema\");\n assert(modelName, \"A model requires a modelName\");\n this._schema = schema;\n this.modelName = modelName;\n this.fks = fks || [];\n /**\n Returns the attributes of your model.\n ```js\n let post = schema.blogPosts.find(1);\n post.attrs; // {id: 1, title: 'Lorem Ipsum', publishedAt: '2012-01-01 10:00:00'}\n ```\n Note that you can also access individual attributes directly off a model, e.g. `post.title`.\n @property attrs\n @public\n */\n\n this.attrs = {};\n attrs = attrs || {}; // Ensure fks are there\n\n this.fks.forEach(function (fk) {\n _this.attrs[fk] = attrs[fk] !== undefined ? attrs[fk] : null;\n });\n Object.keys(attrs).forEach(function (name) {\n var value = attrs[name];\n\n _this._validateAttr(name, value);\n\n _this._setupAttr(name, value);\n\n _this._setupRelationship(name, value);\n });\n return this;\n }\n /**\n Create or saves the model.\n ```js\n let post = blogPosts.new({ title: 'Lorem ipsum' });\n post.id; // null\n post.save();\n post.id; // 1\n post.title = 'Hipster ipsum'; // db has not been updated\n post.save(); // ...now the db is updated\n ```\n @method save\n @return this\n @public\n */\n\n\n _createClass(Model, [{\n key: \"save\",\n value: function save() {\n var collection = this._schema.toInternalCollectionName(this.modelName);\n\n if (this.isNew()) {\n // Update the attrs with the db response\n this.attrs = this._schema.db[collection].insert(this.attrs); // Ensure the id getter/setter is set\n\n this._definePlainAttribute(\"id\");\n } else {\n this._schema.isSaving[this.toString()] = true;\n\n this._schema.db[collection].update(this.attrs.id, this.attrs);\n }\n\n this._saveAssociations();\n\n this._schema.isSaving[this.toString()] = false;\n return this;\n }\n /**\n Updates the record in the db.\n ```js\n let post = blogPosts.find(1);\n post.update('title', 'Hipster ipsum'); // the db was updated\n post.update({\n title: 'Lorem ipsum',\n created_at: 'before it was cool'\n });\n ```\n @method update\n @param {String} key\n @param {String} val\n @return this\n @public\n */\n\n }, {\n key: \"update\",\n value: function update(key, val) {\n var attrs;\n\n if (key == null) {\n return this;\n }\n\n if (_typeof(key) === \"object\") {\n attrs = key;\n } else {\n (attrs = {})[key] = val;\n }\n\n Object.keys(attrs).forEach(function (attr) {\n if (!this.associationKeys.has(attr) && !this.associationIdKeys.has(attr)) {\n this._definePlainAttribute(attr);\n }\n\n this[attr] = attrs[attr];\n }, this);\n this.save();\n return this;\n }\n /**\n Destroys the db record.\n ```js\n let post = blogPosts.find(1);\n post.destroy(); // removed from the db\n ```\n @method destroy\n @public\n */\n\n }, {\n key: \"destroy\",\n value: function destroy() {\n if (this.isSaved()) {\n this._disassociateFromDependents();\n\n var collection = this._schema.toInternalCollectionName(this.modelName);\n\n this._schema.db[collection].remove(this.attrs.id);\n }\n }\n /**\n Boolean, true if the model has not been persisted yet to the db.\n ```js\n let post = blogPosts.new({title: 'Lorem ipsum'});\n post.isNew(); // true\n post.id; // null\n post.save(); // true\n post.isNew(); // false\n post.id; // 1\n ```\n @method isNew\n @return {Boolean}\n @public\n */\n\n }, {\n key: \"isNew\",\n value: function isNew() {\n var hasDbRecord = false;\n var hasId = this.attrs.id !== undefined && this.attrs.id !== null;\n\n if (hasId) {\n var collectionName = this._schema.toInternalCollectionName(this.modelName);\n\n var record = this._schema.db[collectionName].find(this.attrs.id);\n\n if (record) {\n hasDbRecord = true;\n }\n }\n\n return !hasDbRecord;\n }\n /**\n Boolean, opposite of `isNew`\n @method isSaved\n @return {Boolean}\n @public\n */\n\n }, {\n key: \"isSaved\",\n value: function isSaved() {\n return !this.isNew();\n }\n /**\n Reload a model's data from the database.\n ```js\n let post = blogPosts.find(1);\n post.attrs; // {id: 1, title: 'Lorem ipsum'}\n post.title = 'Hipster ipsum';\n post.title; // 'Hipster ipsum';\n post.reload(); // true\n post.title; // 'Lorem ipsum'\n ```\n @method reload\n @return this\n @public\n */\n\n }, {\n key: \"reload\",\n value: function reload() {\n if (this.id) {\n var collection = this._schema.toInternalCollectionName(this.modelName);\n\n var attrs = this._schema.db[collection].find(this.id);\n\n Object.keys(attrs).filter(function (attr) {\n return attr !== \"id\";\n }).forEach(function (attr) {\n this.attrs[attr] = attrs[attr];\n }, this);\n } // Clear temp associations\n\n\n this._tempAssociations = {};\n return this;\n }\n }, {\n key: \"toJSON\",\n value: function toJSON() {\n return _objectSpread2({}, this.attrs);\n }\n /**\n Returns a hash of this model's associations.\n ```js\n let server = createServer({\n models: {\n user: Model,\n post: Model.extend({\n user: belongsTo(),\n comments: hasMany()\n }),\n comment: Model\n },\n seeds(server) {\n let peter = server.create(\"user\", { name: \"Peter\" });\n server.create(\"post\", { user: peter });\n }\n });\n let post = server.schema.posts.find(1)\n post.associations\n // {\n // user: BelongsToAssociation,\n // comments: HasManyAssociation\n // }\n ```\n Check out the docs on the Association class to see what fields are available for each association.\n @method associations\n @type {Object}\n @public\n */\n\n }, {\n key: \"associations\",\n get: function get() {\n return this._schema.associationsFor(this.modelName);\n }\n /**\n Returns the association for the given key\n @method associationFor\n @param key\n @public\n @hide\n */\n\n }, {\n key: \"associationFor\",\n value: function associationFor(key) {\n return this.associations[key];\n }\n /**\n Returns this model's inverse association for the given\n model-type-association pair, if it exists.\n Example:\n post: Model.extend({\n comments: hasMany()\n }),\n comments: Model.extend({\n post: belongsTo()\n })\n post.inversefor(commentsPostAssociation) would return the\n `post.comments` association object.\n Originally we had association.inverse() but that became impossible with\n the addition of polymorphic models. Consider the following:\n post: Model.extend({\n comments: hasMany()\n }),\n picture: Model.extend({\n comments: hasMany()\n }),\n comments: Model.extend({\n commentable: belongsTo({ polymorphic: true })\n })\n `commentable.inverse()` is ambiguous - does it return\n `post.comments` or `picture.comments`? Instead we need to ask each model\n if it has an inverse for a given association. post.inverseFor(commentable)\n is no longer ambiguous.\n @method hasInverseFor\n @param {String} modelName The model name of the class we're scanning\n @param {ORM/Association} association\n @return {ORM/Association}\n @public\n @hide\n */\n\n }, {\n key: \"inverseFor\",\n value: function inverseFor(association) {\n return this._explicitInverseFor(association) || this._implicitInverseFor(association);\n }\n /**\n Finds the inverse for an association that explicity defines it's inverse\n @private\n @hide\n */\n\n }, {\n key: \"_explicitInverseFor\",\n value: function _explicitInverseFor(association) {\n this._checkForMultipleExplicitInverses(association);\n\n var associations = this._schema.associationsFor(this.modelName);\n\n var inverse = association.opts.inverse;\n var candidate = inverse ? associations[inverse] : null;\n var matchingPolymorphic = candidate && candidate.isPolymorphic;\n var matchingInverse = candidate && candidate.modelName === association.ownerModelName;\n var candidateInverse = candidate && candidate.opts.inverse;\n\n if (candidateInverse && candidate.opts.inverse !== association.name) {\n assert(false, \"You specified an inverse of \".concat(inverse, \" for \").concat(association.name, \", but it does not match \").concat(candidate.modelName, \" \").concat(candidate.name, \"'s inverse\"));\n }\n\n return matchingPolymorphic || matchingInverse ? candidate : null;\n }\n /**\n Ensures multiple explicit inverses don't exist on the current model\n for the given association.\n TODO: move this to compile-time check\n @private\n @hide\n */\n\n }, {\n key: \"_checkForMultipleExplicitInverses\",\n value: function _checkForMultipleExplicitInverses(association) {\n var associations = this._schema.associationsFor(this.modelName);\n\n var matchingExplicitInverses = Object.keys(associations).filter(function (key) {\n var candidate = associations[key];\n var modelMatches = association.ownerModelName === candidate.modelName;\n var inverseKeyMatches = association.name === candidate.opts.inverse;\n return modelMatches && inverseKeyMatches;\n });\n assert(matchingExplicitInverses.length <= 1, \"The \".concat(this.modelName, \" model has defined multiple explicit inverse associations for the \").concat(association.ownerModelName, \".\").concat(association.name, \" association.\"));\n }\n /**\n Finds if there is an inverse for an association that does not\n explicitly define one.\n @private\n @hide\n */\n\n }, {\n key: \"_implicitInverseFor\",\n value: function _implicitInverseFor(association) {\n var _this2 = this;\n\n var associations = this._schema.associationsFor(this.modelName);\n\n var modelName = association.ownerModelName;\n return values(associations).filter(function (candidate) {\n return candidate.modelName === modelName;\n }).reduce(function (inverse, candidate) {\n var candidateInverse = candidate.opts.inverse;\n var candidateIsImplicitInverse = candidateInverse === undefined;\n var candidateIsExplicitInverse = candidateInverse === association.name;\n var candidateMatches = candidateIsImplicitInverse || candidateIsExplicitInverse;\n\n if (candidateMatches) {\n // Need to move this check to compile-time init\n assert(!inverse, \"The \".concat(_this2.modelName, \" model has multiple possible inverse associations for the \").concat(association.ownerModelName, \".\").concat(association.name, \" association.\"));\n inverse = candidate;\n }\n\n return inverse;\n }, null);\n }\n /**\n Returns whether this model has an inverse association for the given\n model-type-association pair.\n @method hasInverseFor\n @param {String} modelName\n @param {ORM/Association} association\n @return {Boolean}\n @public\n @hide\n */\n\n }, {\n key: \"hasInverseFor\",\n value: function hasInverseFor(association) {\n return !!this.inverseFor(association);\n }\n /**\n Used to check if models match each other. If models are saved, we check model type\n and id, since they could have other non-persisted properties that are different.\n @public\n @hide\n */\n\n }, {\n key: \"alreadyAssociatedWith\",\n value: function alreadyAssociatedWith(model, association) {\n var associatedModelOrCollection = this[association.name];\n\n if (associatedModelOrCollection && model) {\n if (associatedModelOrCollection instanceof Model) {\n if (associatedModelOrCollection.isSaved() && model.isSaved()) {\n return associatedModelOrCollection.toString() === model.toString();\n } else {\n return associatedModelOrCollection === model;\n }\n } else {\n return associatedModelOrCollection.includes(model);\n }\n }\n }\n }, {\n key: \"associate\",\n value: function associate(model, association) {\n if (this.alreadyAssociatedWith(model, association)) {\n return;\n }\n\n var name = association.name;\n\n if (association instanceof HasMany) {\n if (!this[name].includes(model)) {\n this[name].add(model);\n }\n } else {\n this[name] = model;\n }\n }\n }, {\n key: \"disassociate\",\n value: function disassociate(model, association) {\n var fk = association.getForeignKey();\n\n if (association instanceof HasMany) {\n var i;\n\n if (association.isPolymorphic) {\n var found = this[fk].find(function (_ref) {\n var type = _ref.type,\n id = _ref.id;\n return type === model.modelName && id === model.id;\n });\n i = found && this[fk].indexOf(found);\n } else {\n i = this[fk].map(function (key) {\n return key.toString();\n }).indexOf(model.id.toString());\n }\n\n if (i > -1) {\n this.attrs[fk].splice(i, 1);\n }\n } else {\n this.attrs[fk] = null;\n }\n }\n /**\n @hide\n */\n\n }, {\n key: \"isSaving\",\n get: function get() {\n return this._schema.isSaving[this.toString()];\n } // Private\n\n /**\n model.attrs represents the persistable attributes, i.e. your db\n table fields.\n @method _setupAttr\n @param attr\n @param value\n @private\n @hide\n */\n\n }, {\n key: \"_setupAttr\",\n value: function _setupAttr(attr, value) {\n var isAssociation = this.associationKeys.has(attr) || this.associationIdKeys.has(attr);\n\n if (!isAssociation) {\n this.attrs[attr] = value; // define plain getter/setters for non-association keys\n\n this._definePlainAttribute(attr);\n }\n }\n /**\n Define getter/setter for a plain attribute\n @method _definePlainAttribute\n @param attr\n @private\n @hide\n */\n\n }, {\n key: \"_definePlainAttribute\",\n value: function _definePlainAttribute(attr) {\n // Ensure the property hasn't already been defined\n var existingProperty = Object.getOwnPropertyDescriptor(this, attr);\n\n if (existingProperty && existingProperty.get) {\n return;\n } // Ensure the attribute is on the attrs hash\n\n\n if (!Object.prototype.hasOwnProperty.call(this.attrs, attr)) {\n this.attrs[attr] = null;\n } // Define the getter/setter\n\n\n Object.defineProperty(this, attr, {\n get: function get() {\n return this.attrs[attr];\n },\n set: function set(val) {\n this.attrs[attr] = val;\n }\n });\n }\n /**\n Foreign keys get set on attrs directly (to avoid potential recursion), but\n model references use the setter.\n *\n We validate foreign keys during instantiation.\n *\n @method _setupRelationship\n @param attr\n @param value\n @private\n @hide\n */\n\n }, {\n key: \"_setupRelationship\",\n value: function _setupRelationship(attr, value) {\n var isFk = this.associationIdKeys.has(attr) || this.fks.includes(attr);\n var isAssociation = this.associationKeys.has(attr);\n\n if (isFk) {\n if (value !== undefined && value !== null) {\n this._validateForeignKeyExistsInDatabase(attr, value);\n }\n\n this.attrs[attr] = value;\n }\n\n if (isAssociation) {\n this[attr] = value;\n }\n }\n /**\n @method _validateAttr\n @private\n @hide\n */\n\n }, {\n key: \"_validateAttr\",\n value: function _validateAttr(key, value) {\n // Verify attr passed in for associations is actually an association\n {\n if (this.associationKeys.has(key)) {\n var association = this.associationFor(key);\n var isNull = value === null;\n\n if (association instanceof HasMany) {\n var isCollection = value instanceof Collection || value instanceof PolymorphicCollection;\n var isArrayOfModels = Array.isArray(value) && value.every(function (item) {\n return item instanceof Model;\n });\n assert(isCollection || isArrayOfModels || isNull, \"You're trying to create a \".concat(this.modelName, \" model and you passed in \\\"\").concat(value, \"\\\" under the \").concat(key, \" key, but that key is a HasMany relationship. You must pass in a Collection, PolymorphicCollection, array of Models, or null.\"));\n } else if (association instanceof BelongsTo) {\n assert(value instanceof Model || isNull, \"You're trying to create a \".concat(this.modelName, \" model and you passed in \\\"\").concat(value, \"\\\" under the \").concat(key, \" key, but that key is a BelongsTo relationship. You must pass in a Model or null.\"));\n }\n }\n } // Verify attrs passed in for association foreign keys are actually fks\n\n {\n if (this.associationIdKeys.has(key)) {\n if (key.endsWith(\"Ids\")) {\n var isArray = Array.isArray(value);\n\n var _isNull = value === null;\n\n assert(isArray || _isNull, \"You're trying to create a \".concat(this.modelName, \" model and you passed in \\\"\").concat(value, \"\\\" under the \").concat(key, \" key, but that key is a foreign key for a HasMany relationship. You must pass in an array of ids or null.\"));\n }\n }\n } // Verify no undefined associations are passed in\n\n {\n var isModelOrCollection = value instanceof Model || value instanceof Collection || value instanceof PolymorphicCollection;\n\n var _isArrayOfModels = Array.isArray(value) && value.length && value.every(function (item) {\n return item instanceof Model;\n });\n\n if (isModelOrCollection || _isArrayOfModels) {\n var modelOrCollection = value;\n assert(this.associationKeys.has(key), \"You're trying to create a \".concat(this.modelName, \" model and you passed in a \").concat(modelOrCollection.toString(), \" under the \").concat(key, \" key, but you haven't defined that key as an association on your model.\"));\n }\n }\n }\n /**\n Originally we validated this via association.setId method, but it triggered\n recursion. That method is designed for updating an existing model's ID so\n this method is needed during instantiation.\n *\n @method _validateForeignKeyExistsInDatabase\n @private\n @hide\n */\n\n }, {\n key: \"_validateForeignKeyExistsInDatabase\",\n value: function _validateForeignKeyExistsInDatabase(foreignKeyName, foreignKeys) {\n var _this3 = this;\n\n if (Array.isArray(foreignKeys)) {\n var association = this.hasManyAssociationFks[foreignKeyName];\n var found;\n\n if (association.isPolymorphic) {\n found = foreignKeys.map(function (_ref2) {\n var type = _ref2.type,\n id = _ref2.id;\n return _this3._schema.db[_this3._schema.toInternalCollectionName(type)].find(id);\n });\n found = compact(found);\n } else {\n found = this._schema.db[this._schema.toInternalCollectionName(association.modelName)].find(foreignKeys);\n }\n\n var foreignKeyLabel = association.isPolymorphic ? foreignKeys.map(function (fk) {\n return \"\".concat(fk.type, \":\").concat(fk.id);\n }).join(\",\") : foreignKeys;\n assert(found.length === foreignKeys.length, \"You're instantiating a \".concat(this.modelName, \" that has a \").concat(foreignKeyName, \" of \").concat(foreignKeyLabel, \", but some of those records don't exist in the database.\"));\n } else {\n var _association = this.belongsToAssociationFks[foreignKeyName];\n\n var _found;\n\n if (_association.isPolymorphic) {\n _found = this._schema.db[this._schema.toInternalCollectionName(foreignKeys.type)].find(foreignKeys.id);\n } else {\n _found = this._schema.db[this._schema.toInternalCollectionName(_association.modelName)].find(foreignKeys);\n }\n\n var _foreignKeyLabel = _association.isPolymorphic ? \"\".concat(foreignKeys.type, \":\").concat(foreignKeys.id) : foreignKeys;\n\n assert(_found, \"You're instantiating a \".concat(this.modelName, \" that has a \").concat(foreignKeyName, \" of \").concat(_foreignKeyLabel, \", but that record doesn't exist in the database.\"));\n }\n }\n /**\n Update associated children when saving a collection\n *\n @method _saveAssociations\n @private\n @hide\n */\n\n }, {\n key: \"_saveAssociations\",\n value: function _saveAssociations() {\n this._saveBelongsToAssociations();\n\n this._saveHasManyAssociations();\n }\n }, {\n key: \"_saveBelongsToAssociations\",\n value: function _saveBelongsToAssociations() {\n var _this4 = this;\n\n values(this.belongsToAssociations).forEach(function (association) {\n _this4._disassociateFromOldInverses(association);\n\n _this4._saveNewAssociates(association);\n\n _this4._associateWithNewInverses(association);\n });\n }\n }, {\n key: \"_saveHasManyAssociations\",\n value: function _saveHasManyAssociations() {\n var _this5 = this;\n\n values(this.hasManyAssociations).forEach(function (association) {\n _this5._disassociateFromOldInverses(association);\n\n _this5._saveNewAssociates(association);\n\n _this5._associateWithNewInverses(association);\n });\n }\n }, {\n key: \"_disassociateFromOldInverses\",\n value: function _disassociateFromOldInverses(association) {\n if (association instanceof HasMany) {\n this._disassociateFromHasManyInverses(association);\n } else if (association instanceof BelongsTo) {\n this._disassociateFromBelongsToInverse(association);\n }\n } // Disassociate currently persisted models that are no longer associated\n\n }, {\n key: \"_disassociateFromHasManyInverses\",\n value: function _disassociateFromHasManyInverses(association) {\n var _this6 = this;\n\n var fk = association.getForeignKey();\n var tempAssociation = this._tempAssociations && this._tempAssociations[association.name];\n var associateIds = this.attrs[fk];\n\n if (tempAssociation && associateIds) {\n var models;\n\n if (association.isPolymorphic) {\n models = associateIds.map(function (_ref3) {\n var type = _ref3.type,\n id = _ref3.id;\n return _this6._schema[_this6._schema.toCollectionName(type)].find(id);\n });\n } else {\n // TODO: prob should initialize hasMany fks with []\n models = this._schema[this._schema.toCollectionName(association.modelName)].find(associateIds || []).models;\n }\n\n models.filter(function (associate) {\n return (// filter out models that are already being saved\n !associate.isSaving && // filter out models that will still be associated\n !tempAssociation.includes(associate) && associate.hasInverseFor(association)\n );\n }).forEach(function (associate) {\n var inverse = associate.inverseFor(association);\n associate.disassociate(_this6, inverse);\n associate.save();\n });\n }\n }\n /*\n Disassociate currently persisted models that are no longer associated.\n Example:\n post: Model.extend({\n comments: hasMany()\n }),\n comment: Model.extend({\n post: belongsTo()\n })\n Assume `this` is comment:1. When saving, if comment:1 is no longer\n associated with post:1, we need to remove comment:1 from post:1.comments.\n In this example `association` would be `comment.post`.\n */\n\n }, {\n key: \"_disassociateFromBelongsToInverse\",\n value: function _disassociateFromBelongsToInverse(association) {\n var fk = association.getForeignKey();\n var tempAssociation = this._tempAssociations && this._tempAssociations[association.name];\n var associateId = this.attrs[fk];\n\n if (tempAssociation !== undefined && associateId) {\n var associate;\n\n if (association.isPolymorphic) {\n associate = this._schema[this._schema.toCollectionName(associateId.type)].find(associateId.id);\n } else {\n associate = this._schema[this._schema.toCollectionName(association.modelName)].find(associateId);\n }\n\n if (associate.hasInverseFor(association)) {\n var inverse = associate.inverseFor(association);\n associate.disassociate(this, inverse);\n\n associate._updateInDb(associate.attrs);\n }\n }\n } // Find all other models that depend on me and update their foreign keys\n\n }, {\n key: \"_disassociateFromDependents\",\n value: function _disassociateFromDependents() {\n var _this7 = this;\n\n this._schema.dependentAssociationsFor(this.modelName).forEach(function (association) {\n association.disassociateAllDependentsFromTarget(_this7);\n });\n }\n }, {\n key: \"_saveNewAssociates\",\n value: function _saveNewAssociates(association) {\n var fk = association.getForeignKey();\n var tempAssociate = this._tempAssociations && this._tempAssociations[association.name];\n\n if (tempAssociate !== undefined) {\n this.__isSavingNewChildren = true;\n delete this._tempAssociations[association.name];\n\n if (tempAssociate instanceof Collection) {\n tempAssociate.models.filter(function (model) {\n return !model.isSaving;\n }).forEach(function (child) {\n child.save();\n });\n\n this._updateInDb(_defineProperty({}, fk, tempAssociate.models.map(function (child) {\n return child.id;\n })));\n } else if (tempAssociate instanceof PolymorphicCollection) {\n tempAssociate.models.filter(function (model) {\n return !model.isSaving;\n }).forEach(function (child) {\n child.save();\n });\n\n this._updateInDb(_defineProperty({}, fk, tempAssociate.models.map(function (child) {\n return {\n type: child.modelName,\n id: child.id\n };\n })));\n } else {\n // Clearing the association\n if (tempAssociate === null) {\n this._updateInDb(_defineProperty({}, fk, null)); // Self-referential\n\n } else if (this.equals(tempAssociate)) {\n this._updateInDb(_defineProperty({}, fk, this.id)); // Non-self-referential\n\n } else if (!tempAssociate.isSaving) {\n // Save the tempAssociate and update the local reference\n tempAssociate.save();\n\n this._syncTempAssociations(tempAssociate);\n\n var fkValue;\n\n if (association.isPolymorphic) {\n fkValue = {\n id: tempAssociate.id,\n type: tempAssociate.modelName\n };\n } else {\n fkValue = tempAssociate.id;\n }\n\n this._updateInDb(_defineProperty({}, fk, fkValue));\n }\n }\n\n this.__isSavingNewChildren = false;\n }\n }\n /*\n Step 3 in saving associations.\n Example:\n // initial state\n post.author = steinbeck;\n // new state\n post.author = twain;\n 1. Disassociate from old inverse (remove post from steinbeck.posts)\n 2. Save new associates (if twain.isNew, save twain)\n -> 3. Associate with new inverse (add post to twain.posts)\n */\n\n }, {\n key: \"_associateWithNewInverses\",\n value: function _associateWithNewInverses(association) {\n var _this8 = this;\n\n if (!this.__isSavingNewChildren) {\n var modelOrCollection = this[association.name];\n\n if (modelOrCollection instanceof Model) {\n this._associateModelWithInverse(modelOrCollection, association);\n } else if (modelOrCollection instanceof Collection || modelOrCollection instanceof PolymorphicCollection) {\n modelOrCollection.models.forEach(function (model) {\n _this8._associateModelWithInverse(model, association);\n });\n }\n\n delete this._tempAssociations[association.name];\n }\n }\n }, {\n key: \"_associateModelWithInverse\",\n value: function _associateModelWithInverse(model, association) {\n var _this9 = this;\n\n if (model.hasInverseFor(association)) {\n var inverse = model.inverseFor(association);\n var inverseFk = inverse.getForeignKey();\n var ownerId = this.id;\n\n if (inverse instanceof BelongsTo) {\n var newId;\n\n if (inverse.isPolymorphic) {\n newId = {\n type: this.modelName,\n id: ownerId\n };\n } else {\n newId = ownerId;\n }\n\n this._schema.db[this._schema.toInternalCollectionName(model.modelName)].update(model.id, _defineProperty({}, inverseFk, newId));\n } else {\n var inverseCollection = this._schema.db[this._schema.toInternalCollectionName(model.modelName)];\n\n var currentIdsForInverse = inverseCollection.find(model.id)[inverse.getForeignKey()] || [];\n var newIdsForInverse = Object.assign([], currentIdsForInverse);\n\n var _newId, alreadyAssociatedWith;\n\n if (inverse.isPolymorphic) {\n _newId = {\n type: this.modelName,\n id: ownerId\n };\n alreadyAssociatedWith = newIdsForInverse.some(function (key) {\n return key.type == _this9.modelName && key.id == ownerId;\n });\n } else {\n _newId = ownerId;\n alreadyAssociatedWith = newIdsForInverse.includes(ownerId);\n }\n\n if (!alreadyAssociatedWith) {\n newIdsForInverse.push(_newId);\n }\n\n inverseCollection.update(model.id, _defineProperty({}, inverseFk, newIdsForInverse));\n }\n }\n } // Used to update data directly, since #save and #update can retrigger saves,\n // which can cause cycles with associations.\n\n }, {\n key: \"_updateInDb\",\n value: function _updateInDb(attrs) {\n this.attrs = this._schema.db[this._schema.toInternalCollectionName(this.modelName)].update(this.attrs.id, attrs);\n }\n /*\n Super gnarly: after we save this tempAssociate, we we need to through\n all other tempAssociates for a reference to this same model, and\n update it. Otherwise those other references are stale, which could\n cause a bug when they are subsequently saved.\n This only works for belongsTo right now, should add hasMany logic to it.\n See issue #1613: https://github.com/samselikoff/ember-cli-mirage/pull/1613\n */\n\n }, {\n key: \"_syncTempAssociations\",\n value: function _syncTempAssociations(tempAssociate) {\n var _this10 = this;\n\n Object.keys(this._tempAssociations).forEach(function (key) {\n if (_this10._tempAssociations[key] && _this10._tempAssociations[key].toString() === tempAssociate.toString()) {\n _this10._tempAssociations[key] = tempAssociate;\n }\n });\n }\n /**\n Simple string representation of the model and id.\n ```js\n let post = blogPosts.find(1);\n post.toString(); // \"model:blogPost:1\"\n ```\n @method toString\n @return {String}\n @public\n */\n\n }, {\n key: \"toString\",\n value: function toString() {\n var idLabel = this.id ? \"(\".concat(this.id, \")\") : \"\";\n return \"model:\".concat(this.modelName).concat(idLabel);\n }\n /**\n Checks the equality of this model and the passed-in model\n *\n @method equals\n @return boolean\n @public\n @hide\n */\n\n }, {\n key: \"equals\",\n value: function equals(model) {\n return this.toString() === model.toString();\n }\n }]);\n\n return Model;\n}();\n\nModel.extend = extend;\n\nModel.findBelongsToAssociation = function (associationType) {\n return this.prototype.belongsToAssociations[associationType];\n};\n/**\n Serializers are responsible for formatting your route handler's response.\n\n The application serializer will apply to every response. To make specific customizations, define per-model serializers.\n\n ```js\n import { createServer, RestSerializer } from 'miragejs';\n\n createServer({\n serializers: {\n application: RestSerializer,\n user: RestSerializer.extend({\n // user-specific customizations\n })\n }\n })\n ```\n\n Any Model or Collection returned from a route handler will pass through the serializer layer. Highest priority will be given to a model-specific serializer, then the application serializer, then the default serializer.\n\n Mirage ships with three named serializers:\n\n - **JSONAPISerializer**, to simulate JSON:API compliant API servers:\n\n ```js\n import { createServer, JSONAPISerializer } from 'miragejs';\n\n createServer({\n serializers: {\n application: JSONAPISerializer\n }\n })\n ```\n\n - **ActiveModelSerializer**, to mock Rails APIs that use AMS-style responses:\n\n ```js\n import { createServer, ActiveModelSerializer } from 'miragejs';\n\n createServer({\n serializers: {\n application: ActiveModelSerializer\n }\n })\n ```\n\n - **RestSerializer**, a good starting point for many generic REST APIs:\n\n ```js\n import { createServer, RestSerializer } from 'miragejs';\n\n createServer({\n serializers: {\n application: RestSerializer\n }\n })\n ```\n\n Additionally, Mirage has a basic Serializer class which you can customize using the hooks documented below:\n\n ```js\n import { createServer, Serializer } from 'miragejs';\n\n createServer({\n serializers: {\n application: Serializer\n }\n })\n ```\n\n When writing model-specific serializers, remember to extend from your application serializer so shared logic is used by your model-specific classes:\n\n ```js\n import { createServer, Serializer } from 'miragejs';\n\n const ApplicationSerializer = Serializer.extend()\n\n createServer({\n serializers: {\n application: ApplicationSerializer,\n blogPost: ApplicationSerializer.extend({\n include: ['comments']\n })\n }\n })\n ```\n\n @class Serializer\n @constructor\n @public\n*/\n\n\nvar Serializer = /*#__PURE__*/function () {\n function Serializer(registry, type) {\n var request = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n _classCallCheck(this, Serializer);\n\n this.registry = registry;\n this.type = type;\n this.request = request;\n /**\n Use this property on a model serializer to whitelist attributes that will be used in your JSON payload.\n For example, if you had a `blog-post` model in your database that looked like\n ```\n {\n id: 1,\n title: 'Lorem ipsum',\n createdAt: '2014-01-01 10:00:00',\n updatedAt: '2014-01-03 11:42:12'\n }\n ```\n and you just wanted `id` and `title`, you could write\n ```js\n Serializer.extend({\n attrs: ['id', 'title']\n });\n ```\n and the payload would look like\n ```\n {\n id: 1,\n title: 'Lorem ipsum'\n }\n ```\n @property attrs\n @public\n */\n\n this.attrs = this.attrs || undefined; // this is just here so I can add the doc comment. Better way?\n\n /**\n Use this property on a model serializer to specify related models you'd like to include in your JSON payload. (These can be considered default server-side includes.)\n For example, if you had an `author` with many `blog-post`s and you wanted to sideload these, specify so in the `include` key:\n ```js\n createServer({\n models: {\n author: Model.extend({\n blogPosts: hasMany()\n })\n },\n serializers: {\n author: Serializer.extend({\n include: ['blogPosts']\n });\n }\n })\n ```\n Now a response to a request for an author would look like this:\n ```\n GET /authors/1\n {\n author: {\n id: 1,\n name: 'Link',\n blogPostIds: [1, 2]\n },\n blogPosts: [\n {id: 1, authorId: 1, title: 'Lorem'},\n {id: 2, authorId: 1, title: 'Ipsum'}\n ]\n }\n ```\n You can also define `include` as a function so it can be determined dynamically.\n \n For example, you could conditionally include a relationship based on an `include` query parameter:\n ```js\n // Include blog posts for a GET to /authors/1?include=blogPosts\n \n Serializer.extend({\n include: function(request) {\n if (request.queryParams.include === \"blogPosts\") {\n return ['blogPosts'];\n } else {\n return [];\n }\n }\n });\n ```\n **Query param includes for JSONAPISerializer**\n The JSONAPISerializer supports the use of `include` query parameter to return compound documents out of the box.\n For example, if your app makes the following request\n ```\n GET /api/authors?include=blogPosts\n ```\n the `JSONAPISerializer` will inspect the query params of the request, see that the blogPosts relationship is present, and then proceed as if this relationship was specified directly in the include: [] array on the serializer itself.\n Note that, in accordance with the spec, Mirage gives precedence to an ?include query param over a default include: [] array that you might have specified directly on the serializer. Default includes will still be in effect, however, if a request does not have an ?include query param.\n Also note that default includes specified with the `include: []` array can only take a single model; they cannot take dot-separated paths to nested relationships.\n If you'd like to set a default dot-separated (nested) include path for a resource, you have to do it at the route level by setting a default value for `request.queryParams`:\n ```js\n this.get('/users', function(schema, request) => {\n request.queryParams = request.queryParams || {};\n if (!request.queryParams.include) {\n request.queryParams.include = 'blog-posts.comments';\n }\n // rest of route handler logic\n });\n ```\n @property include\n @public\n */\n\n this.include = this.include || []; // this is just here so I can add the doc comment. Better way?\n\n /**\n Set whether your JSON response should have a root key in it.\n *Doesn't apply to JSONAPISerializer.*\n Defaults to true, so a request for an author looks like:\n ```\n GET /authors/1\n {\n author: {\n id: 1,\n name: 'Link'\n }\n }\n ```\n Setting `root` to false disables this:\n ```js\n Serializer.extend({\n root: false\n });\n ```\n Now the response looks like:\n ```\n GET /authors/1\n {\n id: 1,\n name: 'Link'\n }\n ```\n @property root\n @public\n */\n\n this.root = this.root || undefined; // this is just here so I can add the doc comment. Better way?\n\n /**\n Set whether related models should be embedded or sideloaded.\n *Doesn't apply to JSONAPISerializer.*\n By default this false, so relationships are sideloaded:\n ```\n GET /authors/1\n {\n author: {\n id: 1,\n name: 'Link',\n blogPostIds: [1, 2]\n },\n blogPosts: [\n { id: 1, authorId: 1, title: 'Lorem' },\n { id: 2, authorId: 1, title: 'Ipsum' }\n ]\n }\n ```\n Setting `embed` to true will embed related records:\n ```js\n Serializer.extend({\n embed: true\n });\n ```\n Now the response looks like:\n ```\n GET /authors/1\n {\n author: {\n id: 1,\n name: 'Link',\n blogPosts: [\n { id: 1, authorId: 1, title: 'Lorem' },\n { id: 2, authorId: 1, title: 'Ipsum' }\n ]\n }\n }\n ```\n */\n\n this.embed = this.embed || undefined; // this is just here so I can add the doc comment. Better way?\n\n /**\n Use this to define how your serializer handles serializing relationship keys. It can take one of three values:\n - `included`, which is the default, will serialize the ids of a relationship if that relationship is included (sideloaded) along with the model or collection in the response\n - `always` will always serialize the ids of all relationships for the model or collection in the response\n - `never` will never serialize the ids of relationships for the model or collection in the response\n @property serializeIds\n @public\n */\n\n this.serializeIds = this.serializeIds || undefined; // this is just here so I can add the doc comment. Better way?\n }\n /**\n Override this method to implement your own custom serialize function. *response* is whatever was returned from your route handler, and *request* is the Pretender request object.\n Returns a plain JavaScript object or array, which Mirage uses as the response data to your app's XHR request.\n You can also override this method, call super, and manipulate the data before Mirage responds with it. This is a great place to add metadata, or for one-off operations that don't fit neatly into any of Mirage's other abstractions:\n ```js\n serialize(object, request) {\n // This is how to call super, as Mirage borrows [Backbone's implementation of extend](http://backbonejs.org/#Model-extend)\n let json = Serializer.prototype.serialize.apply(this, arguments);\n // Add metadata, sort parts of the response, etc.\n return json;\n }\n ```\n @param primaryResource\n @param request\n @return { Object } the json response\n */\n\n\n _createClass(Serializer, [{\n key: \"serialize\",\n value: function serialize(primaryResource\n /* , request */\n ) {\n this.primaryResource = primaryResource;\n return this.buildPayload(primaryResource);\n }\n /**\n This method is used by the POST and PUT shorthands. These shorthands expect a valid JSON:API document as part of the request, so that they know how to create or update the appropriate resouce. The *normalize* method allows you to transform your request body into a JSON:API document, which lets you take advantage of the shorthands when you otherwise may not be able to.\n Note that this method is a noop if you're using JSON:API already, since request payloads sent along with POST and PUT requests will already be in the correct format.\n Take a look at the included `ActiveModelSerializer`'s normalize method for an example.\n @method normalize\n @param json\n @public\n */\n\n }, {\n key: \"normalize\",\n value: function normalize(json) {\n return json;\n }\n }, {\n key: \"buildPayload\",\n value: function buildPayload(primaryResource, toInclude, didSerialize, json) {\n if (!primaryResource && isEmpty(toInclude)) {\n return json;\n } else if (primaryResource) {\n var _this$getHashForPrima = this.getHashForPrimaryResource(primaryResource),\n _this$getHashForPrima2 = _slicedToArray(_this$getHashForPrima, 2),\n resourceHash = _this$getHashForPrima2[0],\n newIncludes = _this$getHashForPrima2[1];\n\n var newDidSerialize = this.isCollection(primaryResource) ? primaryResource.models : [primaryResource];\n return this.buildPayload(undefined, newIncludes, newDidSerialize, resourceHash);\n } else {\n var nextIncludedResource = toInclude.shift();\n\n var _this$getHashForInclu = this.getHashForIncludedResource(nextIncludedResource),\n _this$getHashForInclu2 = _slicedToArray(_this$getHashForInclu, 2),\n _resourceHash = _this$getHashForInclu2[0],\n _newIncludes = _this$getHashForInclu2[1];\n\n var newToInclude = _newIncludes.filter(function (resource) {\n return !didSerialize.map(function (m) {\n return m.toString();\n }).includes(resource.toString());\n }).concat(toInclude);\n\n var _newDidSerialize = (this.isCollection(nextIncludedResource) ? nextIncludedResource.models : [nextIncludedResource]).concat(didSerialize);\n\n var newJson = this.mergePayloads(json, _resourceHash);\n return this.buildPayload(undefined, newToInclude, _newDidSerialize, newJson);\n }\n }\n }, {\n key: \"getHashForPrimaryResource\",\n value: function getHashForPrimaryResource(resource) {\n var _this$getHashForResou = this.getHashForResource(resource),\n _this$getHashForResou2 = _slicedToArray(_this$getHashForResou, 2),\n hash = _this$getHashForResou2[0],\n addToIncludes = _this$getHashForResou2[1];\n\n var hashWithRoot;\n\n if (this.root) {\n assert(!(resource instanceof PolymorphicCollection), \"The base Serializer class cannot serialize a top-level PolymorphicCollection when root is true, since PolymorphicCollections have no type.\");\n var serializer = this.serializerFor(resource.modelName);\n var rootKey = serializer.keyForResource(resource);\n hashWithRoot = _defineProperty({}, rootKey, hash);\n } else {\n hashWithRoot = hash;\n }\n\n return [hashWithRoot, addToIncludes];\n }\n }, {\n key: \"getHashForIncludedResource\",\n value: function getHashForIncludedResource(resource) {\n var hashWithRoot, addToIncludes;\n\n if (resource instanceof PolymorphicCollection) {\n hashWithRoot = {};\n addToIncludes = resource.models;\n } else {\n var serializer = this.serializerFor(resource.modelName);\n\n var _serializer$getHashFo = serializer.getHashForResource(resource),\n _serializer$getHashFo2 = _slicedToArray(_serializer$getHashFo, 2),\n hash = _serializer$getHashFo2[0],\n newModels = _serializer$getHashFo2[1]; // Included resources always have a root, and are always pushed to an array.\n\n\n var rootKey = serializer.keyForRelationship(resource.modelName);\n hashWithRoot = Array.isArray(hash) ? _defineProperty({}, rootKey, hash) : _defineProperty({}, rootKey, [hash]);\n addToIncludes = newModels;\n }\n\n return [hashWithRoot, addToIncludes];\n }\n }, {\n key: \"getHashForResource\",\n value: function getHashForResource(resource) {\n var _this = this;\n\n var removeForeignKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n var didSerialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var lookupSerializer = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n var hash, serializer;\n\n if (!lookupSerializer) {\n serializer = this; // this is used for embedded responses\n } // PolymorphicCollection lacks a modelName, but is dealt with in the map\n // by looking up the serializer on a per-model basis\n\n\n if (lookupSerializer && resource.modelName) {\n serializer = this.serializerFor(resource.modelName);\n }\n\n if (this.isModel(resource)) {\n hash = serializer._hashForModel(resource, removeForeignKeys, didSerialize);\n } else {\n hash = resource.models.map(function (m) {\n var modelSerializer = serializer;\n\n if (!modelSerializer) {\n // Can't get here if lookupSerializer is false, so look it up\n modelSerializer = _this.serializerFor(m.modelName);\n }\n\n return modelSerializer._hashForModel(m, removeForeignKeys, didSerialize);\n });\n }\n\n if (this.embed) {\n return [hash, []];\n } else {\n var addToIncludes = uniqBy(compact(flatten(serializer.getKeysForIncluded().map(function (key) {\n if (_this.isCollection(resource)) {\n return resource.models.map(function (m) {\n return m[key];\n });\n } else {\n return resource[key];\n }\n }))), function (m) {\n return m.toString();\n });\n return [hash, addToIncludes];\n }\n }\n /*\n Merges new resource hash into json. If json already has root key,\n pushes value of resourceHash onto that key.\n For example,\n json = {\n post: { id: 1, title: 'Lorem Ipsum', comment_ids: [1, 3] },\n comments: [\n { id: 1, text: 'foo' }\n ]\n };\n resourceHash = {\n comments: [\n { id: 2, text: 'bar' }\n ]\n };\n would yield\n {\n post: { id: 1, title: 'Lorem Ipsum', comment_ids: [1, 3] },\n comments: [\n { id: 1, text: 'foo' },\n { id: 2, text: 'bar' }\n ]\n };\n */\n\n }, {\n key: \"mergePayloads\",\n value: function mergePayloads(json, resourceHash) {\n var newJson;\n\n var _Object$keys = Object.keys(resourceHash),\n _Object$keys2 = _slicedToArray(_Object$keys, 1),\n resourceHashKey = _Object$keys2[0];\n\n if (json[resourceHashKey]) {\n newJson = json;\n newJson[resourceHashKey] = json[resourceHashKey].concat(resourceHash[resourceHashKey]);\n } else {\n newJson = Object.assign(json, resourceHash);\n }\n\n return newJson;\n }\n }, {\n key: \"keyForResource\",\n value: function keyForResource(resource) {\n var modelName = resource.modelName;\n return this.isModel(resource) ? this.keyForModel(modelName) : this.keyForCollection(modelName);\n }\n /**\n Used to define a custom key when serializing a primary model of modelName *modelName*. For example, the default Serializer will return something like the following:\n ```\n GET /blogPosts/1\n {\n blogPost: {\n id: 1,\n title: 'Lorem ipsum'\n }\n }\n ```\n If your API uses hyphenated keys, you could overwrite `keyForModel`:\n ```js\n // serializers/application.js\n export default Serializer.extend({\n keyForModel(modelName) {\n return hyphenate(modelName);\n }\n });\n ```\n Now the response will look like\n ```\n {\n 'blog-post': {\n id: 1,\n title: 'Lorem ipsum'\n }\n }\n ```\n @method keyForModel\n @param modelName\n @public\n */\n\n }, {\n key: \"keyForModel\",\n value: function keyForModel(modelName) {\n return camelize(modelName);\n }\n /**\n Used to customize the key when serializing a primary collection. By default this pluralizes the return value of `keyForModel`.\n For example, by default the following request may look like:\n ```\n GET /blogPosts\n {\n blogPosts: [\n {\n id: 1,\n title: 'Lorem ipsum'\n },\n ...\n ]\n }\n ```\n If your API hyphenates keys, you could overwrite `keyForCollection`:\n ```js\n // serializers/application.js\n export default Serializer.extend({\n keyForCollection(modelName) {\n return this._container.inflector.pluralize(dasherize(modelName));\n }\n });\n ```\n Now the response would look like:\n ```\n {\n 'blog-posts': [\n {\n id: 1,\n title: 'Lorem ipsum'\n },\n ...\n ]\n }\n ```\n @method keyForCollection\n @param modelName\n @public\n */\n\n }, {\n key: \"keyForCollection\",\n value: function keyForCollection(modelName) {\n return this._container.inflector.pluralize(this.keyForModel(modelName));\n }\n }, {\n key: \"_hashForModel\",\n value: function _hashForModel(model, removeForeignKeys) {\n var _this2 = this;\n\n var didSerialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n var attrs = this._attrsForModel(model);\n\n if (removeForeignKeys) {\n model.fks.forEach(function (fk) {\n delete attrs[fk];\n });\n }\n\n if (this.embed) {\n var newDidSerialize = Object.assign({}, didSerialize);\n newDidSerialize[model.modelName] = newDidSerialize[model.modelName] || {};\n newDidSerialize[model.modelName][model.id] = true;\n this.getKeysForIncluded().forEach(function (key) {\n var associatedResource = model[key];\n\n if (associatedResource && !get(newDidSerialize, \"\".concat(associatedResource.modelName, \".\").concat(associatedResource.id))) {\n var _this2$getHashForReso = _this2.getHashForResource(associatedResource, true, newDidSerialize, true),\n _this2$getHashForReso2 = _slicedToArray(_this2$getHashForReso, 1),\n associatedResourceHash = _this2$getHashForReso2[0];\n\n var formattedKey = _this2.keyForEmbeddedRelationship(key);\n\n attrs[formattedKey] = associatedResourceHash;\n\n if (_this2.isModel(associatedResource)) {\n var fk = \"\".concat(camelize(key), \"Id\");\n delete attrs[fk];\n }\n }\n });\n return attrs;\n } else {\n return this._maybeAddAssociationIds(model, attrs);\n }\n }\n /**\n @method _attrsForModel\n @param model\n @private\n @hide\n */\n\n }, {\n key: \"_attrsForModel\",\n value: function _attrsForModel(model) {\n var attrs = {};\n\n if (this.attrs) {\n attrs = this.attrs.reduce(function (memo, attr) {\n memo[attr] = model[attr];\n return memo;\n }, {});\n } else {\n attrs = Object.assign(attrs, model.attrs);\n } // Remove fks\n\n\n model.fks.forEach(function (key) {\n return delete attrs[key];\n });\n return this._formatAttributeKeys(attrs);\n }\n /**\n @method _maybeAddAssociationIds\n @param model\n @param attrs\n @private\n @hide\n */\n\n }, {\n key: \"_maybeAddAssociationIds\",\n value: function _maybeAddAssociationIds(model, attrs) {\n var _this3 = this;\n\n var newHash = Object.assign({}, attrs);\n\n if (this.serializeIds === \"always\") {\n model.associationKeys.forEach(function (key) {\n var resource = model[key];\n var association = model.associationFor(key);\n\n if (_this3.isCollection(resource)) {\n var formattedKey = _this3.keyForRelationshipIds(key);\n\n newHash[formattedKey] = model[\"\".concat(_this3._container.inflector.singularize(key), \"Ids\")];\n } else if (_this3.isModel(resource) && association.isPolymorphic) {\n var formattedTypeKey = _this3.keyForPolymorphicForeignKeyType(key);\n\n var formattedIdKey = _this3.keyForPolymorphicForeignKeyId(key);\n\n newHash[formattedTypeKey] = model[\"\".concat(key, \"Id\")].type;\n newHash[formattedIdKey] = model[\"\".concat(key, \"Id\")].id;\n } else if (resource) {\n var _formattedKey = _this3.keyForForeignKey(key);\n\n newHash[_formattedKey] = model[\"\".concat(key, \"Id\")];\n }\n });\n } else if (this.serializeIds === \"included\") {\n this.getKeysForIncluded().forEach(function (key) {\n var resource = model[key];\n var association = model.associationFor(key);\n\n if (_this3.isCollection(resource)) {\n var formattedKey = _this3.keyForRelationshipIds(key);\n\n newHash[formattedKey] = model[\"\".concat(_this3._container.inflector.singularize(key), \"Ids\")];\n } else if (_this3.isModel(resource) && association.isPolymorphic) {\n var formattedTypeKey = _this3.keyForPolymorphicForeignKeyType(key);\n\n var formattedIdKey = _this3.keyForPolymorphicForeignKeyId(key);\n\n newHash[formattedTypeKey] = model[\"\".concat(key, \"Id\")].type;\n newHash[formattedIdKey] = model[\"\".concat(key, \"Id\")].id;\n } else if (_this3.isModel(resource)) {\n var _formattedKey2 = _this3.keyForForeignKey(key);\n\n newHash[_formattedKey2] = model[\"\".concat(key, \"Id\")];\n }\n });\n }\n\n return newHash;\n }\n /**\n Used to customize how a model's attribute is formatted in your JSON payload.\n By default, model attributes are camelCase:\n ```\n GET /authors/1\n {\n author: {\n firstName: 'Link',\n lastName: 'The WoodElf'\n }\n }\n ```\n If your API expects snake case, you could write the following:\n ```js\n // serializers/application.js\n export default Serializer.extend({\n keyForAttribute(attr) {\n return underscore(attr);\n }\n });\n ```\n Now the response would look like:\n ```\n {\n author: {\n first_name: 'Link',\n last_name: 'The WoodElf'\n }\n }\n ```\n @method keyForAttribute\n @param attr\n @public\n */\n\n }, {\n key: \"keyForAttribute\",\n value: function keyForAttribute(attr) {\n return attr;\n }\n /**\n Use this hook to format the key for collections related to this model. *modelName* is the named parameter for the relationship.\n For example, if you're serializing an `author` that\n sideloads many `blogPosts`, the default response will look like:\n ```\n {\n author: {...},\n blogPosts: [...]\n }\n ```\n Overwrite `keyForRelationship` to format this key:\n ```js\n // serializers/application.js\n export default Serializer.extend({\n keyForRelationship(modelName) {\n return underscore(modelName);\n }\n });\n ```\n Now the response will look like this:\n ```\n {\n author: {...},\n blog_posts: [...]\n }\n ```\n @method keyForRelationship\n @param modelName\n @public\n */\n\n }, {\n key: \"keyForRelationship\",\n value: function keyForRelationship(modelName) {\n return camelize(this._container.inflector.pluralize(modelName));\n }\n /**\n Like `keyForRelationship`, but for embedded relationships.\n @method keyForEmbeddedRelationship\n @param attributeName\n @public\n */\n\n }, {\n key: \"keyForEmbeddedRelationship\",\n value: function keyForEmbeddedRelationship(attributeName) {\n return camelize(attributeName);\n }\n /**\n Use this hook to format the key for the IDS of a `hasMany` relationship\n in this model's JSON representation.\n For example, if you're serializing an `author` that\n sideloads many `blogPosts`, by default your `author` JSON would include a `blogPostIds` key:\n ```\n {\n author: {\n id: 1,\n blogPostIds: [1, 2, 3]\n },\n blogPosts: [...]\n }\n ```\n Overwrite `keyForRelationshipIds` to format this key:\n ```js\n // serializers/application.js\n export default Serializer.extend({\n keyForRelationshipIds(relationship) {\n return underscore(relationship) + '_ids';\n }\n });\n ```\n Now the response will look like:\n ```\n {\n author: {\n id: 1,\n blog_post_ids: [1, 2, 3]\n },\n blogPosts: [...]\n }\n ```\n @method keyForRelationshipIds\n @param modelName\n @public\n */\n\n }, {\n key: \"keyForRelationshipIds\",\n value: function keyForRelationshipIds(relationshipName) {\n return \"\".concat(this._container.inflector.singularize(camelize(relationshipName)), \"Ids\");\n }\n /**\n Like `keyForRelationshipIds`, but for `belongsTo` relationships.\n For example, if you're serializing a `blogPost` that sideloads one `author`,\n your `blogPost` JSON would include a `authorId` key:\n ```\n {\n blogPost: {\n id: 1,\n authorId: 1\n },\n author: ...\n }\n ```\n Overwrite `keyForForeignKey` to format this key:\n ```js\n // serializers/application.js\n export default Serializer.extend({\n keyForForeignKey(relationshipName) {\n return underscore(relationshipName) + '_id';\n }\n });\n ```\n Now the response will look like:\n ```js\n {\n blogPost: {\n id: 1,\n author_id: 1\n },\n author: ...\n }\n ```\n @method keyForForeignKey\n @param relationshipName\n @public\n */\n\n }, {\n key: \"keyForForeignKey\",\n value: function keyForForeignKey(relationshipName) {\n return \"\".concat(camelize(relationshipName), \"Id\");\n }\n /**\n Polymorphic relationships are represented with type-id pairs.\n Given the following model\n ```js\n Model.extend({\n commentable: belongsTo({ polymorphic: true })\n });\n ```\n the default Serializer would produce\n ```js\n {\n comment: {\n id: 1,\n commentableType: 'post',\n commentableId: '1'\n }\n }\n ```\n This hook controls how the `id` field (`commentableId` in the above example)\n is serialized. By default it camelizes the relationship and adds `Id` as a suffix.\n @method keyForPolymorphicForeignKeyId\n @param {String} relationshipName\n @return {String}\n @public\n */\n\n }, {\n key: \"keyForPolymorphicForeignKeyId\",\n value: function keyForPolymorphicForeignKeyId(relationshipName) {\n return \"\".concat(camelize(relationshipName), \"Id\");\n }\n /**\n Polymorphic relationships are represented with type-id pairs.\n Given the following model\n ```js\n Model.extend({\n commentable: belongsTo({ polymorphic: true })\n });\n ```\n the default Serializer would produce\n ```js\n {\n comment: {\n id: 1,\n commentableType: 'post',\n commentableId: '1'\n }\n }\n ```\n This hook controls how the `type` field (`commentableType` in the above example)\n is serialized. By default it camelizes the relationship and adds `Type` as a suffix.\n @method keyForPolymorphicForeignKeyType\n @param {String} relationshipName\n @return {String}\n @public\n */\n\n }, {\n key: \"keyForPolymorphicForeignKeyType\",\n value: function keyForPolymorphicForeignKeyType(relationshipName) {\n return \"\".concat(camelize(relationshipName), \"Type\");\n }\n /**\n @method isModel\n @param object\n @return {Boolean}\n @public\n @hide\n */\n\n }, {\n key: \"isModel\",\n value: function isModel(object) {\n return object instanceof Model;\n }\n /**\n @method isCollection\n @param object\n @return {Boolean}\n @public\n @hide\n */\n\n }, {\n key: \"isCollection\",\n value: function isCollection(object) {\n return object instanceof Collection || object instanceof PolymorphicCollection;\n }\n /**\n @method isModelOrCollection\n @param object\n @return {Boolean}\n @public\n @hide\n */\n\n }, {\n key: \"isModelOrCollection\",\n value: function isModelOrCollection(object) {\n return this.isModel(object) || this.isCollection(object);\n }\n /**\n @method serializerFor\n @param type\n @public\n @hide\n */\n\n }, {\n key: \"serializerFor\",\n value: function serializerFor(type) {\n return this.registry.serializerFor(type);\n }\n }, {\n key: \"getKeysForIncluded\",\n value: function getKeysForIncluded() {\n return isFunction(this.include) ? this.include(this.request, this.primaryResource) : this.include;\n }\n /**\n A reference to the schema instance.\n Useful to reference registered schema information, for example in a Serializer's include hook to include all a resource's associations:\n ```js\n Serializer.extend({\n include(request, resource) {\n return Object.keys(this.schema.associationsFor(resource.modelName));\n }\n })\n ```\n @property\n @type {Object}\n @public\n */\n\n }, {\n key: \"schema\",\n get: function get() {\n return this.registry.schema;\n }\n /**\n @method _formatAttributeKeys\n @param attrs\n @private\n @hide\n */\n\n }, {\n key: \"_formatAttributeKeys\",\n value: function _formatAttributeKeys(attrs) {\n var formattedAttrs = {};\n\n for (var key in attrs) {\n var formattedKey = this.keyForAttribute(key);\n formattedAttrs[formattedKey] = attrs[key];\n }\n\n return formattedAttrs;\n }\n }, {\n key: \"getCoalescedIds\",\n value: function getCoalescedIds() {}\n }]);\n\n return Serializer;\n}(); // Defaults\n\n\nSerializer.prototype.include = [];\nSerializer.prototype.root = true;\nSerializer.prototype.embed = false;\nSerializer.prototype.serializeIds = \"included\"; // can be 'included', 'always', or 'never'\n\nSerializer.extend = extend;\n/**\n The JSONAPISerializer. Subclass of Serializer.\n\n @class JSONAPISerializer\n @constructor\n @public\n */\n\nvar JSONAPISerializer = /*#__PURE__*/function (_Serializer) {\n _inherits(JSONAPISerializer, _Serializer);\n\n var _super = _createSuper(JSONAPISerializer);\n\n function JSONAPISerializer() {\n var _this;\n\n _classCallCheck(this, JSONAPISerializer);\n\n _this = _super.apply(this, arguments);\n /**\n By default, JSON:API's linkage data is only added for relationships that are being included in the current request.\n That means given an `author` model with a `posts` relationship, a GET request to /authors/1 would return a JSON:API document with an empty `relationships` hash:\n ```js\n {\n data: {\n type: 'authors',\n id: '1',\n attributes: { ... }\n }\n }\n ```\n but a request to GET /authors/1?include=posts would have linkage data added (in addition to the included resources):\n ```js\n {\n data: {\n type: 'authors',\n id: '1',\n attributes: { ... },\n relationships: {\n data: [\n { type: 'posts', id: '1' },\n { type: 'posts', id: '2' },\n { type: 'posts', id: '3' }\n ]\n }\n },\n included: [ ... ]\n }\n ```\n To add the linkage data for all relationships, you could set `alwaysIncludeLinkageData` to `true`:\n ```js\n JSONAPISerializer.extend({\n alwaysIncludeLinkageData: true\n });\n ```\n Then, a GET to /authors/1 would respond with\n ```js\n {\n data: {\n type: 'authors',\n id: '1',\n attributes: { ... },\n relationships: {\n posts: {\n data: [\n { type: 'posts', id: '1' },\n { type: 'posts', id: '2' },\n { type: 'posts', id: '3' }\n ]\n }\n }\n }\n }\n ```\n even though the related `posts` are not included in the same document.\n You can also use the `links` method (on the Serializer base class) to add relationship links (which will always be added regardless of the relationship is being included document), or you could use `shouldIncludeLinkageData` for more granular control.\n For more background on the behavior of this API, see [this blog post](http://www.ember-cli-mirage.com/blog/changing-mirages-default-linkage-data-behavior-1475).\n @property alwaysIncludeLinkageData\n @type {Boolean}\n @public\n */\n\n _this.alwaysIncludeLinkageData = _this.alwaysIncludeLinkageData || undefined; // this is just here so I can add the doc comment. Better way?\n\n return _this;\n } // Don't think this is used?\n\n\n _createClass(JSONAPISerializer, [{\n key: \"keyForModel\",\n value: function keyForModel(modelName) {\n return dasherize(modelName);\n } // Don't think this is used?\n\n }, {\n key: \"keyForCollection\",\n value: function keyForCollection(modelName) {\n return dasherize(modelName);\n }\n /**\n Used to customize the key for an attribute. By default, compound attribute names are dasherized.\n For example, the JSON:API document for a `post` model with a `commentCount` attribute would be:\n ```js\n {\n data: {\n id: 1,\n type: 'posts',\n attributes: {\n 'comment-count': 28\n }\n }\n }\n ```\n @method keyForAttribute\n @param {String} attr\n @return {String}\n @public\n */\n\n }, {\n key: \"keyForAttribute\",\n value: function keyForAttribute(attr) {\n return dasherize(attr);\n }\n /**\n Used to customize the key for a relationships. By default, compound relationship names are dasherized.\n For example, the JSON:API document for an `author` model with a `blogPosts` relationship would be:\n ```js\n {\n data: {\n id: 1,\n type: 'author',\n attributes: {\n ...\n },\n relationships: {\n 'blog-posts': {\n ...\n }\n }\n }\n }\n ```\n @method keyForRelationship\n @param {String} key\n @return {String}\n @public\n */\n\n }, {\n key: \"keyForRelationship\",\n value: function keyForRelationship(key) {\n return dasherize(key);\n }\n /**\n Use this hook to add top-level `links` data to JSON:API resource objects. The argument is the model being serialized.\n ```js\n // serializers/author.js\n import { JSONAPISerializer } from 'miragejs';\n export default JSONAPISerializer.extend({\n links(author) {\n return {\n 'posts': {\n related: `/api/authors/${author.id}/posts`\n }\n };\n }\n });\n ```\n @method links\n @param model\n */\n\n }, {\n key: \"links\",\n value: function links() {}\n }, {\n key: \"getHashForPrimaryResource\",\n value: function getHashForPrimaryResource(resource) {\n this._createRequestedIncludesGraph(resource);\n\n var resourceHash = this.getHashForResource(resource);\n var hashWithRoot = {\n data: resourceHash\n };\n var addToIncludes = this.getAddToIncludesForResource(resource);\n return [hashWithRoot, addToIncludes];\n }\n }, {\n key: \"getHashForIncludedResource\",\n value: function getHashForIncludedResource(resource) {\n var serializer = this.serializerFor(resource.modelName);\n var hash = serializer.getHashForResource(resource);\n var hashWithRoot = {\n included: this.isModel(resource) ? [hash] : hash\n };\n var addToIncludes = [];\n\n if (!this.hasQueryParamIncludes()) {\n addToIncludes = this.getAddToIncludesForResource(resource);\n }\n\n return [hashWithRoot, addToIncludes];\n }\n }, {\n key: \"getHashForResource\",\n value: function getHashForResource(resource) {\n var _this2 = this;\n\n var hash;\n\n if (this.isModel(resource)) {\n hash = this.getResourceObjectForModel(resource);\n } else {\n hash = resource.models.map(function (m) {\n return _this2.getResourceObjectForModel(m);\n });\n }\n\n return hash;\n }\n /*\n Returns a flat unique list of resources that need to be added to includes\n */\n\n }, {\n key: \"getAddToIncludesForResource\",\n value: function getAddToIncludesForResource(resource) {\n var relationshipPaths;\n\n if (this.hasQueryParamIncludes()) {\n relationshipPaths = this.request.queryParams.include.split(\",\");\n } else {\n var serializer = this.serializerFor(resource.modelName);\n relationshipPaths = serializer.getKeysForIncluded();\n }\n\n return this.getAddToIncludesForResourceAndPaths(resource, relationshipPaths);\n }\n }, {\n key: \"getAddToIncludesForResourceAndPaths\",\n value: function getAddToIncludesForResourceAndPaths(resource, relationshipPaths) {\n var _this3 = this;\n\n var includes = [];\n relationshipPaths.forEach(function (path) {\n var relationshipNames = path.split(\".\");\n\n var newIncludes = _this3.getIncludesForResourceAndPath.apply(_this3, [resource].concat(_toConsumableArray(relationshipNames)));\n\n includes.push(newIncludes);\n });\n return uniqBy(compact(flatten(includes)), function (m) {\n return m.toString();\n });\n }\n }, {\n key: \"getIncludesForResourceAndPath\",\n value: function getIncludesForResourceAndPath(resource) {\n var _this4 = this;\n\n for (var _len = arguments.length, names = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n names[_key - 1] = arguments[_key];\n }\n\n var nameForCurrentResource = camelize(names.shift());\n var includes = [];\n var modelsToAdd = [];\n\n if (this.isModel(resource)) {\n var relationship = resource[nameForCurrentResource];\n\n if (this.isModel(relationship)) {\n modelsToAdd = [relationship];\n } else if (this.isCollection(relationship)) {\n modelsToAdd = relationship.models;\n }\n } else {\n resource.models.forEach(function (model) {\n var relationship = model[nameForCurrentResource];\n\n if (_this4.isModel(relationship)) {\n modelsToAdd.push(relationship);\n } else if (_this4.isCollection(relationship)) {\n modelsToAdd = modelsToAdd.concat(relationship.models);\n }\n });\n }\n\n includes = includes.concat(modelsToAdd);\n\n if (names.length) {\n modelsToAdd.forEach(function (model) {\n includes = includes.concat(_this4.getIncludesForResourceAndPath.apply(_this4, [model].concat(names)));\n });\n }\n\n return includes;\n }\n }, {\n key: \"getResourceObjectForModel\",\n value: function getResourceObjectForModel(model) {\n var attrs = this._attrsForModel(model, true);\n\n delete attrs.id;\n var hash = {\n type: this.typeKeyForModel(model),\n id: model.id,\n attributes: attrs\n };\n return this._maybeAddRelationshipsToResourceObjectForModel(hash, model);\n }\n }, {\n key: \"_maybeAddRelationshipsToResourceObjectForModel\",\n value: function _maybeAddRelationshipsToResourceObjectForModel(hash, model) {\n var _this5 = this;\n\n var relationships = {};\n model.associationKeys.forEach(function (key) {\n var relationship = model[key];\n\n var relationshipKey = _this5.keyForRelationship(key);\n\n var relationshipHash = {};\n\n if (_this5.hasLinksForRelationship(model, key)) {\n var serializer = _this5.serializerFor(model.modelName);\n\n var links = serializer.links(model);\n relationshipHash.links = links[key];\n }\n\n if (_this5.alwaysIncludeLinkageData || _this5.shouldIncludeLinkageData(key, model) || _this5._relationshipIsIncludedForModel(key, model)) {\n var data = null;\n\n if (_this5.isModel(relationship)) {\n data = {\n type: _this5.typeKeyForModel(relationship),\n id: relationship.id\n };\n } else if (_this5.isCollection(relationship)) {\n data = relationship.models.map(function (model) {\n return {\n type: _this5.typeKeyForModel(model),\n id: model.id\n };\n });\n }\n\n relationshipHash.data = data;\n }\n\n if (!isEmpty(relationshipHash)) {\n relationships[relationshipKey] = relationshipHash;\n }\n });\n\n if (!isEmpty(relationships)) {\n hash.relationships = relationships;\n }\n\n return hash;\n }\n }, {\n key: \"hasLinksForRelationship\",\n value: function hasLinksForRelationship(model, relationshipKey) {\n var serializer = this.serializerFor(model.modelName);\n var links = serializer.links && serializer.links(model);\n return links && links[relationshipKey] != null;\n }\n /*\n This code (and a lot of this serializer) need to be re-worked according to\n the graph logic...\n */\n\n }, {\n key: \"_relationshipIsIncludedForModel\",\n value: function _relationshipIsIncludedForModel(relationshipKey, model) {\n if (this.hasQueryParamIncludes()) {\n var graph = this.request._includesGraph;\n\n var graphKey = this._graphKeyForModel(model); // Find the resource in the graph\n\n\n var graphResource; // Check primary data\n\n if (graph.data[graphKey]) {\n graphResource = graph.data[graphKey]; // Check includes\n } else if (graph.included[this._container.inflector.pluralize(model.modelName)]) {\n graphResource = graph.included[this._container.inflector.pluralize(model.modelName)][graphKey];\n } // If the model's in the graph, check if relationshipKey should be included\n\n\n return graphResource && graphResource.relationships && Object.prototype.hasOwnProperty.call(graphResource.relationships, dasherize(relationshipKey));\n } else {\n var relationshipPaths = this.getKeysForIncluded();\n return relationshipPaths.includes(relationshipKey);\n }\n }\n /*\n This is needed for _relationshipIsIncludedForModel - see the note there for\n more background.\n If/when we can refactor this serializer, the logic in this method would\n probably be the basis for the new overall json/graph creation.\n */\n\n }, {\n key: \"_createRequestedIncludesGraph\",\n value: function _createRequestedIncludesGraph(primaryResource) {\n var _this6 = this;\n\n var graph = {\n data: {}\n };\n\n if (this.isModel(primaryResource)) {\n var primaryResourceKey = this._graphKeyForModel(primaryResource);\n\n graph.data[primaryResourceKey] = {};\n\n this._addPrimaryModelToRequestedIncludesGraph(graph, primaryResource);\n } else if (this.isCollection(primaryResource)) {\n primaryResource.models.forEach(function (model) {\n var primaryResourceKey = _this6._graphKeyForModel(model);\n\n graph.data[primaryResourceKey] = {};\n\n _this6._addPrimaryModelToRequestedIncludesGraph(graph, model);\n });\n } // Hack :/ Need to think of a better palce to put this if\n // refactoring json:api serializer.\n\n\n this.request._includesGraph = graph;\n }\n }, {\n key: \"_addPrimaryModelToRequestedIncludesGraph\",\n value: function _addPrimaryModelToRequestedIncludesGraph(graph, model) {\n var _this7 = this;\n\n if (this.hasQueryParamIncludes()) {\n var graphKey = this._graphKeyForModel(model);\n\n var queryParamIncludes = this.getQueryParamIncludes();\n queryParamIncludes.split(\",\").filter(function (item) {\n return !!item.trim();\n }).forEach(function (includesPath) {\n // includesPath is post.comments, for example\n graph.data[graphKey].relationships = graph.data[graphKey].relationships || {};\n var relationshipKeys = includesPath.split(\".\").map(dasherize);\n var relationshipKey = relationshipKeys[0];\n var graphRelationshipKey = relationshipKey;\n var normalizedRelationshipKey = camelize(relationshipKey);\n var hasAssociation = model.associationKeys.has(normalizedRelationshipKey);\n assert(hasAssociation, \"You tried to include \\\"\".concat(relationshipKey, \"\\\" with \").concat(model, \" but no association named \\\"\").concat(normalizedRelationshipKey, \"\\\" is defined on the model.\"));\n var relationship = model[normalizedRelationshipKey];\n var relationshipData;\n\n if (_this7.isModel(relationship)) {\n relationshipData = _this7._graphKeyForModel(relationship);\n } else if (_this7.isCollection(relationship)) {\n relationshipData = relationship.models.map(_this7._graphKeyForModel);\n } else {\n relationshipData = null;\n }\n\n graph.data[graphKey].relationships[graphRelationshipKey] = relationshipData;\n\n if (relationship) {\n _this7._addResourceToRequestedIncludesGraph(graph, relationship, relationshipKeys.slice(1));\n }\n });\n }\n }\n }, {\n key: \"_addResourceToRequestedIncludesGraph\",\n value: function _addResourceToRequestedIncludesGraph(graph, resource, relationshipNames) {\n var _this8 = this;\n\n graph.included = graph.included || {};\n var models = this.isCollection(resource) ? resource.models : [resource];\n models.forEach(function (model) {\n var collectionName = _this8._container.inflector.pluralize(model.modelName);\n\n graph.included[collectionName] = graph.included[collectionName] || {};\n\n _this8._addModelToRequestedIncludesGraph(graph, model, relationshipNames);\n });\n }\n }, {\n key: \"_addModelToRequestedIncludesGraph\",\n value: function _addModelToRequestedIncludesGraph(graph, model, relationshipNames) {\n var collectionName = this._container.inflector.pluralize(model.modelName);\n\n var resourceKey = this._graphKeyForModel(model);\n\n graph.included[collectionName][resourceKey] = graph.included[collectionName][resourceKey] || {};\n\n if (relationshipNames.length) {\n this._addResourceRelationshipsToRequestedIncludesGraph(graph, collectionName, resourceKey, model, relationshipNames);\n }\n }\n /*\n Lot of the same logic here from _addPrimaryModelToRequestedIncludesGraph, could refactor & share\n */\n\n }, {\n key: \"_addResourceRelationshipsToRequestedIncludesGraph\",\n value: function _addResourceRelationshipsToRequestedIncludesGraph(graph, collectionName, resourceKey, model, relationshipNames) {\n graph.included[collectionName][resourceKey].relationships = graph.included[collectionName][resourceKey].relationships || {};\n var relationshipName = relationshipNames[0];\n var relationship = model[camelize(relationshipName)];\n var relationshipData;\n\n if (this.isModel(relationship)) {\n relationshipData = this._graphKeyForModel(relationship);\n } else if (this.isCollection(relationship)) {\n relationshipData = relationship.models.map(this._graphKeyForModel);\n }\n\n graph.included[collectionName][resourceKey].relationships[relationshipName] = relationshipData;\n\n if (relationship) {\n this._addResourceToRequestedIncludesGraph(graph, relationship, relationshipNames.slice(1));\n }\n }\n }, {\n key: \"_graphKeyForModel\",\n value: function _graphKeyForModel(model) {\n return \"\".concat(model.modelName, \":\").concat(model.id);\n }\n }, {\n key: \"getQueryParamIncludes\",\n value: function getQueryParamIncludes() {\n return get(this, \"request.queryParams.include\");\n }\n }, {\n key: \"hasQueryParamIncludes\",\n value: function hasQueryParamIncludes() {\n return !!this.getQueryParamIncludes();\n }\n /**\n Used to customize the `type` field of the document. By default, pluralizes and dasherizes the model's `modelName`.\n For example, the JSON:API document for a `blogPost` model would be:\n ```js\n {\n data: {\n id: 1,\n type: 'blog-posts'\n }\n }\n ```\n @method typeKeyForModel\n @param {Model} model\n @return {String}\n @public\n */\n\n }, {\n key: \"typeKeyForModel\",\n value: function typeKeyForModel(model) {\n return dasherize(this._container.inflector.pluralize(model.modelName));\n }\n }, {\n key: \"getCoalescedIds\",\n value: function getCoalescedIds(request) {\n var ids = request.queryParams && request.queryParams[\"filter[id]\"];\n\n if (typeof ids === \"string\") {\n return ids.split(\",\");\n }\n\n return ids;\n }\n /**\n Allows for per-relationship inclusion of linkage data. Use this when `alwaysIncludeLinkageData` is not granular enough.\n ```js\n export default JSONAPISerializer.extend({\n shouldIncludeLinkageData(relationshipKey, model) {\n if (relationshipKey === 'author' || relationshipKey === 'ghostWriter') {\n return true;\n }\n return false;\n }\n });\n ```\n @method shouldIncludeLinkageData\n @param {String} relationshipKey\n @param {Model} model\n @return {Boolean}\n @public\n */\n\n }, {\n key: \"shouldIncludeLinkageData\",\n value: function shouldIncludeLinkageData(relationshipKey, model) {\n return false;\n }\n }]);\n\n return JSONAPISerializer;\n}(Serializer);\n\nJSONAPISerializer.prototype.alwaysIncludeLinkageData = false;\n/**\n * @hide\n */\n\nvar SerializerRegistry = /*#__PURE__*/function () {\n function SerializerRegistry(schema) {\n var serializerMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, SerializerRegistry);\n\n this.schema = schema;\n this._serializerMap = serializerMap;\n }\n\n _createClass(SerializerRegistry, [{\n key: \"normalize\",\n value: function normalize(payload, modelName) {\n return this.serializerFor(modelName).normalize(payload);\n }\n }, {\n key: \"serialize\",\n value: function serialize(response, request) {\n var _this = this;\n\n this.request = request;\n\n if (this._isModelOrCollection(response)) {\n var serializer = this.serializerFor(response.modelName);\n return serializer.serialize(response, request);\n } else if (Array.isArray(response) && response.some(this._isCollection)) {\n return response.reduce(function (json, collection) {\n var serializer = _this.serializerFor(collection.modelName);\n\n if (serializer.embed) {\n json[_this._container.inflector.pluralize(collection.modelName)] = serializer.serialize(collection, request);\n } else {\n json = Object.assign(json, serializer.serialize(collection, request));\n }\n\n return json;\n }, {});\n } else {\n return response;\n }\n }\n }, {\n key: \"serializerFor\",\n value: function serializerFor(type) {\n var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n _ref$explicit = _ref.explicit,\n explicit = _ref$explicit === void 0 ? false : _ref$explicit;\n\n var SerializerForResponse = type && this._serializerMap && this._serializerMap[camelize(type)];\n\n if (explicit) {\n assert(!!SerializerForResponse, \"You passed in \".concat(type, \" as an explicit serializer type but that serializer doesn't exist.\"));\n } else {\n SerializerForResponse = SerializerForResponse || this._serializerMap.application || Serializer;\n assert(!SerializerForResponse || SerializerForResponse.prototype.embed || SerializerForResponse.prototype.root || new SerializerForResponse() instanceof JSONAPISerializer, \"You cannot have a serializer that sideloads (embed: false) and disables the root (root: false).\");\n }\n\n return new SerializerForResponse(this, type, this.request);\n }\n }, {\n key: \"_isModel\",\n value: function _isModel(object) {\n return object instanceof Model;\n }\n }, {\n key: \"_isCollection\",\n value: function _isCollection(object) {\n return object instanceof Collection || object instanceof PolymorphicCollection;\n }\n }, {\n key: \"_isModelOrCollection\",\n value: function _isModelOrCollection(object) {\n return this._isModel(object) || this._isCollection(object);\n }\n }, {\n key: \"registerSerializers\",\n value: function registerSerializers(newSerializerMaps) {\n var currentSerializerMap = this._serializerMap || {};\n this._serializerMap = Object.assign(currentSerializerMap, newSerializerMaps);\n }\n }, {\n key: \"getCoalescedIds\",\n value: function getCoalescedIds(request, modelName) {\n return this.serializerFor(modelName).getCoalescedIds(request);\n }\n }]);\n\n return SerializerRegistry;\n}();\n\nvar collectionNameCache = {};\nvar internalCollectionNameCache = {};\nvar modelNameCache = {};\n/**\n The primary use of the `Schema` class is to use it to find Models and Collections via the `Model` class methods.\n\n The `Schema` is most often accessed via the first parameter to a route handler:\n\n ```js\n this.get('posts', schema => {\n return schema.posts.where({ isAdmin: false });\n });\n ```\n\n It is also available from the `.schema` property of a `server` instance:\n\n ```js\n server.schema.users.create({ name: 'Yehuda' });\n ```\n\n To work with the Model or Collection returned from one of the methods below, refer to the instance methods in the API docs for the `Model` and `Collection` classes.\n\n @class Schema\n @constructor\n @public\n */\n\nvar Schema = /*#__PURE__*/function () {\n function Schema(db) {\n var modelsMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, Schema);\n\n assert(db, \"A schema requires a db\");\n /**\n Returns Mirage's database. See the `Db` docs for the db's API.\n @property db\n @type {Object}\n @public\n */\n\n this.db = db;\n this._registry = {};\n this._dependentAssociations = {\n polymorphic: []\n };\n this.registerModels(modelsMap);\n this.isSaving = {}; // a hash of models that are being saved, used to avoid cycles\n }\n /**\n @method registerModels\n @param hash\n @public\n @hide\n */\n\n\n _createClass(Schema, [{\n key: \"registerModels\",\n value: function registerModels() {\n var _this = this;\n\n var hash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n forIn(hash, function (model, key) {\n _this.registerModel(key, hash[key]);\n });\n }\n /**\n @method registerModel\n @param type\n @param ModelClass\n @public\n @hide\n */\n\n }, {\n key: \"registerModel\",\n value: function registerModel(type, ModelClass) {\n var _this2 = this;\n\n var camelizedModelName = camelize(type);\n var modelName = dasherize(camelizedModelName); // Avoid mutating original class, because we may want to reuse it across many tests\n\n ModelClass = ModelClass.extend(); // Store model & fks in registry\n // TODO: don't think this is needed anymore\n\n this._registry[camelizedModelName] = this._registry[camelizedModelName] || {\n \"class\": null,\n foreignKeys: []\n }; // we may have created this key before, if another model added fks to it\n\n this._registry[camelizedModelName][\"class\"] = ModelClass; // TODO: set here, remove from model#constructor\n\n ModelClass.prototype._schema = this;\n ModelClass.prototype.modelName = modelName; // Set up associations\n\n ModelClass.prototype.hasManyAssociations = {}; // a registry of the model's hasMany associations. Key is key from model definition, value is association instance itself\n\n ModelClass.prototype.hasManyAssociationFks = {}; // a lookup table to get the hasMany association by foreignKey\n\n ModelClass.prototype.belongsToAssociations = {}; // a registry of the model's belongsTo associations. Key is key from model definition, value is association instance itself\n\n ModelClass.prototype.belongsToAssociationFks = {}; // a lookup table to get the belongsTo association by foreignKey\n\n ModelClass.prototype.associationKeys = new Set(); // ex: address.user, user.addresses\n\n ModelClass.prototype.associationIdKeys = new Set(); // ex: address.user_id, user.address_ids\n\n ModelClass.prototype.dependentAssociations = []; // a registry of associations that depend on this model, needed for deletion cleanup.\n\n var fksAddedFromThisModel = {};\n\n for (var associationProperty in ModelClass.prototype) {\n if (ModelClass.prototype[associationProperty] instanceof Association) {\n var association = ModelClass.prototype[associationProperty];\n association.name = associationProperty;\n association.modelName = association.modelName || this.toModelName(associationProperty);\n association.ownerModelName = modelName;\n association.setSchema(this); // Update the registry with this association's foreign keys. This is\n // essentially our \"db migration\", since we must know about the fks.\n\n var _association$getForei = association.getForeignKeyArray(),\n _association$getForei2 = _slicedToArray(_association$getForei, 2),\n fkHolder = _association$getForei2[0],\n fk = _association$getForei2[1];\n\n fksAddedFromThisModel[fkHolder] = fksAddedFromThisModel[fkHolder] || [];\n assert(!fksAddedFromThisModel[fkHolder].includes(fk), \"Your '\".concat(type, \"' model definition has multiple possible inverse relationships of type '\").concat(fkHolder, \"'. Please use explicit inverses.\"));\n fksAddedFromThisModel[fkHolder].push(fk);\n\n this._addForeignKeyToRegistry(fkHolder, fk); // Augment the Model's class with any methods added by this association\n\n\n association.addMethodsToModelClass(ModelClass, associationProperty);\n }\n } // Create a db collection for this model, if doesn't exist\n\n\n var collection = this.toCollectionName(modelName);\n\n if (!this.db[collection]) {\n this.db.createCollection(collection);\n } // Create the entity methods\n\n\n this[collection] = {\n camelizedModelName: camelizedModelName,\n \"new\": function _new(attrs) {\n return _this2[\"new\"](camelizedModelName, attrs);\n },\n create: function create(attrs) {\n return _this2.create(camelizedModelName, attrs);\n },\n all: function all(attrs) {\n return _this2.all(camelizedModelName, attrs);\n },\n find: function find(attrs) {\n return _this2.find(camelizedModelName, attrs);\n },\n findBy: function findBy(attrs) {\n return _this2.findBy(camelizedModelName, attrs);\n },\n findOrCreateBy: function findOrCreateBy(attrs) {\n return _this2.findOrCreateBy(camelizedModelName, attrs);\n },\n where: function where(attrs) {\n return _this2.where(camelizedModelName, attrs);\n },\n none: function none(attrs) {\n return _this2.none(camelizedModelName, attrs);\n },\n first: function first(attrs) {\n return _this2.first(camelizedModelName, attrs);\n }\n };\n return this;\n }\n /**\n @method modelFor\n @param type\n @public\n @hide\n */\n\n }, {\n key: \"modelFor\",\n value: function modelFor(type) {\n return this._registry[type];\n }\n /**\n Create a new unsaved model instance with attributes *attrs*.\n ```js\n let post = blogPosts.new({ title: 'Lorem ipsum' });\n post.title; // Lorem ipsum\n post.id; // null\n post.isNew(); // true\n ```\n @method new\n @param type\n @param attrs\n @public\n */\n\n }, {\n key: \"new\",\n value: function _new(type, attrs) {\n return this._instantiateModel(dasherize(type), attrs);\n }\n /**\n Create a new model instance with attributes *attrs*, and insert it into the database.\n ```js\n let post = blogPosts.create({title: 'Lorem ipsum'});\n post.title; // Lorem ipsum\n post.id; // 1\n post.isNew(); // false\n ```\n @method create\n @param type\n @param attrs\n @public\n */\n\n }, {\n key: \"create\",\n value: function create(type, attrs) {\n return this[\"new\"](type, attrs).save();\n }\n /**\n Return all models in the database.\n ```js\n let posts = blogPosts.all();\n // [post:1, post:2, ...]\n ```\n @method all\n @param type\n @public\n */\n\n }, {\n key: \"all\",\n value: function all(type) {\n var collection = this.collectionForType(type);\n return this._hydrate(collection, dasherize(type));\n }\n /**\n Return an empty collection of type `type`.\n @method none\n @param type\n @public\n */\n\n }, {\n key: \"none\",\n value: function none(type) {\n return this._hydrate([], dasherize(type));\n }\n /**\n Return one or many models in the database by id.\n ```js\n let post = blogPosts.find(1);\n let posts = blogPosts.find([1, 3, 4]);\n ```\n @method find\n @param type\n @param ids\n @public\n */\n\n }, {\n key: \"find\",\n value: function find(type, ids) {\n var collection = this.collectionForType(type);\n var records = collection.find(ids);\n\n if (Array.isArray(ids)) {\n assert(records.length === ids.length, \"Couldn't find all \".concat(this._container.inflector.pluralize(type), \" with ids: (\").concat(ids.join(\",\"), \") (found \").concat(records.length, \" results, but was looking for \").concat(ids.length, \")\"));\n }\n\n return this._hydrate(records, dasherize(type));\n }\n /**\n Returns the first model in the database that matches the key-value pairs in `attrs`. Note that a string comparison is used.\n ```js\n let post = blogPosts.findBy({ published: true });\n let post = blogPosts.findBy({ authorId: 1, published: false });\n let post = blogPosts.findBy({ author: janeSmith, featured: true });\n ```\n This will return `null` if the schema doesn't have any matching record.\n A predicate function can also be used to find a match.\n ```js\n let longPost = blogPosts.findBy((post) => post.body.length > 1000);\n ```\n @method findBy\n @param type\n @param attributesOrPredicate\n @public\n */\n\n }, {\n key: \"findBy\",\n value: function findBy(type, query) {\n var collection = this.collectionForType(type);\n var record = collection.findBy(query);\n return this._hydrate(record, dasherize(type));\n }\n /**\n Returns the first model in the database that matches the key-value pairs in `attrs`, or creates a record with the attributes if one is not found.\n ```js\n // Find the first published blog post, or create a new one.\n let post = blogPosts.findOrCreateBy({ published: true });\n ```\n @method findOrCreateBy\n @param type\n @param attributeName\n @public\n */\n\n }, {\n key: \"findOrCreateBy\",\n value: function findOrCreateBy(type, attrs) {\n var collection = this.collectionForType(type);\n var record = collection.findBy(attrs);\n var model;\n\n if (!record) {\n model = this.create(type, attrs);\n } else {\n model = this._hydrate(record, dasherize(type));\n }\n\n return model;\n }\n /**\n Return an ORM/Collection, which represents an array of models from the database matching `query`.\n If `query` is an object, its key-value pairs will be compared against records using string comparison.\n `query` can also be a compare function.\n ```js\n let posts = blogPosts.where({ published: true });\n let posts = blogPosts.where(post => post.published === true);\n ```\n @method where\n @param type\n @param query\n @public\n */\n\n }, {\n key: \"where\",\n value: function where(type, query) {\n var collection = this.collectionForType(type);\n var records = collection.where(query);\n return this._hydrate(records, dasherize(type));\n }\n /**\n Returns the first model in the database.\n ```js\n let post = blogPosts.first();\n ```\n N.B. This will return `null` if the schema doesn't contain any records.\n @method first\n @param type\n @public\n */\n\n }, {\n key: \"first\",\n value: function first(type) {\n var collection = this.collectionForType(type);\n var record = collection[0];\n return this._hydrate(record, dasherize(type));\n }\n /**\n @method modelClassFor\n @param modelName\n @public\n @hide\n */\n\n }, {\n key: \"modelClassFor\",\n value: function modelClassFor(modelName) {\n var model = this._registry[camelize(modelName)];\n\n assert(model, \"Model not registered: \".concat(modelName));\n return model[\"class\"].prototype;\n }\n /*\n This method updates the dependentAssociations registry, which is used to\n keep track of which models depend on a given association. It's used when\n deleting models - their dependents need to be looked up and foreign keys\n updated.\n For example,\n schema = {\n post: Model.extend(),\n comment: Model.extend({\n post: belongsTo()\n })\n };\n comment1.post = post1;\n ...\n post1.destroy()\n Deleting this post should clear out comment1's foreign key.\n Polymorphic associations can have _any_ other model as a dependent, so we\n handle them separately.\n */\n\n }, {\n key: \"addDependentAssociation\",\n value: function addDependentAssociation(association, modelName) {\n if (association.isPolymorphic) {\n this._dependentAssociations.polymorphic.push(association);\n } else {\n this._dependentAssociations[modelName] = this._dependentAssociations[modelName] || [];\n\n this._dependentAssociations[modelName].push(association);\n }\n }\n }, {\n key: \"dependentAssociationsFor\",\n value: function dependentAssociationsFor(modelName) {\n var directDependents = this._dependentAssociations[modelName] || [];\n var polymorphicAssociations = this._dependentAssociations.polymorphic || [];\n return directDependents.concat(polymorphicAssociations);\n }\n /**\n Returns an object containing the associations registered for the model of the given _modelName_.\n For example, given this configuration\n \n ```js\n import { createServer, Model, hasMany, belongsTo } from 'miragejs'\n let server = createServer({\n models: {\n user: Model,\n article: Model.extend({\n fineAuthor: belongsTo(\"user\"),\n comments: hasMany()\n }),\n comment: Model\n }\n })\n ```\n each of the following would return empty objects\n ```js\n server.schema.associationsFor('user')\n // {}\n server.schema.associationsFor('comment')\n // {}\n ```\n but the associations for the `article` would return\n ```js\n server.schema.associationsFor('article')\n // {\n // fineAuthor: BelongsToAssociation,\n // comments: HasManyAssociation\n // }\n ```\n Check out the docs on the Association class to see what fields are available for each association.\n @method associationsFor\n @param {String} modelName\n @return {Object}\n @public\n */\n\n }, {\n key: \"associationsFor\",\n value: function associationsFor(modelName) {\n var modelClass = this.modelClassFor(modelName);\n return Object.assign({}, modelClass.belongsToAssociations, modelClass.hasManyAssociations);\n }\n }, {\n key: \"hasModelForModelName\",\n value: function hasModelForModelName(modelName) {\n return this.modelFor(camelize(modelName));\n }\n /*\n Private methods\n */\n\n /**\n @method collectionForType\n @param type\n @private\n @hide\n */\n\n }, {\n key: \"collectionForType\",\n value: function collectionForType(type) {\n var collection = this.toCollectionName(type);\n assert(this.db[collection], \"You're trying to find model(s) of type \".concat(type, \" but this collection doesn't exist in the database.\"));\n return this.db[collection];\n }\n }, {\n key: \"toCollectionName\",\n value: function toCollectionName(type) {\n if (typeof collectionNameCache[type] !== \"string\") {\n var modelName = dasherize(type);\n var collectionName = camelize(this._container.inflector.pluralize(modelName));\n collectionNameCache[type] = collectionName;\n }\n\n return collectionNameCache[type];\n } // This is to get at the underlying Db collection. Poorly named... need to\n // refactor to DbTable or something.\n\n }, {\n key: \"toInternalCollectionName\",\n value: function toInternalCollectionName(type) {\n if (typeof internalCollectionNameCache[type] !== \"string\") {\n var internalCollectionName = \"_\".concat(this.toCollectionName(type));\n internalCollectionNameCache[type] = internalCollectionName;\n }\n\n return internalCollectionNameCache[type];\n }\n }, {\n key: \"toModelName\",\n value: function toModelName(type) {\n if (typeof modelNameCache[type] !== \"string\") {\n var dasherized = dasherize(type);\n\n var modelName = this._container.inflector.singularize(dasherized);\n\n modelNameCache[type] = modelName;\n }\n\n return modelNameCache[type];\n }\n /**\n @method _addForeignKeyToRegistry\n @param type\n @param fk\n @private\n @hide\n */\n\n }, {\n key: \"_addForeignKeyToRegistry\",\n value: function _addForeignKeyToRegistry(type, fk) {\n this._registry[type] = this._registry[type] || {\n \"class\": null,\n foreignKeys: []\n };\n var fks = this._registry[type].foreignKeys;\n\n if (!fks.includes(fk)) {\n fks.push(fk);\n }\n }\n /**\n @method _instantiateModel\n @param modelName\n @param attrs\n @private\n @hide\n */\n\n }, {\n key: \"_instantiateModel\",\n value: function _instantiateModel(modelName, attrs) {\n var ModelClass = this._modelFor(modelName);\n\n var fks = this._foreignKeysFor(modelName);\n\n return new ModelClass(this, modelName, attrs, fks);\n }\n /**\n @method _modelFor\n @param modelName\n @private\n @hide\n */\n\n }, {\n key: \"_modelFor\",\n value: function _modelFor(modelName) {\n return this._registry[camelize(modelName)][\"class\"];\n }\n /**\n @method _foreignKeysFor\n @param modelName\n @private\n @hide\n */\n\n }, {\n key: \"_foreignKeysFor\",\n value: function _foreignKeysFor(modelName) {\n return this._registry[camelize(modelName)].foreignKeys;\n }\n /**\n Takes a record and returns a model, or an array of records\n and returns a collection.\n *\n @method _hydrate\n @param records\n @param modelName\n @private\n @hide\n */\n\n }, {\n key: \"_hydrate\",\n value: function _hydrate(records, modelName) {\n if (Array.isArray(records)) {\n var models = records.map(function (record) {\n return this._instantiateModel(modelName, record);\n }, this);\n return new Collection(modelName, models);\n } else if (records) {\n return this._instantiateModel(modelName, records);\n } else {\n return null;\n }\n }\n }]);\n\n return Schema;\n}();\n\nvar classes = {\n Db: Db,\n Association: Association,\n RouteHandler: RouteHandler,\n BaseRouteHandler: BaseRouteHandler,\n Serializer: Serializer,\n SerializerRegistry: SerializerRegistry,\n Schema: Schema\n};\nvar defaultInflector$1 = {\n singularize: singularize,\n pluralize: pluralize\n};\n/**\n Lightweight DI container for customizable objects that are needed by\n deeply nested classes.\n\n @class Container\n @hide\n */\n\nvar Container = /*#__PURE__*/function () {\n function Container() {\n _classCallCheck(this, Container);\n\n this.inflector = defaultInflector$1;\n }\n\n _createClass(Container, [{\n key: \"register\",\n value: function register(key, value) {\n this[key] = value;\n }\n }, {\n key: \"create\",\n value: function create(className) {\n var Class = classes[className];\n Class.prototype._container = this;\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return _construct(Class, args);\n }\n }]);\n\n return Container;\n}();\n/**\n These are side effects. We give each class a default container so it can be\n easily unit tested.\n\n We should remove these once we have test coverage and can refactor to a proper\n DI system.\n*/\n\n\nvar defaultContainer = new Container();\nDb.prototype._container = defaultContainer;\nAssociation.prototype._container = defaultContainer;\nBaseRouteHandler.prototype._container = defaultContainer;\nRouteHandler.prototype._container = defaultContainer;\nSerializer.prototype._container = defaultContainer;\nSerializerRegistry.prototype._container = defaultContainer;\nSchema.prototype._container = defaultContainer;\nvar isPluralForModelCache = {};\n/**\n * Creates a new Pretender instance.\n *\n * @method createPretender\n * @param {Server} server\n * @return {Object} A new Pretender instance.\n * @public\n */\n\nfunction createPretender(server) {\n if (typeof window !== \"undefined\") {\n return new Pretender(function () {\n this.passthroughRequest = function (verb, path, request) {\n if (server.shouldLog()) {\n console.log(\"Mirage: Passthrough request for \".concat(verb.toUpperCase(), \" \").concat(request.url));\n }\n };\n\n this.handledRequest = function (verb, path, request) {\n if (server.shouldLog()) {\n console.groupCollapsed(\"Mirage: [\".concat(request.status, \"] \").concat(verb.toUpperCase(), \" \").concat(request.url));\n var requestBody = request.requestBody,\n responseText = request.responseText;\n var loggedRequest, loggedResponse;\n\n try {\n loggedRequest = JSON.parse(requestBody);\n } catch (e) {\n loggedRequest = requestBody;\n }\n\n try {\n loggedResponse = JSON.parse(responseText);\n } catch (e) {\n loggedResponse = responseText;\n }\n\n console.groupCollapsed(\"Response\");\n console.log(loggedResponse);\n console.groupEnd();\n console.groupCollapsed(\"Request (data)\");\n console.log(loggedRequest);\n console.groupEnd();\n console.groupCollapsed(\"Request (raw)\");\n console.log(request);\n console.groupEnd();\n console.groupEnd();\n }\n };\n\n var originalCheckPassthrough = this.checkPassthrough;\n\n this.checkPassthrough = function (request) {\n var shouldPassthrough = server.passthroughChecks.some(function (passthroughCheck) {\n return passthroughCheck(request);\n });\n\n if (shouldPassthrough) {\n var url = request.url.includes(\"?\") ? request.url.substr(0, request.url.indexOf(\"?\")) : request.url;\n this[request.method.toLowerCase()](url, this.passthrough);\n }\n\n return originalCheckPassthrough.apply(this, arguments);\n };\n\n this.unhandledRequest = function (verb, path) {\n path = decodeURI(path);\n assert(\"Your app tried to \".concat(verb, \" '\").concat(path, \"', but there was no route defined to handle this request. Define a route for this endpoint in your routes() config. Did you forget to define a namespace?\"));\n };\n }, {\n trackRequests: server.shouldTrackRequests()\n });\n }\n}\n\nvar defaultRouteOptions = {\n coalesce: false,\n timing: undefined\n};\nvar defaultInflector = {\n singularize: singularize,\n pluralize: pluralize\n};\n/**\n @hide\n*/\n\nvar defaultPassthroughs = [\"http://localhost:0/chromecheckurl\", // mobile chrome\n\"http://localhost:30820/socket.io\", // electron\nfunction (request) {\n return /.+\\.hot-update.json$/.test(request.url);\n}];\n/**\n * Determine if the object contains a valid option.\n *\n * @method isOption\n * @param {Object} option An object with one option value pair.\n * @return {Boolean} True if option is a valid option, false otherwise.\n * @private\n */\n\nfunction isOption(option) {\n if (!option || _typeof(option) !== \"object\") {\n return false;\n }\n\n var allOptions = Object.keys(defaultRouteOptions);\n var optionKeys = Object.keys(option);\n\n for (var i = 0; i < optionKeys.length; i++) {\n var key = optionKeys[i];\n\n if (allOptions.indexOf(key) > -1) {\n return true;\n }\n }\n\n return false;\n}\n/**\n * Extract arguments for a route.\n *\n * @method extractRouteArguments\n * @param {Array} args Of the form [options], [object, code], [function, code]\n * [shorthand, options], [shorthand, code, options]\n * @return {Array} [handler (i.e. the function, object or shorthand), code,\n * options].\n * @private\n */\n\n\nfunction extractRouteArguments(args) {\n var _args$splice = args.splice(-1),\n _args$splice2 = _slicedToArray(_args$splice, 1),\n lastArg = _args$splice2[0];\n\n if (isOption(lastArg)) {\n lastArg = assign({}, defaultRouteOptions, lastArg);\n } else {\n args.push(lastArg);\n lastArg = defaultRouteOptions;\n }\n\n var t = 2 - args.length;\n\n while (t-- > 0) {\n args.push(undefined);\n }\n\n args.push(lastArg);\n return args;\n}\n/**\n * Creates a Server\n * @param {Object} options Server's configuration object\n * @param {String} options.urlPrefix The base URL for the routes. Example: `http://miragejs.com`.\n * @param {String} options.namespace The default namespace for the `Server`. Example: `/api/v1`.\n * @param {Number} options.timing Default latency for the routes to respond to a request.\n * @param {String} options.environment Defines the environment of the `Server`.\n * @param {Boolean} options.trackRequests Pretender `trackRequests`.\n * @param {Boolean} options.useDefaultPassthroughs True to use mirage provided passthroughs\n * @param {Boolean} options.logging Set to true or false to explicitly specify logging behavior.\n * @param {Function} options.seeds Called on the seed phase. Should be used to seed the database.\n * @param {Function} options.scenarios Alias for seeds.\n * @param {Function} options.routes Should be used to define server routes.\n * @param {Function} options.baseConfig Alias for routes.\n * @param {Object} options.inflector Default inflector (used for pluralization and singularization).\n * @param {Object} options.identityManagers Database identity managers.\n * @param {Object} options.models Server models\n * @param {Object} options.serializers Server serializers\n * @param {Object} options.factories Server factories\n * @param {Object} options.pretender Pretender instance\n */\n\n\nfunction createServer(options) {\n return new Server(options);\n}\n/**\n The Mirage server.\n\n Note that `this` within your `routes` function refers to the server instance, which is the same instance that `server` refers to in your tests.\n\n @class Server\n @public\n*/\n\n\nvar Server = /*#__PURE__*/function () {\n /**\n * Creates a Server\n * @param {Object} options Server's configuration object\n * @param {String} options.urlPrefix The base URL for the routes. Example: `http://miragejs.com`.\n * @param {String} options.namespace The default namespace for the `Server`. Example: `/api/v1`.\n * @param {Number} options.timing Default latency for the routes to respond to a request.\n * @param {String} options.environment Defines the environment of the `Server`.\n * @param {Boolean} options.trackRequests Pretender `trackRequests`.\n * @param {Boolean} options.useDefaultPassthroughs True to use mirage provided passthroughs\n * @param {Boolean} options.logging Set to true or false to explicitly specify logging behavior.\n * @param {Function} options.seeds Called on the seed phase. Should be used to seed the database.\n * @param {Function} options.scenarios Alias for seeds.\n * @param {Function} options.routes Should be used to define server routes.\n * @param {Function} options.baseConfig Alias for routes.\n * @param {Object} options.inflector Default inflector (used for pluralization and singularization).\n * @param {Object} options.identityManagers Database identity managers.\n * @param {Object} options.models Server models\n * @param {Object} options.serializers Server serializers\n * @param {Object} options.factories Server factories\n * @param {Object} options.pretender Pretender instance\n */\n function Server() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Server);\n\n this._container = new Container();\n this.config(options);\n /**\n Returns the Mirage Db instance.\n @property db\n @return Db\n */\n\n this.db = this.db || undefined;\n /**\n Returns the Mirage Schema (ORM) instance.\n @property schema\n @return Schema\n */\n\n this.schema = this.schema || undefined;\n }\n\n _createClass(Server, [{\n key: \"config\",\n value: function config() {\n var _config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n this.passthroughChecks = this.passthroughChecks || [];\n var didOverrideConfig = _config.environment && this.environment && this.environment !== _config.environment;\n assert(!didOverrideConfig, \"You cannot modify Mirage's environment once the server is created\");\n this.environment = _config.environment || this.environment || \"development\";\n\n if (_config.routes) {\n assert(!_config.baseConfig, \"The routes option is an alias for the baseConfig option. You can't pass both options into your server definition.\");\n _config.baseConfig = _config.routes;\n }\n\n if (_config.seeds) {\n assert(!_config.scenarios, \"The seeds option is an alias for the scenarios.default option. You can't pass both options into your server definition.\");\n _config.scenarios = {\n \"default\": _config.seeds\n };\n }\n\n this._config = _config;\n /**\n Set the base namespace used for all routes defined with `get`, `post`, `put` or `del`.\n For example,\n ```js\n createServer({\n routes() {\n this.namespace = '/api';\n // this route will handle the URL '/api/contacts'\n this.get('/contacts', 'contacts');\n }\n })\n ```\n Note that only routes defined after `this.namespace` are affected. This is useful if you have a few one-off routes that you don't want under your namespace:\n ```js\n createServer({\n routes() {\n // this route handles /auth\n this.get('/auth', function() { ...});\n this.namespace = '/api';\n // this route will handle the URL '/api/contacts'\n this.get('/contacts', 'contacts');\n };\n })\n ```\n If your app is loaded from the filesystem vs. a server (e.g. via Cordova or Electron vs. `localhost` or `https://yourhost.com/`), you will need to explicitly define a namespace. Likely values are `/` (if requests are made with relative paths) or `https://yourhost.com/api/...` (if requests are made to a defined server).\n For a sample implementation leveraging a configured API host & namespace, check out [this issue comment](https://github.com/miragejs/ember-cli-mirage/issues/497#issuecomment-183458721).\n @property namespace\n @type String\n @public\n */\n\n this.namespace = this.namespace || _config.namespace || \"\";\n /**\n Mirage needs know the singular and plural versions of certain words for some of its APIs to work.\n For example, whenever you define a model\n ```js\n createServer({\n models: {\n post: Model\n }\n })\n ```\n Mirage will pluralize the word \"post\" and use it to create a `db.posts` database collection.\n To accomplish this, Mirage uses an object called an Inflector. An Inflector is an object with two methods, `singularize` and `pluralize`, that Mirage will call whenever it needs to inflect a word.\n Mirage has a default inflector, so if you write\n ```js\n createServer()\n ```\n you'll be using the node [inflected](https://github.com/martinandert/inflected#readme) package. This can be customized if you have irregular words or need to change the defaults. You can wead more in [the guide on customizing inflections](/docs/advanced/customizing-inflections).\n You typically should be able to make your customizations using the provided inflector. It's good to match any custom inflections your backend uses, as this will keep your Mirage code more consistent and simpler.\n You can also override the inflector completely and provide your own `pluralize` and `singularize` methods:\n ```js\n createServer({\n inflector: {\n pluralize(word) {\n // your logic\n },\n singularize(word) {\n // your logic\n }\n }\n })\n ```\n */\n\n this.inflector = _config.inflector || defaultInflector;\n\n this._container.register(\"inflector\", this.inflector);\n /**\n Sets a string to prefix all route handler URLs with.\n Useful if your app makes API requests to a different port.\n ```js\n createServer({\n routes() {\n this.urlPrefix = 'http://localhost:8080'\n }\n })\n ```\n */\n\n\n this.urlPrefix = this.urlPrefix || _config.urlPrefix || \"\";\n /**\n Set the number of milliseconds for the the Server's response time.\n By default there's a 400ms delay during development, and 0 delay in testing (so your tests run fast).\n ```js\n createServer({\n routes() {\n this.timing = 400; // default\n }\n })\n ```\n To set the timing for individual routes, see the `timing` option for route handlers.\n @property timing\n @type Number\n @public\n */\n\n this.timing = this.timing || _config.timing || 400;\n /**\n Set to `true` or `false` to explicitly specify logging behavior.\n By default, server responses are logged in non-testing environments. Logging is disabled by default in testing, so as not to clutter CI test runner output.\n For example, to enable logging in tests, write the following:\n ```js\n test('I can view all users', function() {\n server.logging = true;\n server.create('user');\n visit('/users');\n // ...\n });\n ```\n You can also write a custom log message using the [Pretender server's `handledRequest` hook](https://github.com/pretenderjs/pretender#handled-requests). (You can access the pretender server from your Mirage server via `server.pretender`.)\n To override,\n ```js\n createServer({\n routes() {\n this.pretender.handledRequest = function(verb, path, request) {\n let { responseText } = request;\n // log request and response data\n }\n }\n })\n ```\n @property logging\n @return {Boolean}\n @public\n */\n\n this.logging = this.logging !== undefined ? this.logging : undefined;\n this.testConfig = this.testConfig || undefined;\n this.trackRequests = _config.trackRequests;\n\n this._defineRouteHandlerHelpers();\n\n if (this.db) {\n this.db.registerIdentityManagers(_config.identityManagers);\n } else {\n this.db = this._container.create(\"Db\", undefined, _config.identityManagers);\n }\n\n if (this.schema) {\n this.schema.registerModels(_config.models);\n this.serializerOrRegistry.registerSerializers(_config.serializers || {});\n } else {\n this.schema = this._container.create(\"Schema\", this.db, _config.models);\n this.serializerOrRegistry = this._container.create(\"SerializerRegistry\", this.schema, _config.serializers);\n }\n\n var hasFactories = this._hasModulesOfType(_config, \"factories\");\n\n var hasDefaultScenario = _config.scenarios && Object.prototype.hasOwnProperty.call(_config.scenarios, \"default\");\n var didOverridePretenderConfig = _config.trackRequests !== undefined && this.pretender;\n assert(!didOverridePretenderConfig, \"You cannot modify Pretender's request tracking once the server is created\");\n /**\n Mirage uses [pretender.js](https://github.com/trek/pretender) as its xhttp interceptor. In your Mirage config, `this.pretender` refers to the actual Pretender instance, so any config options that work there will work here as well.\n ```js\n createServer({\n routes() {\n this.pretender.handledRequest = (verb, path, request) => {\n console.log(`Your server responded to ${path}`);\n }\n }\n })\n ```\n Refer to [Pretender's docs](https://github.com/pretenderjs/pretender) if you want to change any options on your Pretender instance.\n @property pretender\n @return {Object} The Pretender instance\n @public\n */\n\n this.pretender = this.pretender || _config.pretender || createPretender(this);\n\n if (_config.baseConfig) {\n this.loadConfig(_config.baseConfig);\n }\n\n if (this.isTest()) {\n if (_config.testConfig) {\n this.loadConfig(_config.testConfig);\n }\n\n if (typeof window !== \"undefined\") {\n window.server = this; // TODO: Better way to inject server into test env\n }\n }\n\n if (this.isTest() && hasFactories) {\n this.loadFactories(_config.factories);\n } else if (!this.isTest() && hasDefaultScenario) {\n this.loadFactories(_config.factories);\n\n _config.scenarios[\"default\"](this);\n } else {\n this.loadFixtures();\n }\n\n var useDefaultPassthroughs = typeof _config.useDefaultPassthroughs !== \"undefined\" ? _config.useDefaultPassthroughs : true;\n\n if (useDefaultPassthroughs) {\n this._configureDefaultPassthroughs();\n }\n }\n /**\n * Determines if the current environment is the testing environment.\n *\n * @method isTest\n * @return {Boolean} True if the environment is 'test', false otherwise.\n * @public\n * @hide\n */\n\n }, {\n key: \"isTest\",\n value: function isTest() {\n return this.environment === \"test\";\n }\n /**\n Determines if the server should log.\n @method shouldLog\n @return The value of this.logging if defined, or false if in the testing environment,\n true otherwise.\n @public\n @hide\n */\n\n }, {\n key: \"shouldLog\",\n value: function shouldLog() {\n return typeof this.logging !== \"undefined\" ? this.logging : !this.isTest();\n }\n /**\n * Determines if the server should track requests.\n *\n * @method shouldTrackRequests\n * @return The value of this.trackRequests if defined, false otherwise.\n * @public\n * @hide\n */\n\n }, {\n key: \"shouldTrackRequests\",\n value: function shouldTrackRequests() {\n return Boolean(this.trackRequests);\n }\n /**\n * Load the configuration given, setting timing to 0 if in the test\n * environment.\n *\n * @method loadConfig\n * @param {Object} config The configuration to load.\n * @public\n * @hide\n */\n\n }, {\n key: \"loadConfig\",\n value: function loadConfig(config) {\n config.call(this);\n this.timing = this.isTest() ? 0 : this.timing || 0;\n }\n /**\n By default, if your app makes a request that is not defined in your server config, Mirage will throw an error. You can use `passthrough` to whitelist requests, and allow them to pass through your Mirage server to the actual network layer.\n Note: Put all passthrough config at the bottom of your routes, to give your route handlers precedence.\n To ignore paths on your current host (as well as configured `namespace`), use a leading `/`:\n ```js\n this.passthrough('/addresses');\n ```\n You can also pass a list of paths, or call `passthrough` multiple times:\n ```js\n this.passthrough('/addresses', '/contacts');\n this.passthrough('/something');\n this.passthrough('/else');\n ```\n These lines will allow all HTTP verbs to pass through. If you want only certain verbs to pass through, pass an array as the last argument with the specified verbs:\n ```js\n this.passthrough('/addresses', ['post']);\n this.passthrough('/contacts', '/photos', ['get']);\n ```\n You can pass a function to `passthrough` to do a runtime check on whether or not the request should be handled by Mirage. If the function returns `true` Mirage will not handle the request and let it pass through.\n ```js\n this.passthrough(request => {\n return request.queryParams.skipMirage;\n });\n ```\n If you want all requests on the current domain to pass through, simply invoke the method with no arguments:\n ```js\n this.passthrough();\n ```\n Note again that the current namespace (i.e. any `namespace` property defined above this call) will be applied.\n You can also allow other-origin hosts to passthrough. If you use a fully-qualified domain name, the `namespace` property will be ignored. Use two * wildcards to match all requests under a path:\n ```js\n this.passthrough('http://api.foo.bar/**');\n this.passthrough('http://api.twitter.com/v1/cards/**');\n ```\n In versions of Pretender prior to 0.12, `passthrough` only worked with jQuery >= 2.x. As long as you're on Pretender@0.12 or higher, you should be all set.\n @method passthrough\n @param {String} [...paths] Any number of paths to whitelist\n @param {Array} options Unused\n @public\n */\n\n }, {\n key: \"passthrough\",\n value: function passthrough() {\n var _this = this;\n\n for (var _len = arguments.length, paths = new Array(_len), _key = 0; _key < _len; _key++) {\n paths[_key] = arguments[_key];\n } // this only works in browser-like environments for now. in node users will have to configure\n // their own interceptor if they are using one.\n\n\n if (typeof window !== \"undefined\") {\n var verbs = [\"get\", \"post\", \"put\", \"delete\", \"patch\", \"options\", \"head\"];\n var lastArg = paths[paths.length - 1];\n\n if (paths.length === 0) {\n paths = [\"/**\", \"/\"];\n } else if (Array.isArray(lastArg)) {\n verbs = paths.pop();\n }\n\n paths.forEach(function (path) {\n if (typeof path === \"function\") {\n _this.passthroughChecks.push(path);\n } else {\n verbs.forEach(function (verb) {\n var fullPath = _this._getFullPath(path);\n\n _this.pretender[verb](fullPath, _this.pretender.passthrough);\n });\n }\n });\n }\n }\n /**\n By default, `fixtures` will be loaded during testing if you don't have factories defined, and during development if you don't have `seeds` defined. You can use `loadFixtures()` to also load fixture files in either of these environments, in addition to using factories to seed your database.\n `server.loadFixtures()` loads all the files, and `server.loadFixtures(file1, file2...)` loads selective fixture files.\n For example, in a test you may want to start out with all your fixture data loaded:\n ```js\n test('I can view the photos', function() {\n server.loadFixtures();\n server.createList('photo', 10);\n visit('/');\n andThen(() => {\n equal( find('img').length, 10 );\n });\n });\n ```\n or in development, you may want to load a few reference fixture files, and use factories to define the rest of your data:\n ```js\n createServer({\n ...,\n seeds(server) {\n server.loadFixtures('countries', 'states');\n let author = server.create('author');\n server.createList('post', 10, {author_id: author.id});\n }\n })\n ```\n @method loadFixtures\n @param {String} [...args] The name of the fixture to load.\n @public\n */\n\n }, {\n key: \"loadFixtures\",\n value: function loadFixtures() {\n var fixtures = this._config.fixtures;\n\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n if (args.length) {\n var camelizedArgs = args.map(camelize);\n var missingKeys = camelizedArgs.filter(function (key) {\n return !fixtures[key];\n });\n\n if (missingKeys.length) {\n throw new Error(\"Fixtures not found: \".concat(missingKeys.join(\", \")));\n }\n\n fixtures = pick.apply(void 0, [fixtures].concat(_toConsumableArray(camelizedArgs)));\n }\n\n this.db.loadData(fixtures);\n }\n /*\n Factory methods\n */\n\n /**\n * Load factories into Mirage's database.\n *\n * @method loadFactories\n * @param {Object} factoryMap\n * @public\n * @hide\n */\n\n }, {\n key: \"loadFactories\",\n value: function loadFactories() {\n var _this2 = this;\n\n var factoryMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // Store a reference to the factories\n\n var currentFactoryMap = this._factoryMap || {};\n this._factoryMap = assign(currentFactoryMap, factoryMap); // Create a collection for each factory\n\n Object.keys(factoryMap).forEach(function (type) {\n var collectionName = _this2.schema.toCollectionName(type);\n\n _this2.db.createCollection(collectionName);\n });\n }\n /**\n * Get the factory for a given type.\n *\n * @method factoryFor\n * @param {String} type\n * @private\n * @hide\n */\n\n }, {\n key: \"factoryFor\",\n value: function factoryFor(type) {\n var camelizedType = camelize(type);\n\n if (this._factoryMap && this._factoryMap[camelizedType]) {\n return this._factoryMap[camelizedType];\n }\n }\n }, {\n key: \"build\",\n value: function build(type) {\n for (var _len3 = arguments.length, traitsAndOverrides = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n traitsAndOverrides[_key3 - 1] = arguments[_key3];\n }\n\n var traits = traitsAndOverrides.filter(function (arg) {\n return arg && typeof arg === \"string\";\n });\n var overrides = find(traitsAndOverrides, function (arg) {\n return isPlainObject(arg);\n });\n var camelizedType = camelize(type); // Store sequence for factory type as instance variable\n\n this.factorySequences = this.factorySequences || {};\n this.factorySequences[camelizedType] = this.factorySequences[camelizedType] + 1 || 0;\n var OriginalFactory = this.factoryFor(type);\n\n if (OriginalFactory) {\n OriginalFactory = OriginalFactory.extend({});\n var attrs = OriginalFactory.attrs || {};\n\n this._validateTraits(traits, OriginalFactory, type);\n\n var mergedExtensions = this._mergeExtensions(attrs, traits, overrides);\n\n this._mapAssociationsFromAttributes(type, attrs, overrides);\n\n this._mapAssociationsFromAttributes(type, mergedExtensions);\n\n var Factory = OriginalFactory.extend(mergedExtensions);\n var factory = new Factory();\n var sequence = this.factorySequences[camelizedType];\n return factory.build(sequence);\n } else {\n return overrides;\n }\n }\n }, {\n key: \"buildList\",\n value: function buildList(type, amount) {\n assert(isInteger(amount), \"second argument has to be an integer, you passed: \".concat(_typeof(amount)));\n var list = [];\n\n for (var _len4 = arguments.length, traitsAndOverrides = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {\n traitsAndOverrides[_key4 - 2] = arguments[_key4];\n }\n\n var buildArgs = [type].concat(traitsAndOverrides);\n\n for (var i = 0; i < amount; i++) {\n list.push(this.build.apply(this, buildArgs));\n }\n\n return list;\n }\n /**\n Generates a single model of type *type*, inserts it into the database (giving it an id), and returns the data that was\n added.\n ```js\n test(\"I can view a contact's details\", function() {\n let contact = server.create('contact');\n visit('/contacts/' + contact.id);\n andThen(() => {\n equal( find('h1').text(), 'The contact is Link');\n });\n });\n ```\n You can override the attributes from the factory definition with a\n hash passed in as the second parameter. For example, if we had this factory\n ```js\n export default Factory.extend({\n name: 'Link'\n });\n ```\n we could override the name like this:\n ```js\n test(\"I can view the contacts\", function() {\n server.create('contact', {name: 'Zelda'});\n visit('/');\n andThen(() => {\n equal( find('p').text(), 'Zelda' );\n });\n });\n ```\n @method create\n @param type the singularized type of the model\n @param traitsAndOverrides\n @public\n */\n\n }, {\n key: \"create\",\n value: function create(type) {\n var _this3 = this;\n\n assert(this._modelOrFactoryExistsForType(type), \"You called server.create('\".concat(type, \"') but no model or factory was found. Make sure you're passing in the singularized version of the model or factory name.\")); // When there is a Model defined, we should return an instance\n // of it instead of returning the bare attributes.\n\n for (var _len5 = arguments.length, options = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {\n options[_key5 - 1] = arguments[_key5];\n }\n\n var traits = options.filter(function (arg) {\n return arg && typeof arg === \"string\";\n });\n var overrides = find(options, function (arg) {\n return isPlainObject(arg);\n });\n var collectionFromCreateList = find(options, function (arg) {\n return arg && Array.isArray(arg);\n });\n var attrs = this.build.apply(this, [type].concat(_toConsumableArray(traits), [overrides]));\n var modelOrRecord;\n\n if (this.schema && this.schema[this.schema.toCollectionName(type)]) {\n var modelClass = this.schema[this.schema.toCollectionName(type)];\n modelOrRecord = modelClass.create(attrs);\n } else {\n var collection, collectionName;\n\n if (collectionFromCreateList) {\n collection = collectionFromCreateList;\n } else {\n collectionName = this.schema ? this.schema.toInternalCollectionName(type) : \"_\".concat(this.inflector.pluralize(type));\n collection = this.db[collectionName];\n }\n\n assert(collection, \"You called server.create('\".concat(type, \"') but no model or factory was found.\"));\n modelOrRecord = collection.insert(attrs);\n }\n\n var OriginalFactory = this.factoryFor(type);\n\n if (OriginalFactory) {\n OriginalFactory.extractAfterCreateCallbacks({\n traits: traits\n }).forEach(function (afterCreate) {\n afterCreate(modelOrRecord, _this3);\n });\n }\n\n return modelOrRecord;\n }\n /**\n Creates *amount* models of type *type*, optionally overriding the attributes from the factory with *attrs*.\n Returns the array of records that were added to the database.\n Here's an example from a test:\n ```js\n test(\"I can view the contacts\", function() {\n server.createList('contact', 5);\n let youngContacts = server.createList('contact', 5, {age: 15});\n visit('/');\n andThen(function() {\n equal(currentRouteName(), 'index');\n equal( find('p').length, 10 );\n });\n });\n ```\n And one from setting up your development database:\n ```js\n createServer({\n seeds(server) {\n let contact = server.create('contact')\n server.createList('address', 5, { contact })\n }\n })\n ```\n @method createList\n @param type\n @param amount\n @param traitsAndOverrides\n @public\n */\n\n }, {\n key: \"createList\",\n value: function createList(type, amount) {\n assert(this._modelOrFactoryExistsForType(type), \"You called server.createList('\".concat(type, \"') but no model or factory was found. Make sure you're passing in the singularized version of the model or factory name.\"));\n assert(isInteger(amount), \"second argument has to be an integer, you passed: \".concat(_typeof(amount)));\n var list = [];\n var collectionName = this.schema ? this.schema.toInternalCollectionName(type) : \"_\".concat(this.inflector.pluralize(type));\n var collection = this.db[collectionName];\n\n for (var _len6 = arguments.length, traitsAndOverrides = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {\n traitsAndOverrides[_key6 - 2] = arguments[_key6];\n }\n\n var createArguments = [type].concat(traitsAndOverrides, [collection]);\n\n for (var i = 0; i < amount; i++) {\n list.push(this.create.apply(this, createArguments));\n }\n\n return list;\n }\n /**\n Shutdown the server and stop intercepting network requests.\n @method shutdown\n @public\n */\n\n }, {\n key: \"shutdown\",\n value: function shutdown() {\n if (typeof window !== \"undefined\") {\n this.pretender.shutdown();\n }\n\n if (typeof window !== \"undefined\" && this.environment === \"test\") {\n window.server = undefined;\n }\n }\n }, {\n key: \"resource\",\n value: function resource(resourceName) {\n var _this4 = this;\n\n var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n only = _ref.only,\n except = _ref.except,\n path = _ref.path;\n\n resourceName = this.inflector.pluralize(resourceName);\n path = path || \"/\".concat(resourceName);\n only = only || [];\n except = except || [];\n\n if (only.length > 0 && except.length > 0) {\n throw \"cannot use both :only and :except options\";\n }\n\n var actionsMethodsAndsPathsMappings = {\n index: {\n methods: [\"get\"],\n path: \"\".concat(path)\n },\n show: {\n methods: [\"get\"],\n path: \"\".concat(path, \"/:id\")\n },\n create: {\n methods: [\"post\"],\n path: \"\".concat(path)\n },\n update: {\n methods: [\"put\", \"patch\"],\n path: \"\".concat(path, \"/:id\")\n },\n \"delete\": {\n methods: [\"del\"],\n path: \"\".concat(path, \"/:id\")\n }\n };\n var allActions = Object.keys(actionsMethodsAndsPathsMappings);\n var actions = only.length > 0 && only || except.length > 0 && allActions.filter(function (action) {\n return except.indexOf(action) === -1;\n }) || allActions;\n actions.forEach(function (action) {\n var methodsWithPath = actionsMethodsAndsPathsMappings[action];\n methodsWithPath.methods.forEach(function (method) {\n return path === resourceName ? _this4[method](methodsWithPath.path) : _this4[method](methodsWithPath.path, resourceName);\n });\n });\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_defineRouteHandlerHelpers\",\n value: function _defineRouteHandlerHelpers() {\n var _this5 = this;\n\n [[\"get\"], [\"post\"], [\"put\"], [\"delete\", \"del\"], [\"patch\"], [\"head\"], [\"options\"]].forEach(function (_ref2) {\n var _ref3 = _slicedToArray(_ref2, 2),\n verb = _ref3[0],\n alias = _ref3[1];\n\n _this5[verb] = function (path) {\n for (var _len7 = arguments.length, args = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {\n args[_key7 - 1] = arguments[_key7];\n }\n\n var _extractRouteArgument = extractRouteArguments(args),\n _extractRouteArgument2 = _slicedToArray(_extractRouteArgument, 3),\n rawHandler = _extractRouteArgument2[0],\n customizedCode = _extractRouteArgument2[1],\n options = _extractRouteArgument2[2];\n\n return _this5._registerRouteHandler(verb, path, rawHandler, customizedCode, options);\n };\n\n if (alias) {\n _this5[alias] = _this5[verb];\n }\n });\n }\n }, {\n key: \"_serialize\",\n value: function _serialize(body) {\n if (typeof body === \"string\") {\n return body;\n } else {\n return JSON.stringify(body);\n }\n }\n }, {\n key: \"_registerRouteHandler\",\n value: function _registerRouteHandler(verb, path, rawHandler, customizedCode, options) {\n var _this6 = this;\n\n var routeHandler = this._container.create(\"RouteHandler\", {\n schema: this.schema,\n verb: verb,\n rawHandler: rawHandler,\n customizedCode: customizedCode,\n options: options,\n path: path,\n serializerOrRegistry: this.serializerOrRegistry\n });\n\n var fullPath = this._getFullPath(path);\n\n var timing = options.timing !== undefined ? options.timing : function () {\n return _this6.timing;\n };\n\n if (this.pretender) {\n return this.pretender[verb](fullPath, function (request) {\n return routeHandler.handle(request).then(function (mirageResponse) {\n var _mirageResponse = _slicedToArray(mirageResponse, 3),\n code = _mirageResponse[0],\n headers = _mirageResponse[1],\n response = _mirageResponse[2];\n\n return [code, headers, _this6._serialize(response)];\n });\n }, timing);\n }\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_hasModulesOfType\",\n value: function _hasModulesOfType(modules, type) {\n var modulesOfType = modules[type];\n return modulesOfType ? Object.keys(modulesOfType).length > 0 : false;\n }\n /**\n * Builds a full path for Pretender to monitor based on the `path` and\n * configured options (`urlPrefix` and `namespace`).\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_getFullPath\",\n value: function _getFullPath(path) {\n path = path[0] === \"/\" ? path.slice(1) : path;\n var fullPath = \"\";\n var urlPrefix = this.urlPrefix ? this.urlPrefix.trim() : \"\";\n var namespace = \"\"; // if there is a urlPrefix and a namespace\n\n if (this.urlPrefix && this.namespace) {\n if (this.namespace[0] === \"/\" && this.namespace[this.namespace.length - 1] === \"/\") {\n namespace = this.namespace.substring(0, this.namespace.length - 1).substring(1);\n }\n\n if (this.namespace[0] === \"/\" && this.namespace[this.namespace.length - 1] !== \"/\") {\n namespace = this.namespace.substring(1);\n }\n\n if (this.namespace[0] !== \"/\" && this.namespace[this.namespace.length - 1] === \"/\") {\n namespace = this.namespace.substring(0, this.namespace.length - 1);\n }\n\n if (this.namespace[0] !== \"/\" && this.namespace[this.namespace.length - 1] !== \"/\") {\n namespace = this.namespace;\n }\n } // if there is a namespace and no urlPrefix\n\n\n if (this.namespace && !this.urlPrefix) {\n if (this.namespace[0] === \"/\" && this.namespace[this.namespace.length - 1] === \"/\") {\n namespace = this.namespace.substring(0, this.namespace.length - 1);\n }\n\n if (this.namespace[0] === \"/\" && this.namespace[this.namespace.length - 1] !== \"/\") {\n namespace = this.namespace;\n }\n\n if (this.namespace[0] !== \"/\" && this.namespace[this.namespace.length - 1] === \"/\") {\n var namespaceSub = this.namespace.substring(0, this.namespace.length - 1);\n namespace = \"/\".concat(namespaceSub);\n }\n\n if (this.namespace[0] !== \"/\" && this.namespace[this.namespace.length - 1] !== \"/\") {\n namespace = \"/\".concat(this.namespace);\n }\n } // if no namespace\n\n\n if (!this.namespace) {\n namespace = \"\";\n } // check to see if path is a FQDN. if so, ignore any urlPrefix/namespace that was set\n\n\n if (/^https?:\\/\\//.test(path)) {\n fullPath += path;\n } else {\n // otherwise, if there is a urlPrefix, use that as the beginning of the path\n if (urlPrefix.length) {\n fullPath += urlPrefix[urlPrefix.length - 1] === \"/\" ? urlPrefix : \"\".concat(urlPrefix, \"/\");\n } // add the namespace to the path\n\n\n fullPath += namespace; // add a trailing slash to the path if it doesn't already contain one\n\n if (fullPath[fullPath.length - 1] !== \"/\") {\n fullPath += \"/\";\n } // finally add the configured path\n\n\n fullPath += path; // if we're making a same-origin request, ensure a / is prepended and\n // dedup any double slashes\n\n if (!/^https?:\\/\\//.test(fullPath)) {\n fullPath = \"/\".concat(fullPath);\n fullPath = fullPath.replace(/\\/+/g, \"/\");\n }\n }\n\n return fullPath;\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_configureDefaultPassthroughs\",\n value: function _configureDefaultPassthroughs() {\n var _this7 = this;\n\n defaultPassthroughs.forEach(function (passthroughUrl) {\n _this7.passthrough(passthroughUrl);\n });\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_typeIsPluralForModel\",\n value: function _typeIsPluralForModel(typeOrCollectionName) {\n if (typeof isPluralForModelCache[typeOrCollectionName] !== \"boolean\") {\n var modelOrFactoryExists = this._modelOrFactoryExistsForTypeOrCollectionName(typeOrCollectionName);\n\n var isPlural = typeOrCollectionName === this.inflector.pluralize(typeOrCollectionName);\n var isUncountable = this.inflector.singularize(typeOrCollectionName) === this.inflector.pluralize(typeOrCollectionName);\n var isPluralForModel = isPlural && !isUncountable && modelOrFactoryExists;\n isPluralForModelCache[typeOrCollectionName] = isPluralForModel;\n }\n\n return isPluralForModelCache[typeOrCollectionName];\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_modelOrFactoryExistsForType\",\n value: function _modelOrFactoryExistsForType(type) {\n var modelExists = this.schema && this.schema.modelFor(camelize(type));\n var dbCollectionExists = this.db[this.schema.toInternalCollectionName(type)];\n return (modelExists || dbCollectionExists) && !this._typeIsPluralForModel(type);\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_modelOrFactoryExistsForTypeOrCollectionName\",\n value: function _modelOrFactoryExistsForTypeOrCollectionName(typeOrCollectionName) {\n var modelExists = this.schema && this.schema.modelFor(camelize(typeOrCollectionName));\n var dbCollectionExists = this.db[this.schema.toInternalCollectionName(typeOrCollectionName)];\n return modelExists || dbCollectionExists;\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_validateTraits\",\n value: function _validateTraits(traits, factory, type) {\n traits.forEach(function (traitName) {\n if (!factory.isTrait(traitName)) {\n throw new Error(\"'\".concat(traitName, \"' trait is not registered in '\").concat(type, \"' factory\"));\n }\n });\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_mergeExtensions\",\n value: function _mergeExtensions(attrs, traits, overrides) {\n var allExtensions = traits.map(function (traitName) {\n return attrs[traitName].extension;\n });\n allExtensions.push(overrides || {});\n return allExtensions.reduce(function (accum, extension) {\n return assign(accum, extension);\n }, {});\n }\n /**\n *\n * @private\n * @hide\n */\n\n }, {\n key: \"_mapAssociationsFromAttributes\",\n value: function _mapAssociationsFromAttributes(modelName, attributes) {\n var _this8 = this;\n\n var overrides = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n Object.keys(attributes || {}).filter(function (attr) {\n return isAssociation(attributes[attr]);\n }).forEach(function (attr) {\n var modelClass = _this8.schema.modelClassFor(modelName);\n\n var association = modelClass.associationFor(attr);\n assert(association && association instanceof BelongsTo, \"You're using the `association` factory helper on the '\".concat(attr, \"' attribute of your \").concat(modelName, \" factory, but that attribute is not a `belongsTo` association.\"));\n var isSelfReferentialBelongsTo = association && association instanceof BelongsTo && association.modelName === modelName;\n assert(!isSelfReferentialBelongsTo, \"You're using the association() helper on your \".concat(modelName, \" factory for \").concat(attr, \", which is a belongsTo self-referential relationship. You can't do this as it will lead to infinite recursion. You can move the helper inside of a trait and use it selectively.\"));\n var isPolymorphic = association && association.opts && association.opts.polymorphic;\n assert(!isPolymorphic, \"You're using the association() helper on your \".concat(modelName, \" factory for \").concat(attr, \", which is a polymorphic relationship. This is not currently supported.\"));\n var factoryAssociation = attributes[attr];\n var foreignKey = \"\".concat(camelize(attr), \"Id\");\n\n if (!overrides[attr]) {\n attributes[foreignKey] = _this8.create.apply(_this8, [association.modelName].concat(_toConsumableArray(factoryAssociation.traitsAndOverrides))).id;\n }\n\n delete attributes[attr];\n });\n }\n }]);\n\n return Server;\n}();\n\nvar ActiveModelSerializer = Serializer.extend({\n serializeIds: \"always\",\n normalizeIds: true,\n keyForModel: function keyForModel(type) {\n return underscore(type);\n },\n keyForAttribute: function keyForAttribute(attr) {\n return underscore(attr);\n },\n keyForRelationship: function keyForRelationship(type) {\n return this._container.inflector.pluralize(underscore(type));\n },\n keyForEmbeddedRelationship: function keyForEmbeddedRelationship(attributeName) {\n return underscore(attributeName);\n },\n keyForRelationshipIds: function keyForRelationshipIds(type) {\n return \"\".concat(underscore(this._container.inflector.singularize(type)), \"_ids\");\n },\n keyForForeignKey: function keyForForeignKey(relationshipName) {\n return \"\".concat(underscore(relationshipName), \"_id\");\n },\n keyForPolymorphicForeignKeyId: function keyForPolymorphicForeignKeyId(relationshipName) {\n return \"\".concat(underscore(relationshipName), \"_id\");\n },\n keyForPolymorphicForeignKeyType: function keyForPolymorphicForeignKeyType(relationshipName) {\n return \"\".concat(underscore(relationshipName), \"_type\");\n },\n normalize: function normalize(payload) {\n var _this = this;\n\n var type = Object.keys(payload)[0];\n var attrs = payload[type];\n var modelName = camelize(type);\n var modelClass = this.schema.modelClassFor(modelName);\n var belongsToAssociations = modelClass.belongsToAssociations,\n hasManyAssociations = modelClass.hasManyAssociations;\n var belongsToKeys = Object.keys(belongsToAssociations);\n var hasManyKeys = Object.keys(hasManyAssociations);\n var jsonApiPayload = {\n data: {\n type: this._container.inflector.pluralize(type),\n attributes: {}\n }\n };\n\n if (attrs.id) {\n jsonApiPayload.data.id = attrs.id;\n }\n\n var relationships = {};\n Object.keys(attrs).forEach(function (key) {\n if (key !== \"id\") {\n if (_this.normalizeIds) {\n if (belongsToKeys.includes(key)) {\n var association = belongsToAssociations[key];\n var associationModel = association.modelName;\n relationships[dasherize(key)] = {\n data: {\n type: associationModel,\n id: attrs[key]\n }\n };\n } else if (hasManyKeys.includes(key)) {\n var _association = hasManyAssociations[key];\n var _associationModel = _association.modelName;\n var data = attrs[key].map(function (id) {\n return {\n type: _associationModel,\n id: id\n };\n });\n relationships[dasherize(key)] = {\n data: data\n };\n } else {\n jsonApiPayload.data.attributes[dasherize(key)] = attrs[key];\n }\n } else {\n jsonApiPayload.data.attributes[dasherize(key)] = attrs[key];\n }\n }\n });\n\n if (Object.keys(relationships).length) {\n jsonApiPayload.data.relationships = relationships;\n }\n\n return jsonApiPayload;\n },\n getCoalescedIds: function getCoalescedIds(request) {\n return request.queryParams && request.queryParams.ids;\n }\n});\nvar restSerializer = ActiveModelSerializer.extend({\n serializeIds: \"always\",\n keyForModel: function keyForModel(type) {\n return camelize(type);\n },\n keyForAttribute: function keyForAttribute(attr) {\n return camelize(attr);\n },\n keyForRelationship: function keyForRelationship(type) {\n return camelize(this._container.inflector.pluralize(type));\n },\n keyForEmbeddedRelationship: function keyForEmbeddedRelationship(attributeName) {\n return camelize(attributeName);\n },\n keyForRelationshipIds: function keyForRelationshipIds(type) {\n return camelize(this._container.inflector.pluralize(type));\n },\n keyForForeignKey: function keyForForeignKey(relationshipName) {\n return camelize(this._container.inflector.singularize(relationshipName));\n },\n getCoalescedIds: function getCoalescedIds(request) {\n return request.queryParams && request.queryParams.ids;\n }\n});\n/**\n UUID generator\n\n @hide\n*/\n\nfunction uuid() {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, function (c) {\n var r = Math.random() * 16 | 0;\n var v = c === \"x\" ? r : r & 0x3 | 0x8;\n return v.toString(16);\n });\n}\n/**\n @hide\n*/\n\n\nfunction hasMany() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _construct(HasMany, args);\n}\n/**\n @hide\n*/\n\n\nfunction belongsTo() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return _construct(BelongsTo, args);\n}\n\nvar index = {\n Factory: Factory,\n Response: Response,\n hasMany: hasMany,\n belongsTo: belongsTo\n};\nexport { ActiveModelSerializer, Collection, Factory, IdentityManager, JSONAPISerializer, Model, Response, restSerializer as RestSerializer, Serializer, Server, Db as _Db, DbCollection as _DbCollection, RouteHandler as _RouteHandler, SerializerRegistry as _SerializerRegistry, assert as _assert, Association as _ormAssociationsAssociation, BelongsTo as _ormAssociationsBelongsTo, HasMany as _ormAssociationsHasMany, PolymorphicCollection as _ormPolymorphicCollection, Schema as _ormSchema, BaseRouteHandler as _routeHandlersBase, FunctionRouteHandler as _routeHandlersFunction, ObjectRouteHandler as _routeHandlersObject, BaseShorthandRouteHandler as _routeHandlersShorthandsBase, DeleteShorthandRouteHandler as _routeHandlersShorthandsDelete, GetShorthandRouteHandler as _routeHandlersShorthandsGet, HeadShorthandRouteHandler as _routeHandlersShorthandsHead, PostShorthandRouteHandler as _routeHandlersShorthandsPost, PutShorthandRouteHandler as _routeHandlersShorthandsPut, extend as _utilsExtend, camelize as _utilsInflectorCamelize, capitalize as _utilsInflectorCapitalize, dasherize as _utilsInflectorDasherize, underscore as _utilsInflectorUnderscore, isAssociation as _utilsIsAssociation, referenceSort as _utilsReferenceSort, uuid as _utilsUuid, association, belongsTo, createServer, index as default, defaultPassthroughs, hasMany, trait };"],"sourceRoot":""}