(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i { typeStripped = element._type.replace(/QDM::/, ''); dataElementsInit.push(new AllDataElements[typeStripped](element)); }); this.set({ dataElements: dataElementsInit }); }; QDMPatientSchema.methods.id = function id() { return this._id; }; // Returns an array of elements that exist on this patient, that // match the given HQMF data criteria OID. QDMPatientSchema.methods.getByHqmfOid = function getByHqmfOid(hqmfOid) { return this.dataElements.filter(element => element.hqmfOid === hqmfOid); }; // Returns an array of elements that exist on this patient, that // match the given QRDA data criteria OID. QDMPatientSchema.methods.getByQrdaOid = function getByQrdaOid(qrdaOid) { return this.dataElements.filter(element => element.qrdaOid === qrdaOid); }; // Returns an array of elements that exist on this patient. Optionally // takes a qdmCategory, which returns all elements of that QDM qdmCategory. // Example: patient.getDataElements({qdmCategory: 'encounters'}) will return // all Encounter QDM data types active on the patient. QDMPatientSchema.methods.getDataElements = function getDataElements(params) { if (params !== undefined && params.qdmCategory !== undefined && params.qdmStatus !== undefined) { return this.dataElements.filter(element => (element.qdmCategory === params.qdmCategory) && (element.qdmStatus === params.qdmStatus)); } else if (params !== undefined && params.qdmCategory !== undefined) { return this.dataElements.filter(element => element.qdmCategory === params.qdmCategory); } return this.dataElements; }; // Returns an array of dataElements that exist on the patient, queried by // QDM profile // @param {string} profile - the data criteria requested by the execution engine // @param {boolean} isNegated - whether dataElements should be returned based on their negation status // @returns {DataElement[]} QDMPatientSchema.methods.getByProfile = function getByProfile(profile, isNegated = null) { // If isNegated == true, only return data elements with a negationRationale that is not null. // If isNegated == false, only return data elements with a null negationRationale. // If isNegated == null, return all matching data elements by type, regardless of negationRationale. const results = this.dataElements.filter(element => (element._type === `QDM::${profile}` || element._type === profile) && (isNegated === null || !!element.negationRationale === isNegated)); return results.map((result) => { const removedMongooseItems = new AllDataElements[profile](result).toObject({ virtuals: true }); // toObject() will remove all mongoose functions but also remove the schema methods, so we add them back Object.entries(result.schema.methods).forEach(([method_name, method]) => { removedMongooseItems[method_name] = method; }); return removedMongooseItems; }); }; // This method is called by the CQL execution engine on a CQLPatient when // the execution engine wants information on a record. A record could be patient // characteristic information about the patient, or it could be data criteria // that currently exist on this patient (data criteria you drag on a patient // in Bonnie patient builder). // @param {String} profile - the data criteria requested by the execution engine // @returns {Object} QDMPatientSchema.methods.findRecords = function findRecords(profile) { // Clear profile cache for this patient if there is no cache or the patient has changed if (QDMPatientSchema.dataElementCache == null || QDMPatientSchema.dataElementCachePatientId !== this._id) { QDMPatientSchema.dataElementCache = {}; QDMPatientSchema.dataElementCachePatientId = this._id; } // If there is a cache 'hit', return it if (Object.prototype.hasOwnProperty.call(QDMPatientSchema.dataElementCache, profile)) { return QDMPatientSchema.dataElementCache[profile]; } let profileStripped; if (profile === 'Patient') { // Requested generic patient info const info = { birthDatetime: this.birthDatetime }; QDMPatientSchema.dataElementCache[profile] = [info]; return [info]; } else if (/PatientCharacteristic/.test(profile)) { // Requested a patient characteristic profileStripped = profile.replace(/ *\{[^)]*\} */g, ''); QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped); return QDMPatientSchema.dataElementCache[profile]; } else if (profile != null) { // Requested something else (probably a QDM data type). // Strip model details from request. The requested profile string contains // a lot of things we do not need or care about. Example, we might see // something like: // "{urn:healthit-gov:qdm:v5_0_draft}PatientCharacteristicEthnicity" // Where we only care about: "PatientCharacteristicEthnicity". profileStripped = profile.replace(/ *\{[^)]*\} */g, ''); // Check and handle negation status if (/Positive/.test(profileStripped)) { profileStripped = profileStripped.replace(/Positive/, ''); // Since the data criteria is 'Positive', it is not negated. QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped, false); return QDMPatientSchema.dataElementCache[profile]; } else if (/Negative/.test(profileStripped)) { profileStripped = profileStripped.replace(/Negative/, ''); // Since the data criteria is 'Negative', it is negated. QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped, true); return QDMPatientSchema.dataElementCache[profile]; } // No negation status, proceed normally QDMPatientSchema.dataElementCache[profile] = this.getByProfile(profileStripped); return QDMPatientSchema.dataElementCache[profile]; } return []; }; QDMPatientSchema.methods.adverse_events = function adverse_events() { return this.getDataElements({ qdmCategory: 'adverse_event' }); }; QDMPatientSchema.methods.allergies = function allergies() { return this.getDataElements({ qdmCategory: 'allergy' }); }; QDMPatientSchema.methods.assessments = function assessments() { return this.getDataElements({ qdmCategory: 'assessment' }); }; QDMPatientSchema.methods.care_experiences = function care_experiences() { return this.getDataElements({ qdmCategory: 'care_experience' }); }; QDMPatientSchema.methods.care_goals = function care_goals() { return this.getDataElements({ qdmCategory: 'care_goal' }); }; QDMPatientSchema.methods.communications = function communications() { return this.getDataElements({ qdmCategory: 'communication' }); }; QDMPatientSchema.methods.conditions = function conditions() { return this.getDataElements({ qdmCategory: 'condition' }); }; QDMPatientSchema.methods.devices = function devices() { return this.getDataElements({ qdmCategory: 'device' }); }; QDMPatientSchema.methods.diagnostic_studies = function diagnostic_studies() { return this.getDataElements({ qdmCategory: 'diagnostic_study' }); }; QDMPatientSchema.methods.encounters = function encounters() { return this.getDataElements({ qdmCategory: 'encounter' }); }; QDMPatientSchema.methods.family_history = function family_history() { return this.getDataElements({ qdmCategory: 'family_history' }); }; QDMPatientSchema.methods.functional_statuses = function functional_statuses() { return this.getDataElements({ qdmCategory: 'functional_status' }); }; QDMPatientSchema.methods.immunizations = function immunizations() { return this.getDataElements({ qdmCategory: 'immunization' }); }; QDMPatientSchema.methods.interventions = function interventions() { return this.getDataElements({ qdmCategory: 'intervention' }); }; QDMPatientSchema.methods.laboratory_tests = function laboratory_tests() { return this.getDataElements({ qdmCategory: 'laboratory_test' }); }; QDMPatientSchema.methods.medical_equipment = function medical_equipment() { return this.getDataElements({ qdmCategory: 'medical_equipment' }); }; QDMPatientSchema.methods.medications = function medications() { return this.getDataElements({ qdmCategory: 'medication' }); }; QDMPatientSchema.methods.patient_characteristics = function patient_characteristics() { return this.getDataElements({ qdmCategory: 'patient_characteristic' }); }; QDMPatientSchema.methods.physical_exams = function physical_exams() { return this.getDataElements({ qdmCategory: 'physical_exam' }); }; QDMPatientSchema.methods.preferences = function preferences() { return this.getDataElements({ qdmCategory: 'preference' }); }; QDMPatientSchema.methods.procedures = function procedures() { return this.getDataElements({ qdmCategory: 'procedure' }); }; QDMPatientSchema.methods.results = function results() { return this.getDataElements({ qdmCategory: 'result' }); }; QDMPatientSchema.methods.risk_category_assessments = function risk_category_assessments() { return this.getDataElements({ qdmCategory: 'risk_category_assessment' }); }; QDMPatientSchema.methods.social_history = function social_history() { return this.getDataElements({ qdmCategory: 'social_history' }); }; QDMPatientSchema.methods.substances = function substances() { return this.getDataElements({ qdmCategory: 'substance' }); }; QDMPatientSchema.methods.symptoms = function symptoms() { return this.getDataElements({ qdmCategory: 'symptom' }); }; QDMPatientSchema.methods.system_characteristics = function system_characteristics() { return this.getDataElements({ qdmCategory: 'system_characteristic' }); }; QDMPatientSchema.methods.transfers = function transfers() { return this.getDataElements({ qdmCategory: 'transfer' }); }; QDMPatientSchema.methods.vital_signs = function vital_signs() { return this.getDataElements({ qdmCategory: 'vital_sign' }); }; QDMPatientSchema.clearDataElementCache = function clearDataElementCache() { QDMPatientSchema.dataElementCachePatientId = null; QDMPatientSchema.dataElementCache = null; }; module.exports.QDMPatientSchema = QDMPatientSchema; class QDMPatient extends mongoose.Document { constructor(object) { super(object, QDMPatientSchema); this.initializeDataElements(); } } module.exports.QDMPatient = QDMPatient; },{"./AllDataElements":2,"./basetypes/Code":69,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/Quantity":74,"mongoose/browser":258}],51:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const RelatedPersonSchema = DataElementSchema({ identifier: IdentifierSchema, linkedPatientId: String, qdmTitle: { type: String, default: 'Related Person' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.141' }, qdmCategory: { type: String, default: 'related_person' }, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::RelatedPerson' }, }); module.exports.RelatedPersonSchema = RelatedPersonSchema; class RelatedPerson extends mongoose.Document { constructor(object) { super(object, RelatedPersonSchema); this._type = 'QDM::RelatedPerson'; } } module.exports.RelatedPerson = RelatedPerson; },{"./attributes/Component":58,"./attributes/Entity":60,"./attributes/FacilityLocation":61,"./attributes/Identifier":62,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":258}],52:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const PlaceholderResultSchema = mongoose.Schema({ cache_id: String, measure_id: String, sub_id: String, test_id: String, effective_date: Number, filters: Object, prefilter: Object, calculation_time: Date, status: Object, population_ids: Object, STRAT: Number, IPP: Number, DENOM: Number, NUMER: Number, NUMEX: Number, DENEX: Number, DENEXCEP: Number, MSRPOPL: Number, OBSERV: Number, MSRPOPLEX: Number, supplemental_data: Object, }); module.exports.ResultSchema = PlaceholderResultSchema; class PlaceholderResult extends mongoose.Document { constructor(object) { super(object, PlaceholderResultSchema); } } module.exports.PlaceholderResult = PlaceholderResult; },{"mongoose/browser":258}],53:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceAdministeredSchema = DataElementSchema({ authorDatetime: DateTime, relevantDatetime: DateTime, relevantPeriod: Interval, dosage: Quantity, frequency: Code, route: Code, negationRationale: Code, performer: AnyEntity, qdmTitle: { type: String, default: 'Substance, Administered' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.73' }, qdmCategory: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'administered' }, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::SubstanceAdministered' }, }); module.exports.SubstanceAdministeredSchema = SubstanceAdministeredSchema; class SubstanceAdministered extends mongoose.Document { constructor(object) { super(object, SubstanceAdministeredSchema); this._type = 'QDM::SubstanceAdministered'; } } module.exports.SubstanceAdministered = SubstanceAdministered; },{"./attributes/Component":58,"./attributes/Entity":60,"./attributes/FacilityLocation":61,"./attributes/Identifier":62,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":258}],54:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceOrderSchema = DataElementSchema({ authorDatetime: DateTime, relevantPeriod: Interval, reason: Code, dosage: Quantity, supply: Quantity, frequency: Code, refills: Number, route: Code, negationRationale: Code, requester: AnyEntity, qdmTitle: { type: String, default: 'Substance, Order' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.77' }, qdmCategory: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'order' }, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::SubstanceOrder' }, }); module.exports.SubstanceOrderSchema = SubstanceOrderSchema; class SubstanceOrder extends mongoose.Document { constructor(object) { super(object, SubstanceOrderSchema); this._type = 'QDM::SubstanceOrder'; } } module.exports.SubstanceOrder = SubstanceOrder; },{"./attributes/Component":58,"./attributes/Entity":60,"./attributes/FacilityLocation":61,"./attributes/Identifier":62,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":258}],55:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceRecommendedSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, dosage: Quantity, frequency: Code, refills: Number, route: Code, negationRationale: Code, requester: AnyEntity, qdmTitle: { type: String, default: 'Substance, Recommended' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.78' }, qdmCategory: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'recommended' }, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::SubstanceRecommended' }, }); module.exports.SubstanceRecommendedSchema = SubstanceRecommendedSchema; class SubstanceRecommended extends mongoose.Document { constructor(object) { super(object, SubstanceRecommendedSchema); this._type = 'QDM::SubstanceRecommended'; } } module.exports.SubstanceRecommended = SubstanceRecommended; },{"./attributes/Component":58,"./attributes/Entity":60,"./attributes/FacilityLocation":61,"./attributes/Identifier":62,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":258}],56:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./attributes/Identifier'); const { DataElementSchema } = require('./basetypes/DataElement'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const QDMDate = require('./basetypes/QDMDate'); const Any = require('./basetypes/Any'); const AnyEntity = require('./basetypes/AnyEntity'); const { ComponentSchema } = require('./attributes/Component'); const { FacilityLocationSchema } = require('./attributes/FacilityLocation'); const { EntitySchema } = require('./attributes/Entity'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SymptomSchema = DataElementSchema({ prevalencePeriod: Interval, severity: Code, recorder: AnyEntity, qdmTitle: { type: String, default: 'Symptom' }, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.116' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.136' }, qdmCategory: { type: String, default: 'symptom' }, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::Symptom' }, }); module.exports.SymptomSchema = SymptomSchema; class Symptom extends mongoose.Document { constructor(object) { super(object, SymptomSchema); this._type = 'QDM::Symptom'; } } module.exports.Symptom = Symptom; },{"./attributes/Component":58,"./attributes/Entity":60,"./attributes/FacilityLocation":61,"./attributes/Identifier":62,"./basetypes/Any":67,"./basetypes/AnyEntity":68,"./basetypes/Code":69,"./basetypes/DataElement":70,"./basetypes/DateTime":71,"./basetypes/Interval":72,"./basetypes/QDMDate":73,"./basetypes/Quantity":74,"mongoose/browser":258}],57:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const CarePartnerSchema = EntitySchemaFunction({ relationship: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.134' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.160' }, _type: { type: String, default: 'QDM::CarePartner' }, }); module.exports.CarePartnerSchema = CarePartnerSchema; class CarePartner extends mongoose.Document { constructor(object) { super(object, CarePartnerSchema); this._type = 'QDM::CarePartner'; } } module.exports.CarePartner = CarePartner; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":60,"mongoose/browser":258}],58:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Schema] = [mongoose.Schema]; const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ComponentSchema = new mongoose.Schema({ code: Code, result: Any, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::Component' }, }); module.exports.ComponentSchema = ComponentSchema; class Component extends mongoose.Document { constructor(object) { super(object, ComponentSchema); this._type = 'QDM::Component'; } } function ComponentSchemaFunction(add, options) { const extended = new Schema({ code: Code, result: Any, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::Component' }, }, options); if (add) { extended.add(add); } return extended; } module.exports.Component = Component; module.exports.ComponentSchemaFunction = ComponentSchemaFunction; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"mongoose/browser":258}],59:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const DiagnosisComponentSchema = new mongoose.Schema({ code: Code, presentOnAdmissionIndicator: Code, rank: Number, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::DiagnosisComponent' }, }); module.exports.DiagnosisComponentSchema = DiagnosisComponentSchema; class DiagnosisComponent extends mongoose.Document { constructor(object) { super(object, DiagnosisComponentSchema); this._type = 'QDM::DiagnosisComponent'; } } module.exports.DiagnosisComponent = DiagnosisComponent; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"mongoose/browser":258}],60:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { IdentifierSchema } = require('./Identifier'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Schema] = [mongoose.Schema]; const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const EntitySchema = new mongoose.Schema({ id: String, identifier: IdentifierSchema, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::Entity' }, }); module.exports.EntitySchema = EntitySchema; class Entity extends mongoose.Document { constructor(object) { super(object, EntitySchema); this._type = 'QDM::Entity'; } } function EntitySchemaFunction(add, options) { const extended = new Schema({ identifier: IdentifierSchema, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::Entity' }, id: { type: String, default() { return this._id ? this._id.toString() : mongoose.Types.ObjectId().toString(); }, }, }, options); if (add) { extended.add(add); } return extended; } module.exports.Entity = Entity; module.exports.EntitySchemaFunction = EntitySchemaFunction; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Identifier":62,"mongoose/browser":258}],61:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const FacilityLocationSchema = new mongoose.Schema({ code: Code, locationPeriod: Interval, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::FacilityLocation' }, }); module.exports.FacilityLocationSchema = FacilityLocationSchema; class FacilityLocation extends mongoose.Document { constructor(object) { super(object, FacilityLocationSchema); this._type = 'QDM::FacilityLocation'; } } module.exports.FacilityLocation = FacilityLocation; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"mongoose/browser":258}],62:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const IdentifierSchema = mongoose.Schema({ namingSystem: String, value: String, qdmVersion: { type: String, default: '5.5' }, _type: { type: String, default: 'QDM::Identifier' }, }, { _id: false, id: false }); module.exports.IdentifierSchema = IdentifierSchema; class Identifier extends mongoose.Document { constructor(object) { super(object, IdentifierSchema); this._type = 'QDM::Identifier'; } } module.exports.Identifier = Identifier; },{"mongoose/browser":258}],63:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const OrganizationSchema = EntitySchemaFunction({ type: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.135' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.163' }, _type: { type: String, default: 'QDM::Organization' }, }); module.exports.OrganizationSchema = OrganizationSchema; class Organization extends mongoose.Document { constructor(object) { super(object, OrganizationSchema); this._type = 'QDM::Organization'; } } module.exports.Organization = Organization; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":60,"mongoose/browser":258}],64:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientEntitySchema = EntitySchemaFunction({ hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.136' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.161' }, _type: { type: String, default: 'QDM::PatientEntity' }, }); module.exports.PatientEntitySchema = PatientEntitySchema; class PatientEntity extends mongoose.Document { constructor(object) { super(object, PatientEntitySchema); this._type = 'QDM::PatientEntity'; } } module.exports.PatientEntity = PatientEntity; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":60,"mongoose/browser":258}],65:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { EntitySchemaFunction } = require('./Entity'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PractitionerSchema = EntitySchemaFunction({ role: Code, specialty: Code, qualification: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.137' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.162' }, _type: { type: String, default: 'QDM::Practitioner' }, }); module.exports.PractitionerSchema = PractitionerSchema; class Practitioner extends mongoose.Document { constructor(object) { super(object, PractitionerSchema); this._type = 'QDM::Practitioner'; } } module.exports.Practitioner = Practitioner; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Entity":60,"mongoose/browser":258}],66:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { ComponentSchemaFunction } = require('./Component'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const QDMDate = require('../basetypes/QDMDate'); const Any = require('../basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ResultComponentSchema = ComponentSchemaFunction({ referenceRange: Interval, _type: { type: String, default: 'QDM::ResultComponent' }, }); module.exports.ResultComponentSchema = ResultComponentSchema; class ResultComponent extends mongoose.Document { constructor(object) { super(object, ResultComponentSchema); this._type = 'QDM::ResultComponent'; } } module.exports.ResultComponent = ResultComponent; },{"../basetypes/Any":67,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/QDMDate":73,"../basetypes/Quantity":74,"./Component":58,"mongoose/browser":258}],67:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function Any(key, options) { mongoose.SchemaType.call(this, key, options, 'Any'); } Any.prototype = Object.create(mongoose.SchemaType.prototype); function RecursiveCast(any) { if (any && any.value && any.unit) { return new cql.Quantity(any.value, any.unit); } if (any && any.numerator && any.denominator) { const numerator = new cql.Quantity(any.numerator.value, any.numerator.unit); const denominator = new cql.Quantity(any.denominator.value, any.denominator.unit); return new cql.Ratio(numerator, denominator); } if (any.isCode || any.isConcept || any.isValueSet || any.isList || any.isDateTime || any.isDate || any.isRatio || any.isQuantiy || any.isInterval || any.isBooleanLiteral || any.isIntegerLiteral || any.isDecimalLiteral || any.isStringLiteral || any.isTuple) { return any; } if (any && any.code && any.system) { const val = { code: any.code, system: any.system }; val.display = (typeof any.display !== 'undefined') ? any.display : null; val.version = (typeof any.version !== 'undefined') ? any.version : null; return new cql.Code(val.code, val.system, val.version, val.display); } if (any && any.low) { const casted = new cql.Interval(any.low, any.high, any.lowClosed, any.highClosed); // Cast Low and High values to Quantities if it is a quantity if (casted.low && casted.low.unit && casted.low.value) { casted.low = new cql.Quantity(casted.low.value, casted.low.unit); if (casted.high && casted.high.unit && casted.high.value) { casted.high = new cql.Quantity(casted.high.value, casted.high.unit); } return casted; } // Cast to DateTime if it is a string representing a DateTime if (casted.low && Date.parse(casted.low)) { casted.low = cql.DateTime.fromJSDate(new Date(casted.low), 0); } if (casted.high && Date.parse(casted.high)) { casted.high = cql.DateTime.fromJSDate(new Date(casted.high), 0); } return casted; } if (Array.isArray(any)) { const casted = []; any.forEach((val) => { casted.push(RecursiveCast(val)); }); return casted; } if (Number.isFinite(any)) { return any; } if (Date.parse(any) || Date.parse(`1984-01-01T${any}`)) { if (any.match(/T/) || any.match(/\+/)) { // If it has a T or a timezoneoffset, it must be a DateTime return cql.DateTime.fromJSDate(new Date(any), 0); } if (any.match(/:/)) { // If it has a : but no T or timezoneoffset, it must be a Time return cql.DateTime.fromJSDate(new Date(`1984-01-01T${any}`), 0).getTime(); } // Must be a Date return cql.DateTime.fromJSDate(new Date(any), 0).getDate(); } return any; } Any.prototype.cast = any => RecursiveCast(any); mongoose.Schema.Types.Any = Any; module.exports = Any; },{"cql-execution":119,"mongoose/browser":258}],68:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { PatientEntity } = require('../attributes/PatientEntity'); const { Practitioner } = require('../attributes/Practitioner'); const { CarePartner } = require('../attributes/CarePartner'); const { Organization } = require('../attributes/Organization'); function AnyEntity(key, options) { mongoose.SchemaType.call(this, key, options, 'AnyEntity'); } AnyEntity.prototype = Object.create(mongoose.SchemaType.prototype); AnyEntity.prototype.cast = (entity) => { if (entity == null) { return null; } if (entity instanceof PatientEntity || entity instanceof Practitioner || entity instanceof CarePartner || entity instanceof Organization) { return entity; } if (entity._type != null) { // copy _id to id if it isn't defined if (entity.id == null && entity._id != null) { entity.id = entity._id; } switch (entity._type) { case 'QDM::PatientEntity': return new PatientEntity(entity); case 'QDM::Practitioner': return new Practitioner(entity); case 'QDM::CarePartner': return new CarePartner(entity); case 'QDM::Organization': return new Organization(entity); default: throw new Error(`Could not find entity type "${entity._type}".`); } } else { throw new Error('Could not find _type indicator for entity.'); } }; mongoose.Schema.Types.AnyEntity = AnyEntity; module.exports = AnyEntity; },{"../attributes/CarePartner":57,"../attributes/Organization":63,"../attributes/PatientEntity":64,"../attributes/Practitioner":65,"mongoose/browser":258}],69:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function Code(key, options) { mongoose.SchemaType.call(this, key, options, 'Code'); } Code.prototype = Object.create(mongoose.SchemaType.prototype); Code.prototype.cast = (code) => { if (code != null) { // return code if it doesn't even need casting if (code.isCode) { return code; } // handles codes that have not yet been cast to a code and those that have already been cast to a code if (code.code && code.system) { const val = { code: code.code, system: code.system }; val.display = (typeof code.display !== 'undefined') ? code.display : null; val.version = (typeof code.version !== 'undefined') ? code.version : null; return new cql.Code(val.code, val.system, val.version, val.display); } throw new Error(`Expected a code. Received ${code}.`); } else { // returns a null or undefined if what is passed in is null or undefined return code; } }; mongoose.Schema.Types.Code = Code; module.exports = Code; },{"cql-execution":119,"mongoose/browser":258}],70:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('./Code.js'); const cql = require('cql-execution'); const Identifier = require('../attributes/Identifier'); const [Schema] = [mongoose.Schema]; function DataElementSchema(add, options) { const extended = new Schema({ dataElementCodes: { type: [Code] }, description: { type: String }, codeListId: { type: String }, id: { type: String, default() { return this._id ? this._id.toString() : mongoose.Types.ObjectId().toString(); }, }, }, options); if (add) { extended.add(add); } // Returns all of the codes on this data element in a format usable by // the cql-execution framework. extended.methods.getCode = function getCode() { if (this.dataElementCodes) { return this.dataElementCodes.map((code) => { if (code.isCode) { return code; } return new cql.Code(code.code, code.system, code.version, code.display); }); } return null; }; // Return the first code on this data element in a format usable by // the cql-execution framework. extended.methods.code = function code() { if (this.dataElementCodes && this.dataElementCodes[0]) { const qdmCode = this.dataElementCodes[0]; if (qdmCode.isCode) { return qdmCode; } return new cql.Code(qdmCode.code, qdmCode.system, qdmCode.version, qdmCode.display); } return null; }; return extended; } module.exports.DataElementSchema = DataElementSchema; },{"../attributes/Identifier":62,"./Code.js":69,"cql-execution":119,"mongoose/browser":258}],71:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function DateTime(key, options) { mongoose.SchemaType.call(this, key, options, 'DateTime'); } DateTime.prototype = Object.create(mongoose.SchemaType.prototype); DateTime.prototype.cast = (dateTime) => { if (dateTime.isDateTime) { return dateTime; } if (!Date.parse(dateTime)) { throw new Error(`DateTime: ${dateTime} is not a valid DateTime`); } return cql.DateTime.fromJSDate(new Date(dateTime), 0); }; mongoose.Schema.Types.DateTime = DateTime; module.exports = DateTime; },{"cql-execution":119,"mongoose/browser":258}],72:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); const DateTime = require('./DateTime'); function Interval(key, options) { mongoose.SchemaType.call(this, key, options, 'Interval'); } Interval.prototype = Object.create(mongoose.SchemaType.prototype); Interval.prototype.cast = (interval) => { if (interval.isInterval) { return interval; } const casted = new cql.Interval(interval.low, interval.high, interval.lowClosed, interval.highClosed); // Cast Low and High values to Quantities if it is a quantity if (casted.low && casted.low.unit && casted.low.value) { casted.low = new cql.Quantity(casted.low.value, casted.low.unit); if (casted.high && casted.high.unit && casted.high.value) { casted.high = new cql.Quantity(casted.high.value, casted.high.unit); } return casted; } // Cast to DateTime if it is a string representing a DateTime if (casted.low) { casted.low = DateTime.prototype.cast(casted.low); } if (casted.high) { casted.high = DateTime.prototype.cast(casted.high); } return casted; }; mongoose.Schema.Types.Interval = Interval; module.exports = Interval; },{"./DateTime":71,"cql-execution":119,"mongoose/browser":258}],73:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function QDMDate(key, options) { mongoose.SchemaType.call(this, key, options, 'Date'); } QDMDate.prototype = Object.create(mongoose.SchemaType.prototype); QDMDate.prototype.cast = (date) => { if (date == null) { return date; } // Already a CQL Date if (date.isDate) { return date; } // Object if (typeof date === 'object') { const keys = Object.keys(date); if (keys.includes('year') && keys.includes('month') && keys.includes('day')) { return new cql.Date(date.year, date.month, date.day); } } // Date String if (!cql.Date.parse(date)) { throw new Error(`Date: ${date} is not a valid Date`); } else { return cql.Date.parse(date); } }; mongoose.Schema.Types.QDMDate = QDMDate; module.exports = QDMDate; },{"cql-execution":119,"mongoose/browser":258}],74:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const cql = require('cql-execution'); function Quantity(key, options) { mongoose.SchemaType.call(this, key, options, 'Quantity'); } Quantity.prototype = Object.create(mongoose.SchemaType.prototype); Quantity.prototype.cast = (quantity) => { if (typeof quantity.value === 'undefined') { throw new Error(`Quantity: ${quantity} does not have a value`); } else if (typeof quantity.unit === 'undefined') { throw new Error(`Quantity: ${quantity} does not have a unit`); } return new cql.Quantity(quantity.value, quantity.unit); }; mongoose.Schema.Types.Quantity = Quantity; module.exports = Quantity; },{"cql-execution":119,"mongoose/browser":258}],75:[function(require,module,exports){ window.cqm = window.cqm || {}; window.cqm.models = require('./index'); },{"./index":88}],76:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { StatementDependencySchema } = require('./CQLStatementDependency'); const [Mixed, mDate] = [ mongoose.Schema.Types.Mixed, mongoose.Schema.Types.Date, ]; const CQLLibrarySchema = new mongoose.Schema( { library_name: String, library_version: String, cql: String, elm: Mixed, elm_annotations: Mixed, is_main_library: { type: Boolean, default: false }, is_top_level: { type: Boolean, default: true }, statement_dependencies: [StatementDependencySchema], }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, // These are the Mongoid conventions for timestamps } ); module.exports.CQLLibrarySchema = CQLLibrarySchema; class CQLLibrary extends mongoose.Document { constructor(object) { super(object, CQLLibrarySchema); } } module.exports.CQLLibrary = CQLLibrary; },{"./CQLStatementDependency":77,"mongoose/browser":258}],77:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const StatementReferenceSchema = new mongoose.Schema({ library_name: String, statement_name: String, hqmf_id: String, }); const StatementDependencySchema = new mongoose.Schema({ statement_name: String, statement_references: [StatementReferenceSchema], }); module.exports.StatementReferenceSchema = StatementReferenceSchema; class StatementReference extends mongoose.Document { constructor(object) { super(object, StatementReferenceSchema); } } module.exports.StatementReference = StatementReference; module.exports.StatementDependencySchema = StatementDependencySchema; class StatementDependency extends mongoose.Document { constructor(object) { super(object, StatementDependencySchema); } } module.exports.StatementDependency = StatementDependency; },{"mongoose/browser":258}],78:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [String, Mixed] = [ mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, ]; const ClauseResultSchema = mongoose.Schema({ // Library the clause this result is for is in library_name: String, // Statement the clause this result is for is in statement_name: String, // LocalId of the clause this result is for localId: String, // Final, processed result of raw calculation final: String, // Raw result of clause calculation raw: Mixed, }); module.exports.ClauseResultSchema = ClauseResultSchema; class ClauseResult extends mongoose.Document { constructor(object) { super(object, ClauseResultSchema); } } module.exports.ClauseResult = ClauseResult; },{"mongoose/browser":258}],79:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const ConceptSchema = new mongoose.Schema({ code: String, code_system_oid: String, code_system_name: String, code_system_version: String, display_name: String, }); module.exports.ConceptSchema = ConceptSchema; class Concept extends mongoose.Document { constructor(object) { super(object, ConceptSchema); } } module.exports.Concept = Concept; },{"mongoose/browser":258}],80:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const { ClauseResultSchema } = require('./ClauseResult'); const { StatementResultSchema } = require('./StatementResult'); const [Number, String, Mixed, ObjectId] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, mongoose.Schema.Types.ObjectId, ]; const IndividualResultSchema = mongoose.Schema( { // Population Attributes STRAT: Number, IPP: Number, DENOM: Number, NUMER: Number, NUMEX: Number, DENEX: Number, DENEXCEP: Number, MSRPOPL: Number, OBSERV: Number, MSRPOPLEX: Number, // Result Attributes clause_results: [ClauseResultSchema], statement_results: [StatementResultSchema], population_relevance: Mixed, episode_results: Mixed, observation_values: [Number], // This field is for application specific information only. If both Bonnie and // Cypress use a common field, it should be made a field on this model, // and not put into extendedData. extendedData: { type: Mixed, default: {}, }, // Calculation State attributes state: { type: String, enum: ['queued', 'running', 'complete', 'cancelled', 'failed'], default: 'queued', }, // Relations to other model classes // 'alias' field makes it so you can call obj.measure, and get the object referenced by measure_id measure_id: { type: ObjectId, ref: 'Measure', alias: 'measure' }, patient_id: { type: ObjectId, ref: 'Patient', alias: 'patient' }, }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, // These are the Mongoid conventions for timestamps } ); IndividualResultSchema.methods.clause_results_by_clause = function clause_results_by_clause() { const clause_results_hash = {}; this.clause_results.forEach((result) => { if (!clause_results_hash[result.library_name]) { clause_results_hash[result.library_name] = {}; } clause_results_hash[result.library_name][result.localId] = result; }); return clause_results_hash; }; IndividualResultSchema.methods.statement_results_by_statement = function statement_results_by_statement() { const statement_results_hash = {}; this.statement_results.forEach((result) => { if (!statement_results_hash[result.library_name]) { statement_results_hash[result.library_name] = {}; } statement_results_hash[result.library_name][result.statement_name] = result; }); return statement_results_hash; }; module.exports.IndividualResultSchema = IndividualResultSchema; class IndividualResult extends mongoose.Document { constructor(object) { super(object, IndividualResultSchema); } } module.exports.IndividualResult = IndividualResult; },{"./ClauseResult":78,"./StatementResult":86,"mongoose/browser":258}],81:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DataElementSchema = require('../basetypes/DataElement').DataElementSchema(); const AllDataElements = require('../AllDataElements'); const { CQLLibrarySchema } = require('./CQLLibrary'); const { PopulationSetSchema } = require('./PopulationSet'); const [Number, String, Boolean, Mixed, ObjectId, Date] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, mongoose.Schema.Types.Boolean, mongoose.Schema.Types.Mixed, mongoose.Schema.Types.ObjectId, mongoose.Schema.Types.Date, ]; const MeasureSchema = new mongoose.Schema( { // A version-specific UUID for the measure hqmf_id: String, // A version-neutral UUID for the measure hqmf_set_id: String, // A Semantic Version-compliant string (e.g. "2.3.4") for the measure hqmf_version_number: String, // A CMS-style string (e.g. "CMS2v4") for the measure cms_id: String, title: String, description: String, // Composite/component measure fields composite: { type: Boolean, default: false, }, component: { type: Boolean, default: false, }, component_hqmf_set_ids: [String], composite_hqmf_set_id: String, // Measure type variables measure_scoring: { type: String, enum: ['PROPORTION', 'RATIO', 'CONTINUOUS_VARIABLE', 'COHORT'], default: 'PROPORTION', }, calculation_method: { type: String, enum: ['PATIENT', 'EPISODE_OF_CARE'], default: 'PATIENT', }, calculate_sdes: Boolean, // ELM/CQL Measure-logic related data encapsulated in CQLLibrarySchema // Field name changed from 'cql' to 'cql_libraries' because the semantics of // embeds_many: cqls (on the Ruby side) sounded weird, // and we wanted to keep the API consistent cql_libraries: [CQLLibrarySchema], main_cql_library: String, // HQMF/Tacoma-specific Measure-logic related data population_criteria: Mixed, source_data_criteria: [], measure_period: Mixed, measure_attributes: [], population_sets: [PopulationSetSchema], // Relations to other model classes bundle: { type: ObjectId, ref: 'Bundle' }, // Cypress-specific, until we migrate the Bundle into cqm-models package: { type: ObjectId, ref: 'MeasurePackage' }, // Bonnie-specific patients: [{ type: ObjectId, ref: 'Patient', index: true }], value_sets: [{ type: ObjectId, ref: 'ValueSet' }], }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, // These are the Mongoid conventions for timestamps } ); // After initialization of a Measure model, initialize every individual data element // to its respective Mongoose Model MeasureSchema.methods.initializeDataElements = function initializeDataElements() { let typeStripped; const sourceDataCriteriaInit = []; this.source_data_criteria.forEach((element) => { typeStripped = element._type.replace(/QDM::/, ''); sourceDataCriteriaInit.push(new AllDataElements[typeStripped](element)); }); this.set('source_data_criteria', sourceDataCriteriaInit); }; MeasureSchema.methods.all_stratifications = function all_stratifications() { return this.population_sets.flatMap(ps => ps.stratifications); }; module.exports.MeasureSchema = MeasureSchema; class Measure extends mongoose.Document { constructor(object) { super(object, MeasureSchema); this.initializeDataElements(); } } module.exports.Measure = Measure; },{"../AllDataElements":2,"../basetypes/Code":69,"../basetypes/DataElement":70,"../basetypes/Interval":72,"../basetypes/Quantity":74,"./CQLLibrary":76,"./PopulationSet":84,"mongoose/browser":258}],82:[function(require,module,exports){ const mongoose = require('mongoose/browser'); // using mBuffer to not conflict with system Buffer const [mBuffer, ObjectId] = [ mongoose.Schema.Types.Buffer, mongoose.Schema.Types.ObjectId, ]; const MeasurePackageSchema = new mongoose.Schema( { file: mBuffer, measure: { type: ObjectId, ref: 'Measure' }, }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, } ); module.exports.MeasurePackageSchema = MeasurePackageSchema; class MeasurePackage extends mongoose.Document { constructor(object) { super(object, MeasurePackageSchema); } } module.exports.MeasurePackage = MeasurePackage; },{"mongoose/browser":258}],83:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Code = require('../basetypes/Code'); const Interval = require('../basetypes/Interval'); const Quantity = require('../basetypes/Quantity'); const DateTime = require('../basetypes/DateTime'); const { QDMPatientSchema, QDMPatient } = require('../QDMPatient'); const { ProviderSchema } = require('./Provider'); const [Schema, Number, String, Mixed] = [ mongoose.Schema, mongoose.Schema.Types.Number, mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, ]; const PatientSchema = new Schema({ givenNames: [String], familyName: String, bundleId: String, expectedValues: [], notes: String, qdmPatient: QDMPatientSchema, providers: [ProviderSchema], measure_ids: [String], }, { id: false }); module.exports.PatientSchema = PatientSchema; class Patient extends mongoose.Document { constructor(object) { super(object, PatientSchema); if (this.qdmPatient) { this.qdmPatient = new QDMPatient(this.qdmPatient.toJSON()); } } } module.exports.Patient = Patient; },{"../QDMPatient":50,"../basetypes/Code":69,"../basetypes/DateTime":71,"../basetypes/Interval":72,"../basetypes/Quantity":74,"./Provider":85,"mongoose/browser":258}],84:[function(require,module,exports){ /* eslint-disable no-unused-vars, no-param-reassign */ const mongoose = require('mongoose/browser'); const { StatementReferenceSchema } = require('./CQLStatementDependency'); const [Mixed] = [ mongoose.Schema.Types.Mixed, ]; // TODO: figure out if there is a better way to handle inheritance like mongoid. // _type is how mongoid stores the specific type of the embedded document. const PopulationMapSchema = new mongoose.Schema({ _type: String, IPP: StatementReferenceSchema, DENOM: StatementReferenceSchema, NUMER: StatementReferenceSchema, NUMEX: StatementReferenceSchema, DENEX: StatementReferenceSchema, DENEXCEP: StatementReferenceSchema, MSRPOPL: StatementReferenceSchema, MSRPOPLEX: StatementReferenceSchema, // STRAT is only here so cqm-execution can handle stratification results compliation with the current approach. STRAT: StatementReferenceSchema, }); if (!PopulationMapSchema.options.toObject) PopulationMapSchema.options.toObject = {}; PopulationMapSchema.options.toObject.transform = function transform(doc, ret, options) { // remove the _id and _type of every document before returning the result delete ret._id; delete ret._type; return ret; }; const StratificationSchema = new mongoose.Schema({ title: String, stratification_id: String, hqmf_id: String, statement: StatementReferenceSchema, }); const ObservationSchema = new mongoose.Schema({ title: String, observation_function: StatementReferenceSchema, observation_parameter: StatementReferenceSchema, aggregation_type: String, hqmf_id: String, }); const PopulationSetSchema = new mongoose.Schema({ title: String, population_set_id: String, populations: PopulationMapSchema, stratifications: [StratificationSchema], supplemental_data_elements: [StatementReferenceSchema], observations: [ObservationSchema], }); module.exports.StratificationSchema = StratificationSchema; class Stratification extends mongoose.Document { constructor(object) { super(object, StratificationSchema); } } module.exports.Stratification = Stratification; module.exports.ObservationSchema = ObservationSchema; class Observation extends mongoose.Document { constructor(object) { super(object, ObservationSchema); } } module.exports.Observation = Observation; module.exports.PopulationMapSchema = PopulationMapSchema; class PopulationMap extends mongoose.Document { constructor(object) { super(object, PopulationMapSchema); } } module.exports.PopulationMap = PopulationMap; module.exports.PopulationSetSchema = PopulationSetSchema; class PopulationSet extends mongoose.Document { constructor(object) { super(object, PopulationSetSchema); } } module.exports.PopulationSet = PopulationSet; },{"./CQLStatementDependency":77,"mongoose/browser":258}],85:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [Schema, String, Boolean] = [ mongoose.Schema, mongoose.Schema.Types.String, mongoose.Schema.Types.Boolean, ]; const AddressSchema = new mongoose.Schema({ street: [String], city: String, state: String, zip: String, country: String, use: String, }); const TelecomSchema = new mongoose.Schema({ use: String, value: String, preferred: Boolean, }); const ProviderSchema = new Schema({ _type: { type: String, default: 'Provider' }, givenNames: [String], familyName: String, specialty: String, title: String, addresses: [AddressSchema], telecoms: [TelecomSchema], }, { id: false }); module.exports.ProviderSchema = ProviderSchema; class Provider extends mongoose.Document { constructor(object) { super(object, ProviderSchema); } } module.exports.Provider = Provider; },{"mongoose/browser":258}],86:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const [String, Mixed] = [ mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, ]; const StatementResultSchema = mongoose.Schema({ // Library the statement this result is for is in library_name: String, // Statement this result is for is in statement_name: String, // Result, processed for display, of the statement this result is for pretty: String, // Final, processed result of raw calculation final: String, // Raw result of clause calculation raw: Mixed, /* * 'NA' - Not applicable. This statement is not relevant to any population calculation in this population_set. Common * for unused library statements or statements only used for other population sets. * * 'FALSE' - This statement is not relevant to any of this patient's population inclusion calculations. * * 'TRUE' - This statement is relevant for one or more of the population inclusion calculations. */ relevance: { type: String, enum: ['NA', 'TRUE', 'FALSE'], default: 'NA', }, }); module.exports.StatementResultSchema = StatementResultSchema; class StatementResult extends mongoose.Document { constructor(object) { super(object, StatementResultSchema); } } module.exports.StatementResult = StatementResult; },{"mongoose/browser":258}],87:[function(require,module,exports){ const mongoose = require('mongoose/browser'); const Concept = require('./Concept.js'); const [String] = [mongoose.Schema.Types.String]; const ValueSetSchema = new mongoose.Schema( { oid: String, display_name: String, version: String, concepts: [Concept.ConceptSchema], }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, } ); module.exports.ValueSetSchema = ValueSetSchema; class ValueSet extends mongoose.Document { constructor(object) { super(object, ValueSetSchema); } } module.exports.ValueSet = ValueSet; },{"./Concept.js":79,"mongoose/browser":258}],88:[function(require,module,exports){ module.exports = require('./AllDataElements.js'); module.exports.CQL = require('cql-execution'); module.exports.Result = require('./Result.js').Result; module.exports.ResultSchema = require('./Result.js').ResultSchema; module.exports.Measure = require('./cqm/Measure.js').Measure; module.exports.MeasureSchema = require('./cqm/Measure.js').MeasureSchema; module.exports.MeasurePackage = require('./cqm/MeasurePackage.js').MeasurePackage; module.exports.MeasurePackageSchema = require('./cqm/MeasurePackage.js').MeasurePackageSchema; module.exports.Patient = require('./cqm/Patient.js').Patient; module.exports.PatientSchema = require('./cqm/Patient.js').PatientSchema; module.exports.Provider = require('./cqm/Provider.js').Provider; module.exports.ProviderSchema = require('./cqm/Provider.js').ProviderSchema; module.exports.StatementDependency = require('./cqm/CQLStatementDependency.js').StatementDependency; module.exports.StatementDependencySchema = require('./cqm/CQLStatementDependency.js').StatementDependencySchema; module.exports.PopulationSet = require('./cqm/PopulationSet.js').PopulationSet; module.exports.PopulationSetSchema = require('./cqm/PopulationSet.js').PopulationSetSchema; module.exports.CQLLibrary = require('./cqm/CQLLibrary.js').CQLLibrary; module.exports.CQLLibrarySchema = require('./cqm/CQLLibrary.js').CQLLibrarySchema; module.exports.ValueSet = require('./cqm/ValueSet.js').ValueSet; module.exports.ValueSetSchema = require('./cqm/ValueSet.js').ValueSetSchema; module.exports.Concept = require('./cqm/Concept.js').Concept; module.exports.ConceptSchema = require('./cqm/Concept.js').ConceptSchema; module.exports.IndividualResult = require('./cqm/IndividualResult.js').IndividualResult; module.exports.IndividualResultSchema = require('./cqm/IndividualResult.js').IndividualResultSchema; module.exports.ClauseResult = require('./cqm/ClauseResult.js').ClauseResult; module.exports.ClauseResultSchema = require('./cqm/ClauseResult.js').ClauseResultSchema; module.exports.StatementResult = require('./cqm/StatementResult.js').StatementResult; module.exports.StatementResultSchema = require('./cqm/StatementResult.js').StatementResultchema; },{"./AllDataElements.js":2,"./Result.js":52,"./cqm/CQLLibrary.js":76,"./cqm/CQLStatementDependency.js":77,"./cqm/ClauseResult.js":78,"./cqm/Concept.js":79,"./cqm/IndividualResult.js":80,"./cqm/Measure.js":81,"./cqm/MeasurePackage.js":82,"./cqm/Patient.js":83,"./cqm/PopulationSet.js":84,"./cqm/Provider.js":85,"./cqm/StatementResult.js":86,"./cqm/ValueSet.js":87,"cql-execution":119}],89:[function(require,module,exports){ (function (global){ 'use strict'; var objectAssign = require('object-assign'); // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js // original notice: /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } function isBuffer(b) { if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { return global.Buffer.isBuffer(b); } return !!(b != null && b._isBuffer); } // based on node assert, original notice: // NB: The URL to the CommonJS spec is kept just for tradition. // node-assert has evolved a lot since then, both in API and behavior. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util/'); var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { return function foo() {}.name === 'foo'; }()); function pToString (obj) { return Object.prototype.toString.call(obj); } function isView(arrbuf) { if (isBuffer(arrbuf)) { return false; } if (typeof global.ArrayBuffer !== 'function') { return false; } if (typeof ArrayBuffer.isView === 'function') { return ArrayBuffer.isView(arrbuf); } if (!arrbuf) { return false; } if (arrbuf instanceof DataView) { return true; } if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { return true; } return false; } // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { if (!util.isFunction(func)) { return; } if (functionsHaveNames) { return func.name; } var str = func.toString(); var match = str.match(regex); return match && match[1]; } assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = getName(stackStartFunction); var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } function inspect(something) { if (functionsHaveNames || !util.isFunction(something)) { return util.inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; return '[Function' + name + ']'; } function getMessage(self) { return truncate(inspect(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect(self.expected), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (!_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); } }; function _deepEqual(actual, expected, strict, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (isBuffer(actual) && isBuffer(expected)) { return compare(actual, expected) === 0; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying // ArrayBuffers in a Buffer each to increase performance // This optimization requires the arrays to have the same type as checked by // Object.prototype.toString (aka pToString). Never perform binary // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their // bit patterns are not identical. } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) { return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else if (isBuffer(actual) !== isBuffer(expected)) { return false; } else { memos = memos || {actual: [], expected: []}; var actualIndex = memos.actual.indexOf(actual); if (actualIndex !== -1) { if (actualIndex === memos.expected.indexOf(expected)) { return true; } } memos.actual.push(actual); memos.expected.push(expected); return objEquiv(actual, expected, strict, memos); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; var aIsArgs = isArguments(a); var bIsArgs = isArguments(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, strict); } var ka = objectKeys(a); var kb = objectKeys(b); var key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length !== kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } } // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } try { if (actual instanceof expected) { return true; } } catch (e) { // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function _tryBlock(block) { var error; try { block(); } catch (e) { error = e; } return error; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof block !== 'function') { throw new TypeError('"block" argument must be a function'); } if (typeof expected === 'string') { message = expected; expected = null; } actual = _tryBlock(block); message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } var userProvidedMessage = typeof message === 'string'; var isUnwantedException = !shouldThrow && util.isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && userProvidedMessage && expectedException(actual, expected)) || isUnexpectedException) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws(true, block, error, message); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { _throws(false, block, error, message); }; assert.ifError = function(err) { if (err) throw err; }; // Expose a strict only variant of assert function strict(value, message) { if (!value) fail(value, true, message, '==', strict); } assert.strict = objectAssign(strict, assert, { equal: assert.strictEqual, deepEqual: assert.deepStrictEqual, notEqual: assert.notStrictEqual, notDeepEqual: assert.notDeepStrictEqual }); assert.strict.strict = assert.strict; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"object-assign":398,"util/":92}],90:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],91:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],92:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":91,"_process":399,"inherits":90}],93:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk( uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) )) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } },{}],94:[function(require,module,exports){ (function (process,global,setImmediate){ /* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2017 Petka Antonov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * bluebird build version 3.5.1 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = Async; module.exports.firstLineError = firstLineError; },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { if (!calledBind) { calledBind = true; Promise.prototype._propagateFrom = debug.propagateFromFunction(); Promise.prototype._boundValue = debug.boundValueFunction(); } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( bindingResolved, bindingRejected, undefined, ret, context); ret._setOnCancel(maybePromise); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { return Promise.resolve(value).bind(thisArg); }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise":22}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; if (!true) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var args = [].slice.call(arguments, 1);; if (!true) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util":36}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; Promise.prototype["break"] = Promise.prototype.cancel = function() { if (!debug.cancellation()) return this._warn("cancellation is disabled"); var promise = this; var child = promise; while (promise._isCancellable()) { if (!promise._cancelBy(child)) { if (child._isFollowing()) { child._followee().cancel(); } else { child._cancelBranched(); } break; } var parent = promise._cancellationParent; if (parent == null || !parent._isCancellable()) { if (promise._isFollowing()) { promise._followee().cancel(); } else { promise._cancelBranched(); } break; } else { if (promise._isFollowing()) promise._followee().cancel(); promise._setWillBeCancelled(); child = promise; promise = parent; } } }; Promise.prototype._branchHasCancelled = function() { this._branchesRemainingToCancel--; }; Promise.prototype._enoughBranchesHaveCancelled = function() { return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; }; Promise.prototype._cancelBy = function(canceller) { if (canceller === this) { this._branchesRemainingToCancel = 0; this._invokeOnCancel(); return true; } else { this._branchHasCancelled(); if (this._enoughBranchesHaveCancelled()) { this._invokeOnCancel(); return true; } } return false; }; Promise.prototype._cancelBranched = function() { if (this._enoughBranchesHaveCancelled()) { this._cancel(); } }; Promise.prototype._cancel = function() { if (!this._isCancellable()) return; this._setCancelled(); async.invoke(this._cancelPromises, this, undefined); }; Promise.prototype._cancelPromises = function() { if (this._length() > 0) this._settlePromises(); }; Promise.prototype._unsetOnCancel = function() { this._onCancelField = undefined; }; Promise.prototype._isCancellable = function() { return this.isPending() && !this._isCancelled(); }; Promise.prototype.isCancellable = function() { return this.isPending() && !this.isCancelled(); }; Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { if (util.isArray(onCancelCallback)) { for (var i = 0; i < onCancelCallback.length; ++i) { this._doInvokeOnCancel(onCancelCallback[i], internalOnly); } } else if (onCancelCallback !== undefined) { if (typeof onCancelCallback === "function") { if (!internalOnly) { var e = tryCatch(onCancelCallback).call(this._boundValue()); if (e === errorObj) { this._attachExtraTrace(e.e); async.throwLater(e.e); } } } else { onCancelCallback._resultCancelled(this); } } }; Promise.prototype._invokeOnCancel = function() { var onCancelCallback = this._onCancel(); this._unsetOnCancel(); async.invoke(this._doInvokeOnCancel, this, onCancelCallback); }; Promise.prototype._invokeInternalOnCancel = function() { if (this._isCancellable()) { this._doInvokeOnCancel(this._onCancel(), true); this._unsetOnCancel(); } }; Promise.prototype._resultCancelled = function() { this.cancel(); }; }; },{"./util":36}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util"); var getKeys = _dereq_("./es5").keys; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function catchFilter(instances, cb, promise) { return function(e) { var boundTo = promise._boundValue(); predicateLoop: for (var i = 0; i < instances.length; ++i) { var item = instances[i]; if (item === Error || (item != null && item.prototype instanceof Error)) { if (e instanceof item) { return tryCatch(cb).call(boundTo, e); } } else if (typeof item === "function") { var matchesPredicate = tryCatch(item).call(boundTo, e); if (matchesPredicate === errorObj) { return matchesPredicate; } else if (matchesPredicate) { return tryCatch(cb).call(boundTo, e); } } else if (util.isObject(e)) { var keys = getKeys(item); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; if (item[key] != e[key]) { continue predicateLoop; } } return tryCatch(cb).call(boundTo, e); } } return NEXT_FILTER; }; } return catchFilter; }; },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var longStackTraces = false; var contextStack = []; Promise.prototype._promiseCreated = function() {}; Promise.prototype._pushContext = function() {}; Promise.prototype._popContext = function() {return null;}; Promise._peekContext = Promise.prototype._peekContext = function() {}; function Context() { this._trace = new Context.CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (this._trace !== undefined) { this._trace._promiseCreated = null; contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (this._trace !== undefined) { var trace = contextStack.pop(); var ret = trace._promiseCreated; trace._promiseCreated = null; return ret; } return null; }; function createContext() { if (longStackTraces) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Context.CapturedTrace = null; Context.create = createContext; Context.deactivateLongStackTraces = function() {}; Context.activateLongStackTraces = function() { var Promise_pushContext = Promise.prototype._pushContext; var Promise_popContext = Promise.prototype._popContext; var Promise_PeekContext = Promise._peekContext; var Promise_peekContext = Promise.prototype._peekContext; var Promise_promiseCreated = Promise.prototype._promiseCreated; Context.deactivateLongStackTraces = function() { Promise.prototype._pushContext = Promise_pushContext; Promise.prototype._popContext = Promise_popContext; Promise._peekContext = Promise_PeekContext; Promise.prototype._peekContext = Promise_peekContext; Promise.prototype._promiseCreated = Promise_promiseCreated; longStackTraces = false; }; longStackTraces = true; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; Promise._peekContext = Promise.prototype._peekContext = peekContext; Promise.prototype._promiseCreated = function() { var ctx = this._peekContext(); if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; }; }; return Context; }; },{}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, Context) { var getDomain = Promise._getDomain; var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var printWarning; var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development")); var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | 524288); }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); var self = this; setTimeout(function() { self._notifyUnhandledRejection(); }, 1); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._setReturnedNonUndefined = function() { this._bitField = this._bitField | 268435456; }; Promise.prototype._returnedNonUndefined = function() { return (this._bitField & 268435456) !== 0; }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._settledValue(); this._setUnhandledRejectionIsNotified(); fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 262144; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~262144); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 1048576; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~1048576); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { return warn(message, shouldUseOwnTrace, promise || this); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; var disableLongStackTraces = function() {}; Promise.longStackTraces = function () { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (!config.longStackTraces && longStackTracesIsSupported()) { var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; config.longStackTraces = true; disableLongStackTraces = function() { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Context.deactivateLongStackTraces(); async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Context.activateLongStackTraces(); async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; var fireDomEvent = (function() { try { if (typeof CustomEvent === "function") { var event = new CustomEvent("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new CustomEvent(name.toLowerCase(), { detail: event, cancelable: true }); return !util.global.dispatchEvent(domEvent); }; } else if (typeof Event === "function") { var event = new Event("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new Event(name.toLowerCase(), { cancelable: true }); domEvent.detail = event; return !util.global.dispatchEvent(domEvent); }; } else { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { var domEvent = document.createEvent("CustomEvent"); domEvent.initCustomEvent(name.toLowerCase(), false, true, event); return !util.global.dispatchEvent(domEvent); }; } } catch (e) {} return function() { return false; }; })(); var fireGlobalEvent = (function() { if (util.isNode) { return function() { return process.emit.apply(process, arguments); }; } else { if (!util.global) { return function() { return false; }; } return function(name) { var methodName = "on" + name.toLowerCase(); var method = util.global[methodName]; if (!method) return false; method.apply(util.global, [].slice.call(arguments, 1)); return true; }; } })(); function generatePromiseLifecycleEventObject(name, promise) { return {promise: promise}; } var eventToObjectGenerator = { promiseCreated: generatePromiseLifecycleEventObject, promiseFulfilled: generatePromiseLifecycleEventObject, promiseRejected: generatePromiseLifecycleEventObject, promiseResolved: generatePromiseLifecycleEventObject, promiseCancelled: generatePromiseLifecycleEventObject, promiseChained: function(name, promise, child) { return {promise: promise, child: child}; }, warning: function(name, warning) { return {warning: warning}; }, unhandledRejection: function (name, reason, promise) { return {reason: reason, promise: promise}; }, rejectionHandled: generatePromiseLifecycleEventObject }; var activeFireEvent = function (name) { var globalEventFired = false; try { globalEventFired = fireGlobalEvent.apply(null, arguments); } catch (e) { async.throwLater(e); globalEventFired = true; } var domEventFired = false; try { domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments)); } catch (e) { async.throwLater(e); domEventFired = true; } return domEventFired || globalEventFired; }; Promise.config = function(opts) { opts = Object(opts); if ("longStackTraces" in opts) { if (opts.longStackTraces) { Promise.longStackTraces(); } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { disableLongStackTraces(); } } if ("warnings" in opts) { var warningsOption = opts.warnings; config.warnings = !!warningsOption; wForgottenReturn = config.warnings; if (util.isObject(warningsOption)) { if ("wForgottenReturn" in warningsOption) { wForgottenReturn = !!warningsOption.wForgottenReturn; } } } if ("cancellation" in opts && opts.cancellation && !config.cancellation) { if (async.haveItemsQueued()) { throw new Error( "cannot enable cancellation after promises are in use"); } Promise.prototype._clearCancellationData = cancellationClearCancellationData; Promise.prototype._propagateFrom = cancellationPropagateFrom; Promise.prototype._onCancel = cancellationOnCancel; Promise.prototype._setOnCancel = cancellationSetOnCancel; Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; Promise.prototype._execute = cancellationExecute; propagateFromFunction = cancellationPropagateFrom; config.cancellation = true; } if ("monitoring" in opts) { if (opts.monitoring && !config.monitoring) { config.monitoring = true; Promise.prototype._fireEvent = activeFireEvent; } else if (!opts.monitoring && config.monitoring) { config.monitoring = false; Promise.prototype._fireEvent = defaultFireEvent; } } return Promise; }; function defaultFireEvent() { return false; } Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._execute = function(executor, resolve, reject) { try { executor(resolve, reject); } catch (e) { return e; } }; Promise.prototype._onCancel = function () {}; Promise.prototype._setOnCancel = function (handler) { ; }; Promise.prototype._attachCancellationCallback = function(onCancel) { ; }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; ; }; function cancellationExecute(executor, resolve, reject) { var promise = this; try { executor(resolve, reject, function(onCancel) { if (typeof onCancel !== "function") { throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); } promise._attachCancellationCallback(onCancel); }); } catch (e) { return e; } } function cancellationAttachCancellationCallback(onCancel) { if (!this._isCancellable()) return this; var previousOnCancel = this._onCancel(); if (previousOnCancel !== undefined) { if (util.isArray(previousOnCancel)) { previousOnCancel.push(onCancel); } else { this._setOnCancel([previousOnCancel, onCancel]); } } else { this._setOnCancel(onCancel); } } function cancellationOnCancel() { return this._onCancelField; } function cancellationSetOnCancel(onCancel) { this._onCancelField = onCancel; } function cancellationClearCancellationData() { this._cancellationParent = undefined; this._onCancelField = undefined; } function cancellationPropagateFrom(parent, flags) { if ((flags & 1) !== 0) { this._cancellationParent = parent; var branchesRemainingToCancel = parent._branchesRemainingToCancel; if (branchesRemainingToCancel === undefined) { branchesRemainingToCancel = 0; } parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; } if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } function bindingPropagateFrom(parent, flags) { if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } var propagateFromFunction = bindingPropagateFrom; function boundValueFunction() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; } function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } function longStackTracesAttachExtraTrace(error, ignoreSelf) { if (canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } } function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) { if (parent !== undefined && parent._returnedNonUndefined()) return; if ((promise._bitField & 65535) === 0) return; if (name) name = name + " "; var handlerLine = ""; var creatorLine = ""; if (promiseCreated._trace) { var traceLines = promiseCreated._trace.stack.split("\n"); var stack = cleanStack(traceLines); for (var i = stack.length - 1; i >= 0; --i) { var line = stack[i]; if (!nodeFramePattern.test(line)) { var lineMatches = line.match(parseLinePattern); if (lineMatches) { handlerLine = "at " + lineMatches[1] + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; } break; } } if (stack.length > 0) { var firstUserLine = stack[0]; for (var i = 0; i < traceLines.length; ++i) { if (traceLines[i] === firstUserLine) { if (i > 0) { creatorLine = "\n" + traceLines[i - 1]; } break; } } } } var msg = "a promise was created in a " + name + "handler " + handlerLine + "but was not returned from it, " + "see http://goo.gl/rRqMUw" + creatorLine; promise._warn(msg, true, promiseCreated); } } function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; if (replacement) message += " Use " + replacement + " instead."; return warn(message); } function warn(message, shouldUseOwnTrace, promise) { if (!config.warnings) return; var warning = new Warning(message); var ctx; if (shouldUseOwnTrace) { promise._attachExtraTrace(warning); } else if (config.longStackTraces && (ctx = Promise._peekContext())) { ctx.attachExtraTrace(warning); } else { var parsed = parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } if (!activeFireEvent("warning", warning)) { formatAndLogError(warning, "", true); } } function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0 && error.name != "SyntaxError") { stack = stack.slice(i); } return stack; } function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: error.name == "SyntaxError" ? stack : cleanStack(stack) }; } function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof printWarning === "function") { printWarning(message, isSoft); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } } function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } if (name === "unhandledRejection") { if (!activeFireEvent(name, reason, promise) && !localEventFired) { formatAndLogError(reason, "Unhandled rejection "); } } else { activeFireEvent(name, promise); } } function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } function longStackTracesIsSupported() { return typeof captureStackTrace === "function"; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; } function CapturedTrace(parent) { this._parent = parent; this._promisesCreated = 0; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); Context.CapturedTrace = CapturedTrace; CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit -= 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit -= 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { printWarning = function(message, isSoft) { var color = isSoft ? "\u001b[33m" : "\u001b[31m"; console.warn(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { printWarning = function(message, isSoft) { console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); }; } } var config = { warnings: warnings, longStackTraces: false, cancellation: false, monitoring: false }; if (longStackTraces) Promise.longStackTraces(); return { longStackTraces: function() { return config.longStackTraces; }, warnings: function() { return config.warnings; }, cancellation: function() { return config.cancellation; }, monitoring: function() { return config.monitoring; }, propagateFromFunction: function() { return propagateFromFunction; }, boundValueFunction: function() { return boundValueFunction; }, checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, CapturedTrace: CapturedTrace, fireDomEvent: fireDomEvent, fireGlobalEvent: fireGlobalEvent }; }; },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function returner() { return this.value; } function thrower() { throw this.reason; } Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { return this._then( thrower, undefined, undefined, {reason: reason}, undefined); }; Promise.prototype.catchThrow = function (reason) { if (arguments.length <= 1) { return this._then( undefined, thrower, undefined, {reason: reason}, undefined); } else { var _reason = arguments[1]; var handler = function() {throw _reason;}; return this.caught(reason, handler); } }; Promise.prototype.catchReturn = function (value) { if (arguments.length <= 1) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( undefined, returner, undefined, {value: value}, undefined); } else { var _value = arguments[1]; if (_value instanceof Promise) _value.suppressUnhandledRejections(); var handler = function() {return _value;}; return this.caught(value, handler); } }; }; },{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return PromiseReduce(this, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseReduce(promises, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; },{}],12:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); es5.defineProperty(Error, "__BluebirdErrorTypes__", { value: errorTypes, writable: false, enumerable: false, configurable: false }); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { var util = _dereq_("./util"); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); function PassThroughHandlerContext(promise, type, handler) { this.promise = promise; this.type = type; this.handler = handler; this.called = false; this.cancelPromise = null; } PassThroughHandlerContext.prototype.isFinallyHandler = function() { return this.type === 0; }; function FinallyHandlerCancelReaction(finallyHandler) { this.finallyHandler = finallyHandler; } FinallyHandlerCancelReaction.prototype._resultCancelled = function() { checkCancel(this.finallyHandler); }; function checkCancel(ctx, reason) { if (ctx.cancelPromise != null) { if (arguments.length > 1) { ctx.cancelPromise._reject(reason); } else { ctx.cancelPromise._cancel(); } ctx.cancelPromise = null; return true; } return false; } function succeed() { return finallyHandler.call(this, this.promise._target()._settledValue()); } function fail(reason) { if (checkCancel(this, reason)) return; errorObj.e = reason; return errorObj; } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; if (!this.called) { this.called = true; var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); if (ret === NEXT_FILTER) { return ret; } else if (ret !== undefined) { promise._setReturnedNonUndefined(); var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { if (this.cancelPromise != null) { if (maybePromise._isCancelled()) { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); errorObj.e = reason; return errorObj; } else if (maybePromise.isPending()) { maybePromise._attachCancellationCallback( new FinallyHandlerCancelReaction(this)); } } return maybePromise._then( succeed, fail, undefined, this, undefined); } } } if (promise.isRejected()) { checkCancel(this); errorObj.e = reasonOrValue; return errorObj; } else { checkCancel(this); return reasonOrValue; } } Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThrough(handler, 0, finallyHandler, finallyHandler); }; Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; Promise.prototype.tapCatch = function (handlerOrPredicate) { var len = arguments.length; if(len === 1) { return this._passThrough(handlerOrPredicate, 1, undefined, finallyHandler); } else { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return Promise.reject(new TypeError( "tapCatch statement predicate: " + "expecting an object but got " + util.classString(item) )); } } catchInstances.length = j; var handler = arguments[i]; return this._passThrough(catchFilter(catchInstances, handler, this), 1, undefined, finallyHandler); } }; return PassThroughHandlerContext; }; },{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = _dereq_("./errors"); var TypeError = errors.TypeError; var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { if (debug.cancellation()) { var internal = new Promise(INTERNAL); var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); this._promise = internal.lastly(function() { return _finallyPromise; }); internal._captureStackTrace(); internal._setOnCancel(this); } else { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); } this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; this._cancellationPhase = false; } util.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this._promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; if (debug.cancellation() && this._finallyPromise !== null) { this._finallyPromise._fulfill(); this._finallyPromise = null; } }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } this._cancellationPhase = true; this._yieldedPromise = null; this._continue(result); }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._rejectCallback(result.e, false); } } var value = result.value; if (result.done === true) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._resolveCallback(value); } } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { Promise._async.invoke( this._promiseFulfilled, this, maybePromise._value() ); } else if (((bitField & 16777216) !== 0)) { Promise._async.invoke( this._promiseRejected, this, maybePromise._reason() ); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; var reject; if (!true) { if (canEvaluate) { var thenCallback = function(i) { return new Function("value", "holder", " \n\ 'use strict'; \n\ holder.pIndex = value; \n\ holder.checkFulfillment(this); \n\ ".replace(/Index/g, i)); }; var promiseSetter = function(i) { return new Function("promise", "holder", " \n\ 'use strict'; \n\ holder.pIndex = promise; \n\ ".replace(/Index/g, i)); }; var generateHolderClass = function(total) { var props = new Array(total); for (var i = 0; i < props.length; ++i) { props[i] = "this.p" + (i+1); } var assignment = props.join(" = ") + " = null;"; var cancellationCode= "var promise;\n" + props.map(function(prop) { return " \n\ promise = " + prop + "; \n\ if (promise instanceof Promise) { \n\ promise.cancel(); \n\ } \n\ "; }).join("\n"); var passedArguments = props.join(", "); var name = "Holder$" + total; var code = "return function(tryCatch, errorObj, Promise, async) { \n\ 'use strict'; \n\ function [TheName](fn) { \n\ [TheProperties] \n\ this.fn = fn; \n\ this.asyncNeeded = true; \n\ this.now = 0; \n\ } \n\ \n\ [TheName].prototype._callFunction = function(promise) { \n\ promise._pushContext(); \n\ var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ promise._popContext(); \n\ if (ret === errorObj) { \n\ promise._rejectCallback(ret.e, false); \n\ } else { \n\ promise._resolveCallback(ret); \n\ } \n\ }; \n\ \n\ [TheName].prototype.checkFulfillment = function(promise) { \n\ var now = ++this.now; \n\ if (now === [TheTotal]) { \n\ if (this.asyncNeeded) { \n\ async.invoke(this._callFunction, this, promise); \n\ } else { \n\ this._callFunction(promise); \n\ } \n\ \n\ } \n\ }; \n\ \n\ [TheName].prototype._resultCancelled = function() { \n\ [CancellationCode] \n\ }; \n\ \n\ return [TheName]; \n\ }(tryCatch, errorObj, Promise, async); \n\ "; code = code.replace(/\[TheName\]/g, name) .replace(/\[TheTotal\]/g, total) .replace(/\[ThePassedArguments\]/g, passedArguments) .replace(/\[TheProperties\]/g, assignment) .replace(/\[CancellationCode\]/g, cancellationCode); return new Function("tryCatch", "errorObj", "Promise", "async", code) (tryCatch, errorObj, Promise, async); }; var holderClasses = []; var thenCallbacks = []; var promiseSetters = []; for (var i = 0; i < 8; ++i) { holderClasses.push(generateHolderClass(i + 1)); thenCallbacks.push(thenCallback(i + 1)); promiseSetters.push(promiseSetter(i + 1)); } reject = function (reason) { this._reject(reason); }; }} Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (!true) { if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var HolderClass = holderClasses[last - 1]; var holder = new HolderClass(fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); promiseSetters[i](maybePromise, holder); holder.asyncNeeded = false; } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); } else { ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } if (!ret._isFateSealed()) { if (holder.asyncNeeded) { var domain = getDomain(); if (domain !== null) { holder.fn = util.domainBind(domain, holder.fn); } } ret._setAsyncGuaranteed(); ret._setOnCancel(holder); } return ret; } } } var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : util.domainBind(domain, fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = []; async.invoke(this._asyncInit, this, undefined); } util.inherits(MappingPromiseArray, PromiseArray); MappingPromiseArray.prototype._asyncInit = function() { this._init$(undefined, -2); }; MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (index < 0) { index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return false; } if (preservedValues !== null) preservedValues[index] = value; var promise = this._promise; var callback = this._callback; var receiver = promise._boundValue(); promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise ); if (ret === errorObj) { this._reject(ret.e); return true; } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; values[index] = maybePromise; maybePromise._proxy(this, (index + 1) * -1); return false; } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); } else if (((bitField & 16777216) !== 0)) { this._reject(maybePromise._reason()); return true; } else { this._cancel(); return true; } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } return true; } return false; }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var limit = 0; if (options !== undefined) { if (typeof options === "object" && options !== null) { if (typeof options.concurrency !== "number") { return Promise.reject( new TypeError("'concurrency' must be a number but it is " + util.classString(options.concurrency))); } limit = options.concurrency; } else { return Promise.reject(new TypeError( "options argument must be an object but it is " + util.classString(options))); } } limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } Promise.prototype.map = function (fn, options) { return map(this, fn, options, null); }; Promise.map = function (promises, fn, options, _filter) { return map(promises, fn, options, _filter); }; }; },{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value; if (arguments.length > 1) { debug.deprecated("calling Promise.try with more than 1 argument"); var arg = arguments[1]; var ctx = arguments[2]; value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); } else { value = tryCatch(fn)(); } var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.try", ret); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; },{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise, multiArgs) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (!multiArgs) { promise._fulfill(value); } else { var args = [].slice.call(arguments, 1);; promise._fulfill(args); } promise = null; }; } module.exports = nodebackForPromise; },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util"); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; },{"./util":36}],22:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = _dereq_("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = _dereq_("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var nodebackForPromise = _dereq_("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (self == null || self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } } function Promise(executor) { if (executor !== INTERNAL) { check(this, executor); } this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; this._resolveFromExecutor(executor); this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("Catch statement predicate: " + "expecting an object but got " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } return async.setScheduler(fn); }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && util.domainBind(domain, handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setWillBeCancelled = function() { this._bitField = this._bitField | 8388608; }; Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : util.domainBind(domain, reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : util.domainBind(domain, reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { if (executor === INTERNAL) return; var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); Promise.Promise = Promise; Promise.version = "3.5.1"; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./call_get.js')(Promise); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./timers.js')(Promise, INTERNAL, debug); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./filter.js')(Promise, INTERNAL); _dereq_('./each.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { var util = _dereq_("./util"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; case -6: return new Map(); } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); } promise._setOnCancel(this); this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } util.inherits(PromiseArray, Proxyable); PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); var bitField = values._bitField; ; this._values = values; if (((bitField & 50397184) === 0)) { this._promise._setAsyncGuaranteed(); return values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); } else if (((bitField & 33554432) !== 0)) { values = values._value(); } else if (((bitField & 16777216) !== 0)) { return this._reject(values._reason()); } else { return this._cancel(); } } values = util.asArray(values); if (values === null) { var err = apiRejection( "expecting an array or an iterable object but got " + util.classString(values)).reason(); this._promise._rejectCallback(err, false); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } this._iterate(values); }; PromiseArray.prototype._iterate = function(values) { var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var result = this._promise; var isResolved = false; var bitField = null; for (var i = 0; i < len; ++i) { var maybePromise = tryConvertToPromise(values[i], result); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); bitField = maybePromise._bitField; } else { bitField = null; } if (isResolved) { if (bitField !== null) { maybePromise.suppressUnhandledRejections(); } } else if (bitField !== null) { if (((bitField & 50397184) === 0)) { maybePromise._proxy(this, i); this._values[i] = maybePromise; } else if (((bitField & 33554432) !== 0)) { isResolved = this._promiseFulfilled(maybePromise._value(), i); } else if (((bitField & 16777216) !== 0)) { isResolved = this._promiseRejected(maybePromise._reason(), i); } else { isResolved = this._promiseCancelled(i); } } else { isResolved = this._promiseFulfilled(maybePromise, i); } } if (!isResolved) result._setAsyncGuaranteed(); }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype._cancel = function() { if (this._isResolved() || !this._promise._isCancellable()) return; this._values = null; this._promise._cancel(); }; PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; PromiseArray.prototype._promiseCancelled = function() { this._cancel(); return true; }; PromiseArray.prototype._promiseRejected = function (reason) { this._totalResolved++; this._reject(reason); return true; }; PromiseArray.prototype._resultCancelled = function() { if (this._isResolved()) return; var values = this._values; this._cancel(); if (values instanceof Promise) { values.cancel(); } else { for (var i = 0; i < values.length; ++i) { if (values[i] instanceof Promise) { values[i].cancel(); } } } }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util"); var nodebackForPromise = _dereq_("./nodeback"); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; if (!true) { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var isObject = util.isObject; var es5 = _dereq_("./es5"); var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, isMap ? -6 : -3); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; },{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : util.domainBind(domain, fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; if(_each === INTERNAL) { this._eachValues = Array(this._length); } else if (_each === 0) { this._eachValues = null; } else { this._eachValues = undefined; } this._promise._captureStackTrace(); this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && this._eachValues !== null && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { if (this._eachValues !== null) { this._eachValues.push(value); } return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; },{"./util":36}],29:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var NativePromise = util.getNativePromise(); if (util.isNode && typeof MutationObserver === "undefined") { var GlobalSetImmediate = global.setImmediate; var ProcessNextTick = process.nextTick; schedule = util.isRecentNode ? function(fn) { GlobalSetImmediate.call(global, fn); } : function(fn) { ProcessNextTick.call(process, fn); }; } else if (typeof NativePromise === "function" && typeof NativePromise.resolve === "function") { var nativePromise = NativePromise.resolve(); schedule = function(fn) { nativePromise.then(fn); }; } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && (window.navigator.standalone || window.cordova))) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; var toggleScheduled = false; var div2 = document.createElement("div"); var o2 = new MutationObserver(function() { div.classList.toggle("foo"); toggleScheduled = false; }); o2.observe(div2, opts); var scheduleToggle = function() { if (toggleScheduled) return; toggleScheduled = true; div2.classList.toggle("foo"); }; return function schedule(fn) { var o = new MutationObserver(function() { o.disconnect(); fn(); }); o.observe(div, opts); scheduleToggle(); }; })(); } else if (typeof setImmediate !== "undefined") { schedule = function (fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function (fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; },{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); } util.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; },{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util"); var RangeError = _dereq_("./errors").RangeError; var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; } else { this._bitField = 0; this._settledValueField = undefined; } } PromiseInspection.prototype._settledValue = function() { return this._settledValueField; }; var value = PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { return (this._bitField & 33554432) !== 0; }; var isRejected = PromiseInspection.prototype.isRejected = function () { return (this._bitField & 16777216) !== 0; }; var isPending = PromiseInspection.prototype.isPending = function () { return (this._bitField & 50397184) === 0; }; var isResolved = PromiseInspection.prototype.isResolved = function () { return (this._bitField & 50331648) !== 0; }; PromiseInspection.prototype.isCancelled = function() { return (this._bitField & 8454144) !== 0; }; Promise.prototype.__isCancelled = function() { return (this._bitField & 65536) === 65536; }; Promise.prototype._isCancelled = function() { return this._target().__isCancelled(); }; Promise.prototype.isCancelled = function() { return (this._target()._bitField & 8454144) !== 0; }; Promise.prototype.isPending = function() { return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { return isResolved.call(this._target()); }; Promise.prototype.value = function() { return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); target._unsetRejectionIsUnhandled(); return reason.call(target); }; Promise.prototype._value = function() { return this._settledValue(); }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue(); }; Promise.PromiseInspection = PromiseInspection; }; },{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) return obj; var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfill, ret._reject, undefined, ret, null ); return ret; } return doThenable(obj, then, context); } } return obj; } function doGetThen(obj) { return obj.then; } function getThen(obj) { try { return doGetThen(obj); } catch (e) { errorObj.e = e; return errorObj; } } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { try { return hasProp.call(obj, "_promise0"); } catch (e) { return false; } } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } function resolve(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } return ret; } return tryConvertToPromise; }; },{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, debug) { var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { this.handle = handle; } HandleWrapper.prototype._resultCancelled = function() { clearTimeout(this.handle); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; var handle; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); if (debug.cancellation() && value instanceof Promise) { ret._setOnCancel(value); } } else { ret = new Promise(INTERNAL); handle = setTimeout(function() { ret._fulfill(); }, +ms); if (debug.cancellation()) { ret._setOnCancel(new HandleWrapper(handle)); } ret._captureStackTrace(); } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; var afterTimeout = function (promise, message, parent) { var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); if (parent != null) { parent.cancel(); } }; function successClear(value) { clearTimeout(this.handle); return value; } function failureClear(reason) { clearTimeout(this.handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret.isPending()) { afterTimeout(ret, message, parent); } }, ms)); if (debug.cancellation()) { parent = this.then(); ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); ret._setOnCancel(handleWrapper); } else { ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); } return ret; }; }; },{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { var util = _dereq_("./util"); var TypeError = _dereq_("./errors").TypeError; var inherits = _dereq_("./util").inherits; var errorObj = util.errorObj; var tryCatch = util.tryCatch; var NULL = {}; function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = new Promise(INTERNAL); function iterator() { if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret; } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return NULL; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== NULL ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } function ResourceList(length) { this.length = length; this.promise = null; this[length-1] = null; } ResourceList.prototype._resultCancelled = function() { var len = this.length; for (var i = 0; i < len; ++i) { var item = this[i]; if (item instanceof Promise) { item.cancel(); } } }; Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var reflectedResources = new Array(resources.length); for (var i = 0; i < reflectedResources.length; ++i) { reflectedResources[i] = Promise.resolve(resources[i]).reflect(); } var resultPromise = Promise.all(reflectedResources) .then(function(inspections) { for (var i = 0; i < inspections.length; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { errorObj.e = inspection.error(); return errorObj; } else if (!inspection.isFulfilled()) { resultPromise.cancel(); return; } inspections[i] = inspection.value(); } promise._pushContext(); fn = tryCatch(fn); var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, "Promise.using", promise); return ret; }); var promise = resultPromise.lastly(function() { var inspection = new Promise.PromiseInspection(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; var tryCatchTarget; var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this !== undefined ? this : null; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return typeof value === "function" || typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; var l = 8; while (l--) new FakeConstructor(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function isError(obj) { return obj instanceof Error || (obj !== null && typeof obj === "object" && typeof obj.message === "string" && typeof obj.name === "string"); } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return isError(obj) && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var asArray = function(v) { if (es5.isArray(v)) { return v; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { var ArrayFrom = typeof Array.from === "function" ? function(v) { return Array.from(v); } : function(v) { var ret = []; var it = v[Symbol.iterator](); var itResult; while (!((itResult = it.next()).done)) { ret.push(itResult.value); } return ret; }; asArray = function(v) { if (es5.isArray(v)) { return v; } else if (v != null && typeof v[Symbol.iterator] === "function") { return ArrayFrom(v); } return null; }; } var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; var hasEnvVariables = typeof process !== "undefined" && typeof process.env !== "undefined"; function env(key) { return hasEnvVariables ? process.env[key] : undefined; } function getNativePromise() { if (typeof Promise === "function") { try { var promise = new Promise(function(){}); if ({}.toString.call(promise) === "[object Promise]") { return Promise; } } catch (e) {} } } function domainBind(self, cb) { return self.bind(cb); } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, isError: isError, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: isNode, hasEnvVariables: hasEnvVariables, env: env, global: globalObject, getNativePromise: getNativePromise, domainBind: domainBind }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) },{"_process":399,"timers":403}],95:[function(require,module,exports){ (function (global){ /** * Module dependencies. * @ignore */ // Test if we're in Node via presence of "global" not absence of "window" // to support hybrid environments like Electron if (typeof global !== 'undefined') { var Buffer = require('buffer').Buffer; // TODO just use global Buffer } var utils = require('./parser/utils'); /** * A class representation of the BSON Binary type. * * Sub types * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. * * @class * @param {Buffer} buffer a buffer object containing the binary data. * @param {Number} [subType] the option binary type. * @return {Binary} */ function Binary(buffer, subType) { if (!(this instanceof Binary)) return new Binary(buffer, subType); if ( buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer) ) { throw new Error('only String, Buffer, Uint8Array or Array accepted'); } this._bsontype = 'Binary'; if (buffer instanceof Number) { this.sub_type = buffer; this.position = 0; } else { this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; this.position = 0; } if (buffer != null && !(buffer instanceof Number)) { // Only accept Buffer, Uint8Array or Arrays if (typeof buffer === 'string') { // Different ways of writing the length of the string for the different types if (typeof Buffer !== 'undefined') { this.buffer = utils.toBuffer(buffer); } else if ( typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]' ) { this.buffer = writeStringToArray(buffer); } else { throw new Error('only String, Buffer, Uint8Array or Array accepted'); } } else { this.buffer = buffer; } this.position = buffer.length; } else { if (typeof Buffer !== 'undefined') { this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); } else if (typeof Uint8Array !== 'undefined') { this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); } else { this.buffer = new Array(Binary.BUFFER_SIZE); } // Set position to start of buffer this.position = 0; } } /** * Updates this binary with byte_value. * * @method * @param {string} byte_value a single byte we wish to write. */ Binary.prototype.put = function put(byte_value) { // If it's a string and a has more than one character throw an error if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); // Decode the byte value once var decoded_byte = null; if (typeof byte_value === 'string') { decoded_byte = byte_value.charCodeAt(0); } else if (byte_value['length'] != null) { decoded_byte = byte_value[0]; } else { decoded_byte = byte_value; } if (this.buffer.length > this.position) { this.buffer[this.position++] = decoded_byte; } else { if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { // Create additional overflow buffer var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); // Combine the two buffers together this.buffer.copy(buffer, 0, 0, this.buffer.length); this.buffer = buffer; this.buffer[this.position++] = decoded_byte; } else { buffer = null; // Create a new buffer (typed or normal array) if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); } else { buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); } // We need to copy all the content to the new array for (var i = 0; i < this.buffer.length; i++) { buffer[i] = this.buffer[i]; } // Reassign the buffer this.buffer = buffer; // Write the byte this.buffer[this.position++] = decoded_byte; } } }; /** * Writes a buffer or string to the binary. * * @method * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. * @param {number} offset specify the binary of where to write the content. * @return {null} */ Binary.prototype.write = function write(string, offset) { offset = typeof offset === 'number' ? offset : this.position; // If the buffer is to small let's extend the buffer if (this.buffer.length < offset + string.length) { var buffer = null; // If we are in node.js if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { buffer = utils.allocBuffer(this.buffer.length + string.length); this.buffer.copy(buffer, 0, 0, this.buffer.length); } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { // Create a new buffer buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); // Copy the content for (var i = 0; i < this.position; i++) { buffer[i] = this.buffer[i]; } } // Assign the new buffer this.buffer = buffer; } if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { string.copy(this.buffer, offset, 0, string.length); this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length } else if ( typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer) ) { this.buffer.write(string, offset, 'binary'); this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length; } else if ( Object.prototype.toString.call(string) === '[object Uint8Array]' || (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') ) { for (i = 0; i < string.length; i++) { this.buffer[offset++] = string[i]; } this.position = offset > this.position ? offset : this.position; } else if (typeof string === 'string') { for (i = 0; i < string.length; i++) { this.buffer[offset++] = string.charCodeAt(i); } this.position = offset > this.position ? offset : this.position; } }; /** * Reads **length** bytes starting at **position**. * * @method * @param {number} position read from the given position in the Binary. * @param {number} length the number of bytes to read. * @return {Buffer} */ Binary.prototype.read = function read(position, length) { length = length && length > 0 ? length : this.position; // Let's return the data based on the type we have if (this.buffer['slice']) { return this.buffer.slice(position, position + length); } else { // Create a buffer to keep the result var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); for (var i = 0; i < length; i++) { buffer[i] = this.buffer[position++]; } } // Return the buffer return buffer; }; /** * Returns the value of this binary as a string. * * @method * @return {string} */ Binary.prototype.value = function value(asRaw) { asRaw = asRaw == null ? false : asRaw; // Optimize to serialize for the situation where the data == size of buffer if ( asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position ) return this.buffer; // If it's a node.js buffer object if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); } else { if (asRaw) { // we support the slice command use it if (this.buffer['slice'] != null) { return this.buffer.slice(0, this.position); } else { // Create a new buffer to copy content to var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); // Copy content for (var i = 0; i < this.position; i++) { newBuffer[i] = this.buffer[i]; } // Return the buffer return newBuffer; } } else { return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); } } }; /** * Length. * * @method * @return {number} the length of the binary. */ Binary.prototype.length = function length() { return this.position; }; /** * @ignore */ Binary.prototype.toJSON = function() { return this.buffer != null ? this.buffer.toString('base64') : ''; }; /** * @ignore */ Binary.prototype.toString = function(format) { return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; }; /** * Binary default subtype * @ignore */ var BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * @ignore */ var writeStringToArray = function(data) { // Create a buffer var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); // Write the content to the buffer for (var i = 0; i < data.length; i++) { buffer[i] = data.charCodeAt(i); } // Write the string to the buffer return buffer; }; /** * Convert Array ot Uint8Array to Binary String * * @ignore */ var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { var result = ''; for (var i = startIndex; i < endIndex; i++) { result = result + String.fromCharCode(byteArray[i]); } return result; }; Binary.BUFFER_SIZE = 256; /** * Default BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_DEFAULT = 0; /** * Function BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_FUNCTION = 1; /** * Byte Array BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_BYTE_ARRAY = 2; /** * OLD UUID BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_UUID_OLD = 3; /** * UUID BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_UUID = 4; /** * MD5 BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_MD5 = 5; /** * User BSON type * * @classconstant SUBTYPE_DEFAULT **/ Binary.SUBTYPE_USER_DEFINED = 128; /** * Expose. */ module.exports = Binary; module.exports.Binary = Binary; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./parser/utils":111,"buffer":115}],96:[function(require,module,exports){ 'use strict'; var Map = require('./map'), Long = require('./long'), Double = require('./double'), Timestamp = require('./timestamp'), ObjectID = require('./objectid'), BSONRegExp = require('./regexp'), Symbol = require('./symbol'), Int32 = require('./int_32'), Code = require('./code'), Decimal128 = require('./decimal128'), MinKey = require('./min_key'), MaxKey = require('./max_key'), DBRef = require('./db_ref'), Binary = require('./binary'); // Parts of the parser var deserialize = require('./parser/deserializer'), serializer = require('./parser/serializer'), calculateObjectSize = require('./parser/calculate_size'), utils = require('./parser/utils'); /** * @ignore * @api private */ // Default Max Size var MAXSIZE = 1024 * 1024 * 17; // Current Internal Temporary Serialization Buffer var buffer = utils.allocBuffer(MAXSIZE); var BSON = function() {}; /** * Serialize a Javascript object. * * @param {Object} object the Javascript object to serialize. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. * @return {Buffer} returns the Buffer object containing the serialized object. * @api public */ BSON.prototype.serialize = function serialize(object, options) { options = options || {}; // Unpack the options var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; // Resize the internal serialization buffer if needed if (buffer.length < minInternalBufferSize) { buffer = utils.allocBuffer(minInternalBufferSize); } // Attempt to serialize var serializationIndex = serializer( buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, [] ); // Create the final buffer var finishedBuffer = utils.allocBuffer(serializationIndex); // Copy into the finished buffer buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); // Return the buffer return finishedBuffer; }; /** * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. * * @param {Object} object the Javascript object to serialize. * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. * @return {Number} returns the index pointing to the last written byte in the buffer. * @api public */ BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { options = options || {}; // Unpack the options var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; var startIndex = typeof options.index === 'number' ? options.index : 0; // Attempt to serialize var serializationIndex = serializer( finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined ); // Return the index return serializationIndex - 1; }; /** * Deserialize data as BSON. * * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. * @return {Object} returns the deserialized Javascript Object. * @api public */ BSON.prototype.deserialize = function(buffer, options) { return deserialize(buffer, options); }; /** * Calculate the bson size for a passed in Javascript object. * * @param {Object} object the Javascript object to calculate the BSON byte size for. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. * @return {Number} returns the number of bytes the BSON object will take up. * @api public */ BSON.prototype.calculateObjectSize = function(object, options) { options = options || {}; var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; return calculateObjectSize(object, serializeFunctions, ignoreUndefined); }; /** * Deserialize stream data as BSON documents. * * @param {Buffer} data the buffer containing the serialized set of BSON documents. * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. * @param {Number} numberOfDocuments number of documents to deserialize. * @param {Array} documents an array where to store the deserialized documents. * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. * @param {Object} [options] additional options used for the deserialization. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. * @api public */ BSON.prototype.deserializeStream = function( data, startIndex, numberOfDocuments, documents, docStartIndex, options ) { options = options != null ? options : {}; var index = startIndex; // Loop over all documents for (var i = 0; i < numberOfDocuments; i++) { // Find size of the document var size = data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); // Update options with index options['index'] = index; // Parse the document at this point documents[docStartIndex + i] = this.deserialize(data, options); // Adjust index by the document size index = index + size; } // Return object containing end index of parsing and list of documents return index; }; /** * @ignore * @api private */ // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; BSON.BSON_INT64_MIN = -Math.pow(2, 63); // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // Internal long versions // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. /** * Number BSON Type * * @classconstant BSON_DATA_NUMBER **/ BSON.BSON_DATA_NUMBER = 1; /** * String BSON Type * * @classconstant BSON_DATA_STRING **/ BSON.BSON_DATA_STRING = 2; /** * Object BSON Type * * @classconstant BSON_DATA_OBJECT **/ BSON.BSON_DATA_OBJECT = 3; /** * Array BSON Type * * @classconstant BSON_DATA_ARRAY **/ BSON.BSON_DATA_ARRAY = 4; /** * Binary BSON Type * * @classconstant BSON_DATA_BINARY **/ BSON.BSON_DATA_BINARY = 5; /** * ObjectID BSON Type * * @classconstant BSON_DATA_OID **/ BSON.BSON_DATA_OID = 7; /** * Boolean BSON Type * * @classconstant BSON_DATA_BOOLEAN **/ BSON.BSON_DATA_BOOLEAN = 8; /** * Date BSON Type * * @classconstant BSON_DATA_DATE **/ BSON.BSON_DATA_DATE = 9; /** * null BSON Type * * @classconstant BSON_DATA_NULL **/ BSON.BSON_DATA_NULL = 10; /** * RegExp BSON Type * * @classconstant BSON_DATA_REGEXP **/ BSON.BSON_DATA_REGEXP = 11; /** * Code BSON Type * * @classconstant BSON_DATA_CODE **/ BSON.BSON_DATA_CODE = 13; /** * Symbol BSON Type * * @classconstant BSON_DATA_SYMBOL **/ BSON.BSON_DATA_SYMBOL = 14; /** * Code with Scope BSON Type * * @classconstant BSON_DATA_CODE_W_SCOPE **/ BSON.BSON_DATA_CODE_W_SCOPE = 15; /** * 32 bit Integer BSON Type * * @classconstant BSON_DATA_INT **/ BSON.BSON_DATA_INT = 16; /** * Timestamp BSON Type * * @classconstant BSON_DATA_TIMESTAMP **/ BSON.BSON_DATA_TIMESTAMP = 17; /** * Long BSON Type * * @classconstant BSON_DATA_LONG **/ BSON.BSON_DATA_LONG = 18; /** * MinKey BSON Type * * @classconstant BSON_DATA_MIN_KEY **/ BSON.BSON_DATA_MIN_KEY = 0xff; /** * MaxKey BSON Type * * @classconstant BSON_DATA_MAX_KEY **/ BSON.BSON_DATA_MAX_KEY = 0x7f; /** * Binary Default Type * * @classconstant BSON_BINARY_SUBTYPE_DEFAULT **/ BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * Binary Function Type * * @classconstant BSON_BINARY_SUBTYPE_FUNCTION **/ BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; /** * Binary Byte Array Type * * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY **/ BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; /** * Binary UUID Type * * @classconstant BSON_BINARY_SUBTYPE_UUID **/ BSON.BSON_BINARY_SUBTYPE_UUID = 3; /** * Binary MD5 Type * * @classconstant BSON_BINARY_SUBTYPE_MD5 **/ BSON.BSON_BINARY_SUBTYPE_MD5 = 4; /** * Binary User Defined Type * * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED **/ BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; // Return BSON module.exports = BSON; module.exports.Code = Code; module.exports.Map = Map; module.exports.Symbol = Symbol; module.exports.BSON = BSON; module.exports.DBRef = DBRef; module.exports.Binary = Binary; module.exports.ObjectID = ObjectID; module.exports.Long = Long; module.exports.Timestamp = Timestamp; module.exports.Double = Double; module.exports.Int32 = Int32; module.exports.MinKey = MinKey; module.exports.MaxKey = MaxKey; module.exports.BSONRegExp = BSONRegExp; module.exports.Decimal128 = Decimal128; },{"./binary":95,"./code":97,"./db_ref":98,"./decimal128":99,"./double":100,"./int_32":102,"./long":103,"./map":104,"./max_key":105,"./min_key":106,"./objectid":107,"./parser/calculate_size":108,"./parser/deserializer":109,"./parser/serializer":110,"./parser/utils":111,"./regexp":112,"./symbol":113,"./timestamp":114}],97:[function(require,module,exports){ /** * A class representation of the BSON Code type. * * @class * @param {(string|function)} code a string or function. * @param {Object} [scope] an optional scope for the function. * @return {Code} */ var Code = function Code(code, scope) { if (!(this instanceof Code)) return new Code(code, scope); this._bsontype = 'Code'; this.code = code; this.scope = scope; }; /** * @ignore */ Code.prototype.toJSON = function() { return { scope: this.scope, code: this.code }; }; module.exports = Code; module.exports.Code = Code; },{}],98:[function(require,module,exports){ /** * A class representation of the BSON DBRef type. * * @class * @param {string} namespace the collection name. * @param {ObjectID} oid the reference ObjectID. * @param {string} [db] optional db name, if omitted the reference is local to the current db. * @return {DBRef} */ function DBRef(namespace, oid, db) { if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); this._bsontype = 'DBRef'; this.namespace = namespace; this.oid = oid; this.db = db; } /** * @ignore * @api private */ DBRef.prototype.toJSON = function() { return { $ref: this.namespace, $id: this.oid, $db: this.db == null ? '' : this.db }; }; module.exports = DBRef; module.exports.DBRef = DBRef; },{}],99:[function(require,module,exports){ 'use strict'; var Long = require('./long'); var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; var EXPONENT_MAX = 6111; var EXPONENT_MIN = -6176; var EXPONENT_BIAS = 6176; var MAX_DIGITS = 34; // Nan value bits as 32 bit values (due to lack of longs) var NAN_BUFFER = [ 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ].reverse(); // Infinity value bits 32 bit values (due to lack of longs) var INF_NEGATIVE_BUFFER = [ 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ].reverse(); var INF_POSITIVE_BUFFER = [ 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ].reverse(); var EXPONENT_REGEX = /^([-+])?(\d+)?$/; var utils = require('./parser/utils'); // Detect if the value is a digit var isDigit = function(value) { return !isNaN(parseInt(value, 10)); }; // Divide two uint128 values var divideu128 = function(value) { var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); var _rem = Long.fromNumber(0); var i = 0; if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { return { quotient: value, rem: _rem }; } for (i = 0; i <= 3; i++) { // Adjust remainder to match value of next dividend _rem = _rem.shiftLeft(32); // Add the divided to _rem _rem = _rem.add(new Long(value.parts[i], 0)); value.parts[i] = _rem.div(DIVISOR).low_; _rem = _rem.modulo(DIVISOR); } return { quotient: value, rem: _rem }; }; // Multiply two Long values and return the 128 bit value var multiply64x2 = function(left, right) { if (!left && !right) { return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; } var leftHigh = left.shiftRightUnsigned(32); var leftLow = new Long(left.getLowBits(), 0); var rightHigh = right.shiftRightUnsigned(32); var rightLow = new Long(right.getLowBits(), 0); var productHigh = leftHigh.multiply(rightHigh); var productMid = leftHigh.multiply(rightLow); var productMid2 = leftLow.multiply(rightHigh); var productLow = leftLow.multiply(rightLow); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productMid = new Long(productMid.getLowBits(), 0) .add(productMid2) .add(productLow.shiftRightUnsigned(32)); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); // Return the 128 bit result return { high: productHigh, low: productLow }; }; var lessThan = function(left, right) { // Make values unsigned var uhleft = left.high_ >>> 0; var uhright = right.high_ >>> 0; // Compare high bits first if (uhleft < uhright) { return true; } else if (uhleft === uhright) { var ulleft = left.low_ >>> 0; var ulright = right.low_ >>> 0; if (ulleft < ulright) return true; } return false; }; // var longtoHex = function(value) { // var buffer = utils.allocBuffer(8); // var index = 0; // // Encode the low 64 bits of the decimal // // Encode low bits // buffer[index++] = value.low_ & 0xff; // buffer[index++] = (value.low_ >> 8) & 0xff; // buffer[index++] = (value.low_ >> 16) & 0xff; // buffer[index++] = (value.low_ >> 24) & 0xff; // // Encode high bits // buffer[index++] = value.high_ & 0xff; // buffer[index++] = (value.high_ >> 8) & 0xff; // buffer[index++] = (value.high_ >> 16) & 0xff; // buffer[index++] = (value.high_ >> 24) & 0xff; // return buffer.reverse().toString('hex'); // }; // var int32toHex = function(value) { // var buffer = utils.allocBuffer(4); // var index = 0; // // Encode the low 64 bits of the decimal // // Encode low bits // buffer[index++] = value & 0xff; // buffer[index++] = (value >> 8) & 0xff; // buffer[index++] = (value >> 16) & 0xff; // buffer[index++] = (value >> 24) & 0xff; // return buffer.reverse().toString('hex'); // }; /** * A class representation of the BSON Decimal128 type. * * @class * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. * @return {Double} */ var Decimal128 = function(bytes) { this._bsontype = 'Decimal128'; this.bytes = bytes; }; /** * Create a Decimal128 instance from a string representation * * @method * @param {string} string a numeric string representation. * @return {Decimal128} returns a Decimal128 instance. */ Decimal128.fromString = function(string) { // Parse state tracking var isNegative = false; var sawRadix = false; var foundNonZero = false; // Total number of significant digits (no leading or trailing zero) var significantDigits = 0; // Total number of significand digits read var nDigitsRead = 0; // Total number of digits (no leading zeros) var nDigits = 0; // The number of the digits after radix var radixPosition = 0; // The index of the first non-zero in *str* var firstNonZero = 0; // Digits Array var digits = [0]; // The number of digits in digits var nDigitsStored = 0; // Insertion pointer for digits var digitsInsert = 0; // The index of the first non-zero digit var firstDigit = 0; // The index of the last digit var lastDigit = 0; // Exponent var exponent = 0; // loop index over array var i = 0; // The high 17 digits of the significand var significandHigh = [0, 0]; // The low 17 digits of the significand var significandLow = [0, 0]; // The biased exponent var biasedExponent = 0; // Read index var index = 0; // Trim the string string = string.trim(); // Naively prevent against REDOS attacks. // TODO: implementing a custom parsing for this, or refactoring the regex would yield // further gains. if (string.length >= 7000) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Results var stringMatch = string.match(PARSE_STRING_REGEXP); var infMatch = string.match(PARSE_INF_REGEXP); var nanMatch = string.match(PARSE_NAN_REGEXP); // Validate the string if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Check if we have an illegal exponent format if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Get the negative or positive sign if (string[index] === '+' || string[index] === '-') { isNegative = string[index++] === '-'; } // Check if user passed Infinity or NaN if (!isDigit(string[index]) && string[index] !== '.') { if (string[index] === 'i' || string[index] === 'I') { return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } else if (string[index] === 'N') { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } } // Read all the digits while (isDigit(string[index]) || string[index] === '.') { if (string[index] === '.') { if (sawRadix) { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } sawRadix = true; index = index + 1; continue; } if (nDigitsStored < 34) { if (string[index] !== '0' || foundNonZero) { if (!foundNonZero) { firstNonZero = nDigitsRead; } foundNonZero = true; // Only store 34 digits digits[digitsInsert++] = parseInt(string[index], 10); nDigitsStored = nDigitsStored + 1; } } if (foundNonZero) { nDigits = nDigits + 1; } if (sawRadix) { radixPosition = radixPosition + 1; } nDigitsRead = nDigitsRead + 1; index = index + 1; } if (sawRadix && !nDigitsRead) { throw new Error('' + string + ' not a valid Decimal128 string'); } // Read exponent if exists if (string[index] === 'e' || string[index] === 'E') { // Read exponent digits var match = string.substr(++index).match(EXPONENT_REGEX); // No digits read if (!match || !match[2]) { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } // Get exponent exponent = parseInt(match[0], 10); // Adjust the index index = index + match[0].length; } // Return not a number if (string[index]) { return new Decimal128(utils.toBuffer(NAN_BUFFER)); } // Done reading input // Find first non-zero digit in digits firstDigit = 0; if (!nDigitsStored) { firstDigit = 0; lastDigit = 0; digits[0] = 0; nDigits = 1; nDigitsStored = 1; significantDigits = 0; } else { lastDigit = nDigitsStored - 1; significantDigits = nDigits; if (exponent !== 0 && significantDigits !== 1) { while (string[firstNonZero + significantDigits - 1] === '0') { significantDigits = significantDigits - 1; } } } // Normalization of exponent // Correct exponent based on radix position, and shift significand as needed // to represent user input // Overflow prevention if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { exponent = EXPONENT_MIN; } else { exponent = exponent - radixPosition; } // Attempt to normalize the exponent while (exponent > EXPONENT_MAX) { // Shift exponent to significand and decrease lastDigit = lastDigit + 1; if (lastDigit - firstDigit > MAX_DIGITS) { // Check if we have a zero then just hard clamp, otherwise fail var digitsString = digits.join(''); if (digitsString.match(/^0+$/)) { exponent = EXPONENT_MAX; break; } else { return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } } exponent = exponent - 1; } while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { // Shift last digit if (lastDigit === 0) { exponent = EXPONENT_MIN; significantDigits = 0; break; } if (nDigitsStored < nDigits) { // adjust to match digits not stored nDigits = nDigits - 1; } else { // adjust to round lastDigit = lastDigit - 1; } if (exponent < EXPONENT_MAX) { exponent = exponent + 1; } else { // Check if we have a zero then just hard clamp, otherwise fail digitsString = digits.join(''); if (digitsString.match(/^0+$/)) { exponent = EXPONENT_MAX; break; } else { return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } } } // Round // We've normalized the exponent, but might still need to round. if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { var endOfString = nDigitsRead; // If we have seen a radix point, 'string' is 1 longer than we have // documented with ndigits_read, so inc the position of the first nonzero // digit and the position that digits are read to. if (sawRadix && exponent === EXPONENT_MIN) { firstNonZero = firstNonZero + 1; endOfString = endOfString + 1; } var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); var roundBit = 0; if (roundDigit >= 5) { roundBit = 1; if (roundDigit === 5) { roundBit = digits[lastDigit] % 2 === 1; for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { if (parseInt(string[i], 10)) { roundBit = 1; break; } } } } if (roundBit) { var dIdx = lastDigit; for (; dIdx >= 0; dIdx--) { if (++digits[dIdx] > 9) { digits[dIdx] = 0; // overflowed most significant digit if (dIdx === 0) { if (exponent < EXPONENT_MAX) { exponent = exponent + 1; digits[dIdx] = 1; } else { return new Decimal128( utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) ); } } } else { break; } } } } // Encode significand // The high 17 digits of the significand significandHigh = Long.fromNumber(0); // The low 17 digits of the significand significandLow = Long.fromNumber(0); // read a zero if (significantDigits === 0) { significandHigh = Long.fromNumber(0); significandLow = Long.fromNumber(0); } else if (lastDigit - firstDigit < 17) { dIdx = firstDigit; significandLow = Long.fromNumber(digits[dIdx++]); significandHigh = new Long(0, 0); for (; dIdx <= lastDigit; dIdx++) { significandLow = significandLow.multiply(Long.fromNumber(10)); significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); } } else { dIdx = firstDigit; significandHigh = Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit - 17; dIdx++) { significandHigh = significandHigh.multiply(Long.fromNumber(10)); significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); } significandLow = Long.fromNumber(digits[dIdx++]); for (; dIdx <= lastDigit; dIdx++) { significandLow = significandLow.multiply(Long.fromNumber(10)); significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); } } var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); significand.low = significand.low.add(significandLow); if (lessThan(significand.low, significandLow)) { significand.high = significand.high.add(Long.fromNumber(1)); } // Biased exponent biasedExponent = exponent + EXPONENT_BIAS; var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; // Encode combination, exponent, and significand. if ( significand.high .shiftRightUnsigned(49) .and(Long.fromNumber(1)) .equals(Long.fromNumber) ) { // Encode '11' into bits 1 to 3 dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); dec.high = dec.high.or( Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) ); dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); } else { dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); } dec.low = significand.low; // Encode sign if (isNegative) { dec.high = dec.high.or(Long.fromString('9223372036854775808')); } // Encode into a buffer var buffer = utils.allocBuffer(16); index = 0; // Encode the low 64 bits of the decimal // Encode low bits buffer[index++] = dec.low.low_ & 0xff; buffer[index++] = (dec.low.low_ >> 8) & 0xff; buffer[index++] = (dec.low.low_ >> 16) & 0xff; buffer[index++] = (dec.low.low_ >> 24) & 0xff; // Encode high bits buffer[index++] = dec.low.high_ & 0xff; buffer[index++] = (dec.low.high_ >> 8) & 0xff; buffer[index++] = (dec.low.high_ >> 16) & 0xff; buffer[index++] = (dec.low.high_ >> 24) & 0xff; // Encode the high 64 bits of the decimal // Encode low bits buffer[index++] = dec.high.low_ & 0xff; buffer[index++] = (dec.high.low_ >> 8) & 0xff; buffer[index++] = (dec.high.low_ >> 16) & 0xff; buffer[index++] = (dec.high.low_ >> 24) & 0xff; // Encode high bits buffer[index++] = dec.high.high_ & 0xff; buffer[index++] = (dec.high.high_ >> 8) & 0xff; buffer[index++] = (dec.high.high_ >> 16) & 0xff; buffer[index++] = (dec.high.high_ >> 24) & 0xff; // Return the new Decimal128 return new Decimal128(buffer); }; // Extract least significant 5 bits var COMBINATION_MASK = 0x1f; // Extract least significant 14 bits var EXPONENT_MASK = 0x3fff; // Value of combination field for Inf var COMBINATION_INFINITY = 30; // Value of combination field for NaN var COMBINATION_NAN = 31; // Value of combination field for NaN // var COMBINATION_SNAN = 32; // decimal128 exponent bias EXPONENT_BIAS = 6176; /** * Create a string representation of the raw Decimal128 value * * @method * @return {string} returns a Decimal128 string representation. */ Decimal128.prototype.toString = function() { // Note: bits in this routine are referred to starting at 0, // from the sign bit, towards the coefficient. // bits 0 - 31 var high; // bits 32 - 63 var midh; // bits 64 - 95 var midl; // bits 96 - 127 var low; // bits 1 - 5 var combination; // decoded biased exponent (14 bits) var biased_exponent; // the number of significand digits var significand_digits = 0; // the base-10 digits in the significand var significand = new Array(36); for (var i = 0; i < significand.length; i++) significand[i] = 0; // read pointer into significand var index = 0; // unbiased exponent var exponent; // the exponent if scientific notation is used var scientific_exponent; // true if the number is zero var is_zero = false; // the most signifcant significand bits (50-46) var significand_msb; // temporary storage for significand decoding var significand128 = { parts: new Array(4) }; // indexing variables i; var j, k; // Output string var string = []; // Unpack index index = 0; // Buffer reference var buffer = this.bytes; // Unpack the low 64bits into a long low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Unpack the high 64bits into a long midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Unpack index index = 0; // Create the state of the decimal var dec = { low: new Long(low, midl), high: new Long(midh, high) }; if (dec.high.lessThan(Long.ZERO)) { string.push('-'); } // Decode combination field and exponent combination = (high >> 26) & COMBINATION_MASK; if (combination >> 3 === 3) { // Check for 'special' values if (combination === COMBINATION_INFINITY) { return string.join('') + 'Infinity'; } else if (combination === COMBINATION_NAN) { return 'NaN'; } else { biased_exponent = (high >> 15) & EXPONENT_MASK; significand_msb = 0x08 + ((high >> 14) & 0x01); } } else { significand_msb = (high >> 14) & 0x07; biased_exponent = (high >> 17) & EXPONENT_MASK; } exponent = biased_exponent - EXPONENT_BIAS; // Create string of significand digits // Convert the 114-bit binary number represented by // (significand_high, significand_low) to at most 34 decimal // digits through modulo and division. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); significand128.parts[1] = midh; significand128.parts[2] = midl; significand128.parts[3] = low; if ( significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0 ) { is_zero = true; } else { for (k = 3; k >= 0; k--) { var least_digits = 0; // Peform the divide var result = divideu128(significand128); significand128 = result.quotient; least_digits = result.rem.low_; // We now have the 9 least significant digits (in base 2). // Convert and output to string. if (!least_digits) continue; for (j = 8; j >= 0; j--) { // significand[k * 9 + j] = Math.round(least_digits % 10); significand[k * 9 + j] = least_digits % 10; // least_digits = Math.round(least_digits / 10); least_digits = Math.floor(least_digits / 10); } } } // Output format options: // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd // Regular - ddd.ddd if (is_zero) { significand_digits = 1; significand[index] = 0; } else { significand_digits = 36; i = 0; while (!significand[index]) { i++; significand_digits = significand_digits - 1; index = index + 1; } } scientific_exponent = significand_digits - 1 + exponent; // The scientific exponent checks are dictated by the string conversion // specification and are somewhat arbitrary cutoffs. // // We must check exponent > 0, because if this is the case, the number // has trailing zeros. However, we *cannot* output these trailing zeros, // because doing so would change the precision of the value, and would // change stored data if the string converted number is round tripped. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { // Scientific format string.push(significand[index++]); significand_digits = significand_digits - 1; if (significand_digits) { string.push('.'); } for (i = 0; i < significand_digits; i++) { string.push(significand[index++]); } // Exponent string.push('E'); if (scientific_exponent > 0) { string.push('+' + scientific_exponent); } else { string.push(scientific_exponent); } } else { // Regular format with no decimal place if (exponent >= 0) { for (i = 0; i < significand_digits; i++) { string.push(significand[index++]); } } else { var radix_position = significand_digits + exponent; // non-zero digits before radix if (radix_position > 0) { for (i = 0; i < radix_position; i++) { string.push(significand[index++]); } } else { string.push('0'); } string.push('.'); // add leading zeros after radix while (radix_position++ < 0) { string.push('0'); } for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { string.push(significand[index++]); } } } return string.join(''); }; Decimal128.prototype.toJSON = function() { return { $numberDecimal: this.toString() }; }; module.exports = Decimal128; module.exports.Decimal128 = Decimal128; },{"./long":103,"./parser/utils":111}],100:[function(require,module,exports){ /** * A class representation of the BSON Double type. * * @class * @param {number} value the number we want to represent as a double. * @return {Double} */ function Double(value) { if (!(this instanceof Double)) return new Double(value); this._bsontype = 'Double'; this.value = value; } /** * Access the number value. * * @method * @return {number} returns the wrapped double number. */ Double.prototype.valueOf = function() { return this.value; }; /** * @ignore */ Double.prototype.toJSON = function() { return this.value; }; module.exports = Double; module.exports.Double = Double; },{}],101:[function(require,module,exports){ // Copyright (c) 2008, Fair Oaks Labs, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // // Modifications to writeIEEE754 to support negative zeroes made by Brian White var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { var e, m, bBE = endian === 'big', eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = bBE ? 0 : nBytes - 1, d = bBE ? 1 : -1, s = buffer[offset + i]; i += d; e = s & ((1 << -nBits) - 1); s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << -nBits) - 1); e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { var e, m, c, bBE = endian === 'big', eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, i = bBE ? nBytes - 1 : 0, d = bBE ? -1 : 1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; exports.readIEEE754 = readIEEE754; exports.writeIEEE754 = writeIEEE754; },{}],102:[function(require,module,exports){ /** * A class representation of a BSON Int32 type. * * @class * @param {number} value the number we want to represent as an int32. * @return {Int32} */ var Int32 = function(value) { if (!(this instanceof Int32)) return new Int32(value); this._bsontype = 'Int32'; this.value = value; }; /** * Access the number value. * * @method * @return {number} returns the wrapped int32 number. */ Int32.prototype.valueOf = function() { return this.value; }; /** * @ignore */ Int32.prototype.toJSON = function() { return this.value; }; module.exports = Int32; module.exports.Int32 = Int32; },{}],103:[function(require,module,exports){ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Copyright 2009 Google Inc. All Rights Reserved /** * Defines a Long class for representing a 64-bit two's-complement * integer value, which faithfully simulates the behavior of a Java "Long". This * implementation is derived from LongLib in GWT. * * Constructs a 64-bit two's-complement integer, given its low and high 32-bit * values as *signed* integers. See the from* functions below for more * convenient ways of constructing Longs. * * The internal representation of a Long is the two given signed, 32-bit values. * We use 32-bit pieces because these are the size of integers on which * Javascript performs bit-operations. For operations like addition and * multiplication, we split each number into 16-bit pieces, which can easily be * multiplied within Javascript's floating-point representation without overflow * or change in sign. * * In the algorithms below, we frequently reduce the negative case to the * positive case by negating the input(s) and then post-processing the result. * Note that we must ALWAYS check specially whether those values are MIN_VALUE * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as * a positive number, it overflows back into a negative). Not handling this * case would often result in infinite recursion. * * @class * @param {number} low the low (signed) 32 bits of the Long. * @param {number} high the high (signed) 32 bits of the Long. * @return {Long} */ function Long(low, high) { if (!(this instanceof Long)) return new Long(low, high); this._bsontype = 'Long'; /** * @type {number} * @ignore */ this.low_ = low | 0; // force into 32 signed bits. /** * @type {number} * @ignore */ this.high_ = high | 0; // force into 32 signed bits. } /** * Return the int value. * * @method * @return {number} the value, assuming it is a 32-bit integer. */ Long.prototype.toInt = function() { return this.low_; }; /** * Return the Number value. * * @method * @return {number} the closest floating-point representation to this value. */ Long.prototype.toNumber = function() { return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); }; /** * Return the JSON value. * * @method * @return {string} the JSON representation. */ Long.prototype.toJSON = function() { return this.toString(); }; /** * Return the String value. * * @method * @param {number} [opt_radix] the radix in which the text should be written. * @return {string} the textual representation of this value. */ Long.prototype.toString = function(opt_radix) { var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (this.isZero()) { return '0'; } if (this.isNegative()) { if (this.equals(Long.MIN_VALUE)) { // We need to change the Long value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. var radixLong = Long.fromNumber(radix); var div = this.div(radixLong); var rem = div.multiply(radixLong).subtract(this); return div.toString(radix) + rem.toInt().toString(radix); } else { return '-' + this.negate().toString(radix); } } // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Long.fromNumber(Math.pow(radix, 6)); rem = this; var result = ''; while (!rem.isZero()) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) { return digits + result; } else { while (digits.length < 6) { digits = '0' + digits; } result = '' + digits + result; } } }; /** * Return the high 32-bits value. * * @method * @return {number} the high 32-bits as a signed value. */ Long.prototype.getHighBits = function() { return this.high_; }; /** * Return the low 32-bits value. * * @method * @return {number} the low 32-bits as a signed value. */ Long.prototype.getLowBits = function() { return this.low_; }; /** * Return the low unsigned 32-bits value. * * @method * @return {number} the low 32-bits as an unsigned value. */ Long.prototype.getLowBitsUnsigned = function() { return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; }; /** * Returns the number of bits needed to represent the absolute value of this Long. * * @method * @return {number} Returns the number of bits needed to represent the absolute value of this Long. */ Long.prototype.getNumBitsAbs = function() { if (this.isNegative()) { if (this.equals(Long.MIN_VALUE)) { return 64; } else { return this.negate().getNumBitsAbs(); } } else { var val = this.high_ !== 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { if ((val & (1 << bit)) !== 0) { break; } } return this.high_ !== 0 ? bit + 33 : bit + 1; } }; /** * Return whether this value is zero. * * @method * @return {boolean} whether this value is zero. */ Long.prototype.isZero = function() { return this.high_ === 0 && this.low_ === 0; }; /** * Return whether this value is negative. * * @method * @return {boolean} whether this value is negative. */ Long.prototype.isNegative = function() { return this.high_ < 0; }; /** * Return whether this value is odd. * * @method * @return {boolean} whether this value is odd. */ Long.prototype.isOdd = function() { return (this.low_ & 1) === 1; }; /** * Return whether this Long equals the other * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long equals the other */ Long.prototype.equals = function(other) { return this.high_ === other.high_ && this.low_ === other.low_; }; /** * Return whether this Long does not equal the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long does not equal the other. */ Long.prototype.notEquals = function(other) { return this.high_ !== other.high_ || this.low_ !== other.low_; }; /** * Return whether this Long is less than the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is less than the other. */ Long.prototype.lessThan = function(other) { return this.compare(other) < 0; }; /** * Return whether this Long is less than or equal to the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is less than or equal to the other. */ Long.prototype.lessThanOrEqual = function(other) { return this.compare(other) <= 0; }; /** * Return whether this Long is greater than the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is greater than the other. */ Long.prototype.greaterThan = function(other) { return this.compare(other) > 0; }; /** * Return whether this Long is greater than or equal to the other. * * @method * @param {Long} other Long to compare against. * @return {boolean} whether this Long is greater than or equal to the other. */ Long.prototype.greaterThanOrEqual = function(other) { return this.compare(other) >= 0; }; /** * Compares this Long with the given one. * * @method * @param {Long} other Long to compare against. * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. */ Long.prototype.compare = function(other) { if (this.equals(other)) { return 0; } var thisNeg = this.isNegative(); var otherNeg = other.isNegative(); if (thisNeg && !otherNeg) { return -1; } if (!thisNeg && otherNeg) { return 1; } // at this point, the signs are the same, so subtraction will not overflow if (this.subtract(other).isNegative()) { return -1; } else { return 1; } }; /** * The negation of this value. * * @method * @return {Long} the negation of this value. */ Long.prototype.negate = function() { if (this.equals(Long.MIN_VALUE)) { return Long.MIN_VALUE; } else { return this.not().add(Long.ONE); } }; /** * Returns the sum of this and the given Long. * * @method * @param {Long} other Long to add to this one. * @return {Long} the sum of this and the given Long. */ Long.prototype.add = function(other) { // Divide each number into 4 chunks of 16 bits, and then sum the chunks. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 + b48; c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns the difference of this and the given Long. * * @method * @param {Long} other Long to subtract from this. * @return {Long} the difference of this and the given Long. */ Long.prototype.subtract = function(other) { return this.add(other.negate()); }; /** * Returns the product of this and the given Long. * * @method * @param {Long} other Long to multiply with this. * @return {Long} the product of this and the other. */ Long.prototype.multiply = function(other) { if (this.isZero()) { return Long.ZERO; } else if (other.isZero()) { return Long.ZERO; } if (this.equals(Long.MIN_VALUE)) { return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; } else if (other.equals(Long.MIN_VALUE)) { return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { return this.negate() .multiply(other) .negate(); } } else if (other.isNegative()) { return this.multiply(other.negate()).negate(); } // If both Longs are small, use float multiplication if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { return Long.fromNumber(this.toNumber() * other.toNumber()); } // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. // We can skip products that would overflow. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns this Long divided by the given one. * * @method * @param {Long} other Long by which to divide. * @return {Long} this Long divided by the given one. */ Long.prototype.div = function(other) { if (other.isZero()) { throw Error('division by zero'); } else if (this.isZero()) { return Long.ZERO; } if (this.equals(Long.MIN_VALUE)) { if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE } else if (other.equals(Long.MIN_VALUE)) { return Long.ONE; } else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. var halfThis = this.shiftRight(1); var approx = halfThis.div(other).shiftLeft(1); if (approx.equals(Long.ZERO)) { return other.isNegative() ? Long.ONE : Long.NEG_ONE; } else { var rem = this.subtract(other.multiply(approx)); var result = approx.add(rem.div(other)); return result; } } } else if (other.equals(Long.MIN_VALUE)) { return Long.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { return this.negate() .div(other) .negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); } // Repeat the following until the remainder is less than other: find a // floating-point that approximates remainder / other *from below*, add this // into the result, and subtract it from the remainder. It is critical that // the approximate value is less than or equal to the real value so that the // remainder never becomes negative. var res = Long.ZERO; rem = this; while (rem.greaterThanOrEqual(other)) { // Approximate the result of division. This may be a little greater or // smaller than the actual value. approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or // the smallest non-fractional digit, whichever is larger. var log2 = Math.ceil(Math.log(approx) / Math.LN2); var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. var approxRes = Long.fromNumber(approx); var approxRem = approxRes.multiply(other); while (approxRem.isNegative() || approxRem.greaterThan(rem)) { approx -= delta; approxRes = Long.fromNumber(approx); approxRem = approxRes.multiply(other); } // We know the answer can't be zero... and actually, zero would cause // infinite recursion since we would make no progress. if (approxRes.isZero()) { approxRes = Long.ONE; } res = res.add(approxRes); rem = rem.subtract(approxRem); } return res; }; /** * Returns this Long modulo the given one. * * @method * @param {Long} other Long by which to mod. * @return {Long} this Long modulo the given one. */ Long.prototype.modulo = function(other) { return this.subtract(this.div(other).multiply(other)); }; /** * The bitwise-NOT of this value. * * @method * @return {Long} the bitwise-NOT of this value. */ Long.prototype.not = function() { return Long.fromBits(~this.low_, ~this.high_); }; /** * Returns the bitwise-AND of this Long and the given one. * * @method * @param {Long} other the Long with which to AND. * @return {Long} the bitwise-AND of this and the other. */ Long.prototype.and = function(other) { return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); }; /** * Returns the bitwise-OR of this Long and the given one. * * @method * @param {Long} other the Long with which to OR. * @return {Long} the bitwise-OR of this and the other. */ Long.prototype.or = function(other) { return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); }; /** * Returns the bitwise-XOR of this Long and the given one. * * @method * @param {Long} other the Long with which to XOR. * @return {Long} the bitwise-XOR of this and the other. */ Long.prototype.xor = function(other) { return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); }; /** * Returns this Long with bits shifted to the left by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Long} this shifted to the left by the given amount. */ Long.prototype.shiftLeft = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var low = this.low_; if (numBits < 32) { var high = this.high_; return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return Long.fromBits(0, low << (numBits - 32)); } } }; /** * Returns this Long with bits shifted to the right by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Long} this shifted to the right by the given amount. */ Long.prototype.shiftRight = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); } } }; /** * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. */ Long.prototype.shiftRightUnsigned = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); } else if (numBits === 32) { return Long.fromBits(high, 0); } else { return Long.fromBits(high >>> (numBits - 32), 0); } } }; /** * Returns a Long representing the given (32-bit) integer value. * * @method * @param {number} value the 32-bit integer in question. * @return {Long} the corresponding Long value. */ Long.fromInt = function(value) { if (-128 <= value && value < 128) { var cachedObj = Long.INT_CACHE_[value]; if (cachedObj) { return cachedObj; } } var obj = new Long(value | 0, value < 0 ? -1 : 0); if (-128 <= value && value < 128) { Long.INT_CACHE_[value] = obj; } return obj; }; /** * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * * @method * @param {number} value the number in question. * @return {Long} the corresponding Long value. */ Long.fromNumber = function(value) { if (isNaN(value) || !isFinite(value)) { return Long.ZERO; } else if (value <= -Long.TWO_PWR_63_DBL_) { return Long.MIN_VALUE; } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { return Long.MAX_VALUE; } else if (value < 0) { return Long.fromNumber(-value).negate(); } else { return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); } }; /** * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. * * @method * @param {number} lowBits the low 32-bits. * @param {number} highBits the high 32-bits. * @return {Long} the corresponding Long value. */ Long.fromBits = function(lowBits, highBits) { return new Long(lowBits, highBits); }; /** * Returns a Long representation of the given string, written using the given radix. * * @method * @param {string} str the textual representation of the Long. * @param {number} opt_radix the radix in which the text is written. * @return {Long} the corresponding Long value. */ Long.fromString = function(str, opt_radix) { if (str.length === 0) { throw Error('number format error: empty string'); } var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (str.charAt(0) === '-') { return Long.fromString(str.substring(1), radix).negate(); } else if (str.indexOf('-') >= 0) { throw Error('number format error: interior "-" character: ' + str); } // Do several (8) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Long.fromNumber(Math.pow(radix, 8)); var result = Long.ZERO; for (var i = 0; i < str.length; i += 8) { var size = Math.min(8, str.length - i); var value = parseInt(str.substring(i, i + size), radix); if (size < 8) { var power = Long.fromNumber(Math.pow(radix, size)); result = result.multiply(power).add(Long.fromNumber(value)); } else { result = result.multiply(radixToPower); result = result.add(Long.fromNumber(value)); } } return result; }; // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the // from* methods on which they depend. /** * A cache of the Long representations of small integer values. * @type {Object} * @ignore */ Long.INT_CACHE_ = {}; // NOTE: the compiler should inline these constant values below and then remove // these variables, so there should be no runtime penalty for these. /** * Number used repeated below in calculations. This must appear before the * first call to any from* function below. * @type {number} * @ignore */ Long.TWO_PWR_16_DBL_ = 1 << 16; /** * @type {number} * @ignore */ Long.TWO_PWR_24_DBL_ = 1 << 24; /** * @type {number} * @ignore */ Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; /** * @type {number} * @ignore */ Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; /** * @type {number} * @ignore */ Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; /** @type {Long} */ Long.ZERO = Long.fromInt(0); /** @type {Long} */ Long.ONE = Long.fromInt(1); /** @type {Long} */ Long.NEG_ONE = Long.fromInt(-1); /** @type {Long} */ Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); /** @type {Long} */ Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); /** * @type {Long} * @ignore */ Long.TWO_PWR_24_ = Long.fromInt(1 << 24); /** * Expose. */ module.exports = Long; module.exports.Long = Long; },{}],104:[function(require,module,exports){ (function (global){ 'use strict'; // We have an ES6 Map available, return the native instance if (typeof global.Map !== 'undefined') { module.exports = global.Map; module.exports.Map = global.Map; } else { // We will return a polyfill var Map = function(array) { this._keys = []; this._values = {}; for (var i = 0; i < array.length; i++) { if (array[i] == null) continue; // skip null and undefined var entry = array[i]; var key = entry[0]; var value = entry[1]; // Add the key to the list of keys in order this._keys.push(key); // Add the key and value to the values dictionary with a point // to the location in the ordered keys list this._values[key] = { v: value, i: this._keys.length - 1 }; } }; Map.prototype.clear = function() { this._keys = []; this._values = {}; }; Map.prototype.delete = function(key) { var value = this._values[key]; if (value == null) return false; // Delete entry delete this._values[key]; // Remove the key from the ordered keys list this._keys.splice(value.i, 1); return true; }; Map.prototype.entries = function() { var self = this; var index = 0; return { next: function() { var key = self._keys[index++]; return { value: key !== undefined ? [key, self._values[key].v] : undefined, done: key !== undefined ? false : true }; } }; }; Map.prototype.forEach = function(callback, self) { self = self || this; for (var i = 0; i < this._keys.length; i++) { var key = this._keys[i]; // Call the forEach callback callback.call(self, this._values[key].v, key, self); } }; Map.prototype.get = function(key) { return this._values[key] ? this._values[key].v : undefined; }; Map.prototype.has = function(key) { return this._values[key] != null; }; Map.prototype.keys = function() { var self = this; var index = 0; return { next: function() { var key = self._keys[index++]; return { value: key !== undefined ? key : undefined, done: key !== undefined ? false : true }; } }; }; Map.prototype.set = function(key, value) { if (this._values[key]) { this._values[key].v = value; return this; } // Add the key to the list of keys in order this._keys.push(key); // Add the key and value to the values dictionary with a point // to the location in the ordered keys list this._values[key] = { v: value, i: this._keys.length - 1 }; return this; }; Map.prototype.values = function() { var self = this; var index = 0; return { next: function() { var key = self._keys[index++]; return { value: key !== undefined ? self._values[key].v : undefined, done: key !== undefined ? false : true }; } }; }; // Last ismaster Object.defineProperty(Map.prototype, 'size', { enumerable: true, get: function() { return this._keys.length; } }); module.exports = Map; module.exports.Map = Map; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],105:[function(require,module,exports){ /** * A class representation of the BSON MaxKey type. * * @class * @return {MaxKey} A MaxKey instance */ function MaxKey() { if (!(this instanceof MaxKey)) return new MaxKey(); this._bsontype = 'MaxKey'; } module.exports = MaxKey; module.exports.MaxKey = MaxKey; },{}],106:[function(require,module,exports){ /** * A class representation of the BSON MinKey type. * * @class * @return {MinKey} A MinKey instance */ function MinKey() { if (!(this instanceof MinKey)) return new MinKey(); this._bsontype = 'MinKey'; } module.exports = MinKey; module.exports.MinKey = MinKey; },{}],107:[function(require,module,exports){ (function (process,Buffer){ // Custom inspect property name / symbol. var inspect = 'inspect'; var utils = require('./parser/utils'); /** * Machine id. * * Create a random 3-byte value (i.e. unique for this * process). Other drivers use a md5 of the machine id here, but * that would mean an asyc call to gethostname, so we don't bother. * @ignore */ var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); // Regular expression that checks for hex value var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); // Check if buffer exists try { if (Buffer && Buffer.from) { var hasBufferType = true; inspect = require('util').inspect.custom || 'inspect'; } } catch (err) { hasBufferType = false; } /** * Create a new ObjectID instance * * @class * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. * @property {number} generationTime The generation time of this ObjectId instance * @return {ObjectID} instance of ObjectID. */ var ObjectID = function ObjectID(id) { // Duck-typing to support ObjectId from different npm packages if (id instanceof ObjectID) return id; if (!(this instanceof ObjectID)) return new ObjectID(id); this._bsontype = 'ObjectID'; // The most common usecase (blank id, new objectId instance) if (id == null || typeof id === 'number') { // Generate a new id this.id = this.generate(id); // If we are caching the hex string if (ObjectID.cacheHexString) this.__id = this.toString('hex'); // Return the object return; } // Check if the passed in id is valid var valid = ObjectID.isValid(id); // Throw an error if it's not a valid setup if (!valid && id != null) { throw new Error( 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' ); } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { return new ObjectID(utils.toBuffer(id, 'hex')); } else if (valid && typeof id === 'string' && id.length === 24) { return ObjectID.createFromHexString(id); } else if (id != null && id.length === 12) { // assume 12 byte string this.id = id; } else if (id != null && id.toHexString) { // Duck-typing to support ObjectId from different npm packages return id; } else { throw new Error( 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' ); } if (ObjectID.cacheHexString) this.__id = this.toString('hex'); }; // Allow usage of ObjectId as well as ObjectID // var ObjectId = ObjectID; // Precomputed hex table enables speedy hex string conversion var hexTable = []; for (var i = 0; i < 256; i++) { hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); } /** * Return the ObjectID id as a 24 byte hex string representation * * @method * @return {string} return the 24 byte hex string representation. */ ObjectID.prototype.toHexString = function() { if (ObjectID.cacheHexString && this.__id) return this.__id; var hexString = ''; if (!this.id || !this.id.length) { throw new Error( 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']' ); } if (this.id instanceof _Buffer) { hexString = convertToHex(this.id); if (ObjectID.cacheHexString) this.__id = hexString; return hexString; } for (var i = 0; i < this.id.length; i++) { hexString += hexTable[this.id.charCodeAt(i)]; } if (ObjectID.cacheHexString) this.__id = hexString; return hexString; }; /** * Update the ObjectID index used in generating new ObjectID's on the driver * * @method * @return {number} returns next index value. * @ignore */ ObjectID.prototype.get_inc = function() { return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); }; /** * Update the ObjectID index used in generating new ObjectID's on the driver * * @method * @return {number} returns next index value. * @ignore */ ObjectID.prototype.getInc = function() { return this.get_inc(); }; /** * Generate a 12 byte id buffer used in ObjectID's * * @method * @param {number} [time] optional parameter allowing to pass in a second based timestamp. * @return {Buffer} return the 12 byte id buffer string. */ ObjectID.prototype.generate = function(time) { if ('number' !== typeof time) { time = ~~(Date.now() / 1000); } // Use pid var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; var inc = this.get_inc(); // Buffer used var buffer = utils.allocBuffer(12); // Encode time buffer[3] = time & 0xff; buffer[2] = (time >> 8) & 0xff; buffer[1] = (time >> 16) & 0xff; buffer[0] = (time >> 24) & 0xff; // Encode machine buffer[6] = MACHINE_ID & 0xff; buffer[5] = (MACHINE_ID >> 8) & 0xff; buffer[4] = (MACHINE_ID >> 16) & 0xff; // Encode pid buffer[8] = pid & 0xff; buffer[7] = (pid >> 8) & 0xff; // Encode index buffer[11] = inc & 0xff; buffer[10] = (inc >> 8) & 0xff; buffer[9] = (inc >> 16) & 0xff; // Return the buffer return buffer; }; /** * Converts the id into a 24 byte hex string for printing * * @param {String} format The Buffer toString format parameter. * @return {String} return the 24 byte hex string representation. * @ignore */ ObjectID.prototype.toString = function(format) { // Is the id a buffer then use the buffer toString method to return the format if (this.id && this.id.copy) { return this.id.toString(typeof format === 'string' ? format : 'hex'); } // if(this.buffer ) return this.toHexString(); }; /** * Converts to a string representation of this Id. * * @return {String} return the 24 byte hex string representation. * @ignore */ ObjectID.prototype[inspect] = ObjectID.prototype.toString; /** * Converts to its JSON representation. * * @return {String} return the 24 byte hex string representation. * @ignore */ ObjectID.prototype.toJSON = function() { return this.toHexString(); }; /** * Compares the equality of this ObjectID with `otherID`. * * @method * @param {object} otherID ObjectID instance to compare against. * @return {boolean} the result of comparing two ObjectID's */ ObjectID.prototype.equals = function equals(otherId) { // var id; if (otherId instanceof ObjectID) { return this.toString() === otherId.toString(); } else if ( typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer ) { return otherId === this.id.toString('binary'); } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { return otherId.toLowerCase() === this.toHexString(); } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { return otherId === this.id; } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { return otherId.toHexString() === this.toHexString(); } else { return false; } }; /** * Returns the generation date (accurate up to the second) that this ID was generated. * * @method * @return {date} the generation date */ ObjectID.prototype.getTimestamp = function() { var timestamp = new Date(); var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); timestamp.setTime(Math.floor(time) * 1000); return timestamp; }; /** * @ignore */ ObjectID.index = ~~(Math.random() * 0xffffff); /** * @ignore */ ObjectID.createPk = function createPk() { return new ObjectID(); }; /** * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. * * @method * @param {number} time an integer number representing a number of seconds. * @return {ObjectID} return the created ObjectID */ ObjectID.createFromTime = function createFromTime(time) { var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // Encode time into first 4 bytes buffer[3] = time & 0xff; buffer[2] = (time >> 8) & 0xff; buffer[1] = (time >> 16) & 0xff; buffer[0] = (time >> 24) & 0xff; // Return the new objectId return new ObjectID(buffer); }; // Lookup tables //var encodeLookup = '0123456789abcdef'.split(''); var decodeLookup = []; i = 0; while (i < 10) decodeLookup[0x30 + i] = i++; while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; var _Buffer = Buffer; var convertToHex = function(bytes) { return bytes.toString('hex'); }; /** * Creates an ObjectID from a hex string representation of an ObjectID. * * @method * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. * @return {ObjectID} return the created ObjectID */ ObjectID.createFromHexString = function createFromHexString(string) { // Throw an error if it's not a valid setup if (typeof string === 'undefined' || (string != null && string.length !== 24)) { throw new Error( 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' ); } // Use Buffer.from method if available if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); // Calculate lengths var array = new _Buffer(12); var n = 0; var i = 0; while (i < 24) { array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; } return new ObjectID(array); }; /** * Checks if a value is a valid bson ObjectId * * @method * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. */ ObjectID.isValid = function isValid(id) { if (id == null) return false; if (typeof id === 'number') { return true; } if (typeof id === 'string') { return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); } if (id instanceof ObjectID) { return true; } if (id instanceof _Buffer) { return true; } // Duck-Typing detection of ObjectId like objects if (id.toHexString) { return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); } return false; }; /** * @ignore */ Object.defineProperty(ObjectID.prototype, 'generationTime', { enumerable: true, get: function() { return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); }, set: function(value) { // Encode time into first 4 bytes this.id[3] = value & 0xff; this.id[2] = (value >> 8) & 0xff; this.id[1] = (value >> 16) & 0xff; this.id[0] = (value >> 24) & 0xff; } }); /** * Expose. */ module.exports = ObjectID; module.exports.ObjectID = ObjectID; module.exports.ObjectId = ObjectID; }).call(this,require('_process'),require("buffer").Buffer) },{"./parser/utils":111,"_process":399,"buffer":115,"util":414}],108:[function(require,module,exports){ (function (Buffer){ 'use strict'; var Long = require('../long').Long, Double = require('../double').Double, Timestamp = require('../timestamp').Timestamp, ObjectID = require('../objectid').ObjectID, Symbol = require('../symbol').Symbol, BSONRegExp = require('../regexp').BSONRegExp, Code = require('../code').Code, Decimal128 = require('../decimal128'), MinKey = require('../min_key').MinKey, MaxKey = require('../max_key').MaxKey, DBRef = require('../db_ref').DBRef, Binary = require('../binary').Binary; var normalizedFunctionString = require('./utils').normalizedFunctionString; // To ensure that 0.4 of node works correctly var isDate = function isDate(d) { return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; }; var calculateObjectSize = function calculateObjectSize( object, serializeFunctions, ignoreUndefined ) { var totalLength = 4 + 1; if (Array.isArray(object)) { for (var i = 0; i < object.length; i++) { totalLength += calculateElement( i.toString(), object[i], serializeFunctions, true, ignoreUndefined ); } } else { // If we have toBSON defined, override the current object if (object.toBSON) { object = object.toBSON(); } // Calculate size for (var key in object) { totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); } } return totalLength; }; /** * @ignore * @api private */ function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { // If we have toBSON defined, override the current object if (value && value.toBSON) { value = value.toBSON(); } switch (typeof value) { case 'string': return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; case 'number': if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); } else { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } } else { // 64 bit return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } case 'undefined': if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; return 0; case 'boolean': return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); case 'object': if ( value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey' ) { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); } else if (value instanceof Date || isDate(value)) { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length ); } else if ( value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp' ) { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); } else if (value instanceof Code || value['_bsontype'] === 'Code') { // Calculate size depending on the availability of a scope if (value.scope != null && Object.keys(value.scope).length > 0) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) ); } else { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 ); } } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { // Check what kind of subtype we have if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4) ); } else { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) ); } } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1 ); } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { // Set up correct object for serialization var ordered_values = { $ref: value.namespace, $id: value.oid }; // Add db reference if it exists if (null != value.db) { ordered_values['$db'] = value.db; } return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) ); } else if ( value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' ) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 ); } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1 ); } else { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1 ); } case 'function': // WTF for 0.4.X where typeof /someregexp/ === 'function' if ( value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]' ) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 ); } else { if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) ); } else if (serializeFunctions) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 ); } } } return 0; } var BSON = {}; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. module.exports = calculateObjectSize; }).call(this,require("buffer").Buffer) },{"../binary":95,"../code":97,"../db_ref":98,"../decimal128":99,"../double":100,"../long":103,"../max_key":105,"../min_key":106,"../objectid":107,"../regexp":112,"../symbol":113,"../timestamp":114,"./utils":111,"buffer":115}],109:[function(require,module,exports){ 'use strict'; var Long = require('../long').Long, Double = require('../double').Double, Timestamp = require('../timestamp').Timestamp, ObjectID = require('../objectid').ObjectID, Symbol = require('../symbol').Symbol, Code = require('../code').Code, MinKey = require('../min_key').MinKey, MaxKey = require('../max_key').MaxKey, Decimal128 = require('../decimal128'), Int32 = require('../int_32'), DBRef = require('../db_ref').DBRef, BSONRegExp = require('../regexp').BSONRegExp, Binary = require('../binary').Binary; var utils = require('./utils'); var deserialize = function(buffer, options, isArray) { options = options == null ? {} : options; var index = options && options.index ? options.index : 0; // Read the document size var size = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); // Ensure buffer is valid size if (size < 5 || buffer.length < size || size + index > buffer.length) { throw new Error('corrupt bson message'); } // Illegal end value if (buffer[index + size - 1] !== 0) { throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); } // Start deserializtion return deserializeObject(buffer, index, options, isArray); }; var deserializeObject = function(buffer, index, options, isArray) { var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; if (!cacheFunctionsCrc32) var crc32 = null; var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; // Return raw bson buffer instead of parsing it var raw = options['raw'] == null ? false : options['raw']; // Return BSONRegExp objects instead of native regular expressions var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; // Controls the promotion of values vs wrapper classes var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; // Set the start index var startIndex = index; // Validate that we have at least 4 bytes of buffer if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); // Read the document size var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Ensure buffer is valid size if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); // Create holding object var object = isArray ? [] : {}; // Used for arrays to skip having to perform utf8 decoding var arrayIndex = 0; var done = false; // While we have more left data left keep parsing // while (buffer[index + 1] !== 0) { while (!done) { // Read the type var elementType = buffer[index++]; // If we get a zero it's the last byte, exit if (elementType === 0) break; // Get the start search index var i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); index = i + 1; if (elementType === BSON.BSON_DATA_STRING) { var stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); object[name] = buffer.toString('utf8', index, index + stringSize - 1); index = index + stringSize; } else if (elementType === BSON.BSON_DATA_OID) { var oid = utils.allocBuffer(12); buffer.copy(oid, 0, index, index + 12); object[name] = new ObjectID(oid); index = index + 12; } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { object[name] = new Int32( buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) ); } else if (elementType === BSON.BSON_DATA_INT) { object[name] = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { object[name] = new Double(buffer.readDoubleLE(index)); index = index + 8; } else if (elementType === BSON.BSON_DATA_NUMBER) { object[name] = buffer.readDoubleLE(index); index = index + 8; } else if (elementType === BSON.BSON_DATA_DATE) { var lowBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); var highBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); object[name] = new Date(new Long(lowBits, highBits).toNumber()); } else if (elementType === BSON.BSON_DATA_BOOLEAN) { if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); object[name] = buffer[index++] === 1; } else if (elementType === BSON.BSON_DATA_OBJECT) { var _index = index; var objectSize = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); // We have a raw value if (raw) { object[name] = buffer.slice(index, index + objectSize); } else { object[name] = deserializeObject(buffer, _index, options, false); } index = index + objectSize; } else if (elementType === BSON.BSON_DATA_ARRAY) { _index = index; objectSize = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); var arrayOptions = options; // Stop index var stopIndex = index + objectSize; // All elements of array to be returned as raw bson if (fieldsAsRaw && fieldsAsRaw[name]) { arrayOptions = {}; for (var n in options) arrayOptions[n] = options[n]; arrayOptions['raw'] = true; } object[name] = deserializeObject(buffer, _index, arrayOptions, true); index = index + objectSize; if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); if (index !== stopIndex) throw new Error('corrupted array bson'); } else if (elementType === BSON.BSON_DATA_UNDEFINED) { object[name] = undefined; } else if (elementType === BSON.BSON_DATA_NULL) { object[name] = null; } else if (elementType === BSON.BSON_DATA_LONG) { // Unpack the low and high bits lowBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); highBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); var long = new Long(lowBits, highBits); // Promote the long if possible if (promoteLongs && promoteValues === true) { object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; } else { object[name] = long; } } else if (elementType === BSON.BSON_DATA_DECIMAL128) { // Buffer to contain the decimal bytes var bytes = utils.allocBuffer(16); // Copy the next 16 bytes into the bytes buffer buffer.copy(bytes, 0, index, index + 16); // Update index index = index + 16; // Assign the new Decimal128 value var decimal128 = new Decimal128(bytes); // If we have an alternative mapper use that object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; } else if (elementType === BSON.BSON_DATA_BINARY) { var binarySize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); var totalBinarySize = binarySize; var subType = buffer[index++]; // Did we have a negative binary size, throw if (binarySize < 0) throw new Error('Negative binary type element size found'); // Is the length longer than the document if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); // Decode as raw Buffer object if options specifies it if (buffer['slice'] != null) { // If we have subtype 2 skip the 4 bytes for the size if (subType === Binary.SUBTYPE_BYTE_ARRAY) { binarySize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); } if (promoteBuffers && promoteValues) { object[name] = buffer.slice(index, index + binarySize); } else { object[name] = new Binary(buffer.slice(index, index + binarySize), subType); } } else { var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); // If we have subtype 2 skip the 4 bytes for the size if (subType === Binary.SUBTYPE_BYTE_ARRAY) { binarySize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); } // Copy the data for (i = 0; i < binarySize; i++) { _buffer[i] = buffer[index + i]; } if (promoteBuffers && promoteValues) { object[name] = _buffer; } else { object[name] = new Binary(_buffer, subType); } } // Update the index index = index + binarySize; } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string var source = buffer.toString('utf8', index, i); // Create the regexp index = i + 1; // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string var regExpOptions = buffer.toString('utf8', index, i); index = i + 1; // For each option add the corresponding one for javascript var optionsArray = new Array(regExpOptions.length); // Parse options for (i = 0; i < regExpOptions.length; i++) { switch (regExpOptions[i]) { case 'm': optionsArray[i] = 'm'; break; case 's': optionsArray[i] = 'g'; break; case 'i': optionsArray[i] = 'i'; break; } } object[name] = new RegExp(source, optionsArray.join('')); } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string source = buffer.toString('utf8', index, i); index = i + 1; // Get the start search index i = index; // Locate the end of the c string while (buffer[i] !== 0x00 && i < buffer.length) { i++; } // If are at the end of the buffer there is a problem with the document if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string regExpOptions = buffer.toString('utf8', index, i); index = i + 1; // Set the object object[name] = new BSONRegExp(source, regExpOptions); } else if (elementType === BSON.BSON_DATA_SYMBOL) { stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); index = index + stringSize; } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { lowBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); highBits = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); object[name] = new Timestamp(lowBits, highBits); } else if (elementType === BSON.BSON_DATA_MIN_KEY) { object[name] = new MinKey(); } else if (elementType === BSON.BSON_DATA_MAX_KEY) { object[name] = new MaxKey(); } else if (elementType === BSON.BSON_DATA_CODE) { stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); var functionString = buffer.toString('utf8', index, index + stringSize - 1); // If we are evaluating the functions if (evalFunctions) { // If we have cache enabled let's look for the md5 of the function in the cache if (cacheFunctions) { var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); } else { object[name] = isolateEval(functionString); } } else { object[name] = new Code(functionString); } // Update parse index position index = index + stringSize; } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { var totalSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Element cannot be shorter than totalSize + stringSize + documentSize + terminator if (totalSize < 4 + 4 + 4 + 1) { throw new Error('code_w_scope total size shorter minimum expected length'); } // Get the code string size stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Check if we have a valid string if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); // Javascript function functionString = buffer.toString('utf8', index, index + stringSize - 1); // Update parse index position index = index + stringSize; // Parse the element _index = index; // Decode the size of the object document objectSize = buffer[index] | (buffer[index + 1] << 8) | (buffer[index + 2] << 16) | (buffer[index + 3] << 24); // Decode the scope object var scopeObject = deserializeObject(buffer, _index, options, false); // Adjust the index index = index + objectSize; // Check if field length is to short if (totalSize < 4 + 4 + objectSize + stringSize) { throw new Error('code_w_scope total size is to short, truncating scope'); } // Check if totalSize field is to long if (totalSize > 4 + 4 + objectSize + stringSize) { throw new Error('code_w_scope total size is to long, clips outer document'); } // If we are evaluating the functions if (evalFunctions) { // If we have cache enabled let's look for the md5 of the function in the cache if (cacheFunctions) { hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); } else { object[name] = isolateEval(functionString); } object[name].scope = scopeObject; } else { object[name] = new Code(functionString, scopeObject); } } else if (elementType === BSON.BSON_DATA_DBPOINTER) { // Get the code string size stringSize = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); // Check if we have a valid string if ( stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0 ) throw new Error('bad string length in bson'); // Namespace var namespace = buffer.toString('utf8', index, index + stringSize - 1); // Update parse index position index = index + stringSize; // Read the oid var oidBuffer = utils.allocBuffer(12); buffer.copy(oidBuffer, 0, index, index + 12); oid = new ObjectID(oidBuffer); // Update the index index = index + 12; // Split the namespace var parts = namespace.split('.'); var db = parts.shift(); var collection = parts.join('.'); // Upgrade to DBRef type object[name] = new DBRef(collection, oid, db); } else { throw new Error( 'Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser' ); } } // Check if the deserialization was against a valid array/object if (size !== index - startIndex) { if (isArray) throw new Error('corrupt array bson'); throw new Error('corrupt object bson'); } // Check if we have a db ref object if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); return object; }; /** * Ensure eval is isolated. * * @ignore * @api private */ var isolateEvalWithHash = function(functionCache, hash, functionString, object) { // Contains the value we are going to set var value = null; // Check for cache hit, eval if missing and return cached function if (functionCache[hash] == null) { eval('value = ' + functionString); functionCache[hash] = value; } // Set the object return functionCache[hash].bind(object); }; /** * Ensure eval is isolated. * * @ignore * @api private */ var isolateEval = function(functionString) { // Contains the value we are going to set var value = null; // Eval the function eval('value = ' + functionString); return value; }; var BSON = {}; /** * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 * * @ignore * @api private */ var functionCache = (BSON.functionCache = {}); /** * Number BSON Type * * @classconstant BSON_DATA_NUMBER **/ BSON.BSON_DATA_NUMBER = 1; /** * String BSON Type * * @classconstant BSON_DATA_STRING **/ BSON.BSON_DATA_STRING = 2; /** * Object BSON Type * * @classconstant BSON_DATA_OBJECT **/ BSON.BSON_DATA_OBJECT = 3; /** * Array BSON Type * * @classconstant BSON_DATA_ARRAY **/ BSON.BSON_DATA_ARRAY = 4; /** * Binary BSON Type * * @classconstant BSON_DATA_BINARY **/ BSON.BSON_DATA_BINARY = 5; /** * Binary BSON Type * * @classconstant BSON_DATA_UNDEFINED **/ BSON.BSON_DATA_UNDEFINED = 6; /** * ObjectID BSON Type * * @classconstant BSON_DATA_OID **/ BSON.BSON_DATA_OID = 7; /** * Boolean BSON Type * * @classconstant BSON_DATA_BOOLEAN **/ BSON.BSON_DATA_BOOLEAN = 8; /** * Date BSON Type * * @classconstant BSON_DATA_DATE **/ BSON.BSON_DATA_DATE = 9; /** * null BSON Type * * @classconstant BSON_DATA_NULL **/ BSON.BSON_DATA_NULL = 10; /** * RegExp BSON Type * * @classconstant BSON_DATA_REGEXP **/ BSON.BSON_DATA_REGEXP = 11; /** * Code BSON Type * * @classconstant BSON_DATA_DBPOINTER **/ BSON.BSON_DATA_DBPOINTER = 12; /** * Code BSON Type * * @classconstant BSON_DATA_CODE **/ BSON.BSON_DATA_CODE = 13; /** * Symbol BSON Type * * @classconstant BSON_DATA_SYMBOL **/ BSON.BSON_DATA_SYMBOL = 14; /** * Code with Scope BSON Type * * @classconstant BSON_DATA_CODE_W_SCOPE **/ BSON.BSON_DATA_CODE_W_SCOPE = 15; /** * 32 bit Integer BSON Type * * @classconstant BSON_DATA_INT **/ BSON.BSON_DATA_INT = 16; /** * Timestamp BSON Type * * @classconstant BSON_DATA_TIMESTAMP **/ BSON.BSON_DATA_TIMESTAMP = 17; /** * Long BSON Type * * @classconstant BSON_DATA_LONG **/ BSON.BSON_DATA_LONG = 18; /** * Long BSON Type * * @classconstant BSON_DATA_DECIMAL128 **/ BSON.BSON_DATA_DECIMAL128 = 19; /** * MinKey BSON Type * * @classconstant BSON_DATA_MIN_KEY **/ BSON.BSON_DATA_MIN_KEY = 0xff; /** * MaxKey BSON Type * * @classconstant BSON_DATA_MAX_KEY **/ BSON.BSON_DATA_MAX_KEY = 0x7f; /** * Binary Default Type * * @classconstant BSON_BINARY_SUBTYPE_DEFAULT **/ BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * Binary Function Type * * @classconstant BSON_BINARY_SUBTYPE_FUNCTION **/ BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; /** * Binary Byte Array Type * * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY **/ BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; /** * Binary UUID Type * * @classconstant BSON_BINARY_SUBTYPE_UUID **/ BSON.BSON_BINARY_SUBTYPE_UUID = 3; /** * Binary MD5 Type * * @classconstant BSON_BINARY_SUBTYPE_MD5 **/ BSON.BSON_BINARY_SUBTYPE_MD5 = 4; /** * Binary User Defined Type * * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED **/ BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; BSON.BSON_INT64_MIN = -Math.pow(2, 63); // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // Internal long versions var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. module.exports = deserialize; },{"../binary":95,"../code":97,"../db_ref":98,"../decimal128":99,"../double":100,"../int_32":102,"../long":103,"../max_key":105,"../min_key":106,"../objectid":107,"../regexp":112,"../symbol":113,"../timestamp":114,"./utils":111}],110:[function(require,module,exports){ (function (Buffer){ 'use strict'; var writeIEEE754 = require('../float_parser').writeIEEE754, Long = require('../long').Long, Map = require('../map'), Binary = require('../binary').Binary; var normalizedFunctionString = require('./utils').normalizedFunctionString; // try { // var _Buffer = Uint8Array; // } catch (e) { // _Buffer = Buffer; // } var regexp = /\x00/; // eslint-disable-line no-control-regex var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; // To ensure that 0.4 of node works correctly var isDate = function isDate(d) { return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; }; var isRegExp = function isRegExp(d) { return Object.prototype.toString.call(d) === '[object RegExp]'; }; var serializeString = function(buffer, key, value, index, isArray) { // Encode String type buffer[index++] = BSON.BSON_DATA_STRING; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes + 1; buffer[index - 1] = 0; // Write the string var size = buffer.write(value, index + 4, 'utf8'); // Write the size of the string to buffer buffer[index + 3] = ((size + 1) >> 24) & 0xff; buffer[index + 2] = ((size + 1) >> 16) & 0xff; buffer[index + 1] = ((size + 1) >> 8) & 0xff; buffer[index] = (size + 1) & 0xff; // Update index index = index + 4 + size; // Write zero buffer[index++] = 0; return index; }; var serializeNumber = function(buffer, key, value, index, isArray) { // We have an integer value if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { // If the value fits in 32 bits encode as int, if it fits in a double // encode it as a double, otherwise long if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // Set int type 32 bits or less buffer[index++] = BSON.BSON_DATA_INT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the int value buffer[index++] = value & 0xff; buffer[index++] = (value >> 8) & 0xff; buffer[index++] = (value >> 16) & 0xff; buffer[index++] = (value >> 24) & 0xff; } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { // Encode as double buffer[index++] = BSON.BSON_DATA_NUMBER; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write float writeIEEE754(buffer, value, index, 'little', 52, 8); // Ajust index index = index + 8; } else { // Set long type buffer[index++] = BSON.BSON_DATA_LONG; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; var longVal = Long.fromNumber(value); var lowBits = longVal.getLowBits(); var highBits = longVal.getHighBits(); // Encode low bits buffer[index++] = lowBits & 0xff; buffer[index++] = (lowBits >> 8) & 0xff; buffer[index++] = (lowBits >> 16) & 0xff; buffer[index++] = (lowBits >> 24) & 0xff; // Encode high bits buffer[index++] = highBits & 0xff; buffer[index++] = (highBits >> 8) & 0xff; buffer[index++] = (highBits >> 16) & 0xff; buffer[index++] = (highBits >> 24) & 0xff; } } else { // Encode as double buffer[index++] = BSON.BSON_DATA_NUMBER; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write float writeIEEE754(buffer, value, index, 'little', 52, 8); // Ajust index index = index + 8; } return index; }; var serializeNull = function(buffer, key, value, index, isArray) { // Set long type buffer[index++] = BSON.BSON_DATA_NULL; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; return index; }; var serializeBoolean = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_BOOLEAN; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Encode the boolean value buffer[index++] = value ? 1 : 0; return index; }; var serializeDate = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_DATE; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the date var dateInMilis = Long.fromNumber(value.getTime()); var lowBits = dateInMilis.getLowBits(); var highBits = dateInMilis.getHighBits(); // Encode low bits buffer[index++] = lowBits & 0xff; buffer[index++] = (lowBits >> 8) & 0xff; buffer[index++] = (lowBits >> 16) & 0xff; buffer[index++] = (lowBits >> 24) & 0xff; // Encode high bits buffer[index++] = highBits & 0xff; buffer[index++] = (highBits >> 8) & 0xff; buffer[index++] = (highBits >> 16) & 0xff; buffer[index++] = (highBits >> 24) & 0xff; return index; }; var serializeRegExp = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_REGEXP; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; if (value.source && value.source.match(regexp) != null) { throw Error('value ' + value.source + ' must not contain null bytes'); } // Adjust the index index = index + buffer.write(value.source, index, 'utf8'); // Write zero buffer[index++] = 0x00; // Write the parameters if (value.global) buffer[index++] = 0x73; // s if (value.ignoreCase) buffer[index++] = 0x69; // i if (value.multiline) buffer[index++] = 0x6d; // m // Add ending zero buffer[index++] = 0x00; return index; }; var serializeBSONRegExp = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_REGEXP; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Check the pattern for 0 bytes if (value.pattern.match(regexp) != null) { // The BSON spec doesn't allow keys with null bytes because keys are // null-terminated. throw Error('pattern ' + value.pattern + ' must not contain null bytes'); } // Adjust the index index = index + buffer.write(value.pattern, index, 'utf8'); // Write zero buffer[index++] = 0x00; // Write the options index = index + buffer.write( value.options .split('') .sort() .join(''), index, 'utf8' ); // Add ending zero buffer[index++] = 0x00; return index; }; var serializeMinMax = function(buffer, key, value, index, isArray) { // Write the type of either min or max key if (value === null) { buffer[index++] = BSON.BSON_DATA_NULL; } else if (value._bsontype === 'MinKey') { buffer[index++] = BSON.BSON_DATA_MIN_KEY; } else { buffer[index++] = BSON.BSON_DATA_MAX_KEY; } // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; return index; }; var serializeObjectId = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_OID; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the objectId into the shared buffer if (typeof value.id === 'string') { buffer.write(value.id, index, 'binary'); } else if (value.id && value.id.copy) { value.id.copy(buffer, index, 0, 12); } else { throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); } // Ajust index return index + 12; }; var serializeBuffer = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_BINARY; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Get size of the buffer (current write point) var size = value.length; // Write the size of the string to buffer buffer[index++] = size & 0xff; buffer[index++] = (size >> 8) & 0xff; buffer[index++] = (size >> 16) & 0xff; buffer[index++] = (size >> 24) & 0xff; // Write the default subtype buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; // Copy the content form the binary field to the buffer value.copy(buffer, index, 0, size); // Adjust the index index = index + size; return index; }; var serializeObject = function( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path ) { for (var i = 0; i < path.length; i++) { if (path[i] === value) throw new Error('cyclic dependency detected'); } // Push value to stack path.push(value); // Write the type buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; var endIndex = serializeInto( buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path ); // Pop stack path.pop(); // Write size return endIndex; }; var serializeDecimal128 = function(buffer, key, value, index, isArray) { buffer[index++] = BSON.BSON_DATA_DECIMAL128; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the data from the value value.bytes.copy(buffer, index, 0, 16); return index + 16; }; var serializeLong = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the date var lowBits = value.getLowBits(); var highBits = value.getHighBits(); // Encode low bits buffer[index++] = lowBits & 0xff; buffer[index++] = (lowBits >> 8) & 0xff; buffer[index++] = (lowBits >> 16) & 0xff; buffer[index++] = (lowBits >> 24) & 0xff; // Encode high bits buffer[index++] = highBits & 0xff; buffer[index++] = (highBits >> 8) & 0xff; buffer[index++] = (highBits >> 16) & 0xff; buffer[index++] = (highBits >> 24) & 0xff; return index; }; var serializeInt32 = function(buffer, key, value, index, isArray) { // Set int type 32 bits or less buffer[index++] = BSON.BSON_DATA_INT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the int value buffer[index++] = value & 0xff; buffer[index++] = (value >> 8) & 0xff; buffer[index++] = (value >> 16) & 0xff; buffer[index++] = (value >> 24) & 0xff; return index; }; var serializeDouble = function(buffer, key, value, index, isArray) { // Encode as double buffer[index++] = BSON.BSON_DATA_NUMBER; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write float writeIEEE754(buffer, value, index, 'little', 52, 8); // Ajust index index = index + 8; return index; }; var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { buffer[index++] = BSON.BSON_DATA_CODE; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Function string var functionString = normalizedFunctionString(value); // Write the string var size = buffer.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = size & 0xff; buffer[index + 1] = (size >> 8) & 0xff; buffer[index + 2] = (size >> 16) & 0xff; buffer[index + 3] = (size >> 24) & 0xff; // Update index index = index + 4 + size - 1; // Write zero buffer[index++] = 0; return index; }; var serializeCode = function( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray ) { if (value.scope && typeof value.scope === 'object') { // Write the type buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Starting index var startIndex = index; // Serialize the function // Get the function string var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); // Index adjustment index = index + 4; // Write string into buffer var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = codeSize & 0xff; buffer[index + 1] = (codeSize >> 8) & 0xff; buffer[index + 2] = (codeSize >> 16) & 0xff; buffer[index + 3] = (codeSize >> 24) & 0xff; // Write end 0 buffer[index + 4 + codeSize - 1] = 0; // Write the index = index + codeSize + 4; // // Serialize the scope value var endIndex = serializeInto( buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined ); index = endIndex - 1; // Writ the total var totalSize = endIndex - startIndex; // Write the total size of the object buffer[startIndex++] = totalSize & 0xff; buffer[startIndex++] = (totalSize >> 8) & 0xff; buffer[startIndex++] = (totalSize >> 16) & 0xff; buffer[startIndex++] = (totalSize >> 24) & 0xff; // Write trailing zero buffer[index++] = 0; } else { buffer[index++] = BSON.BSON_DATA_CODE; // Number of written bytes numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Function string functionString = value.code.toString(); // Write the string var size = buffer.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = size & 0xff; buffer[index + 1] = (size >> 8) & 0xff; buffer[index + 2] = (size >> 16) & 0xff; buffer[index + 3] = (size >> 24) & 0xff; // Update index index = index + 4 + size - 1; // Write zero buffer[index++] = 0; } return index; }; var serializeBinary = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_BINARY; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Extract the buffer var data = value.value(true); // Calculate size var size = value.position; // Add the deprecated 02 type 4 bytes of size to total if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; // Write the size of the string to buffer buffer[index++] = size & 0xff; buffer[index++] = (size >> 8) & 0xff; buffer[index++] = (size >> 16) & 0xff; buffer[index++] = (size >> 24) & 0xff; // Write the subtype to the buffer buffer[index++] = value.sub_type; // If we have binary type 2 the 4 first bytes are the size if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { size = size - 4; buffer[index++] = size & 0xff; buffer[index++] = (size >> 8) & 0xff; buffer[index++] = (size >> 16) & 0xff; buffer[index++] = (size >> 24) & 0xff; } // Write the data to the object data.copy(buffer, index, 0, value.position); // Adjust the index index = index + value.position; return index; }; var serializeSymbol = function(buffer, key, value, index, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_SYMBOL; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; // Write the string var size = buffer.write(value.value, index + 4, 'utf8') + 1; // Write the size of the string to buffer buffer[index] = size & 0xff; buffer[index + 1] = (size >> 8) & 0xff; buffer[index + 2] = (size >> 16) & 0xff; buffer[index + 3] = (size >> 24) & 0xff; // Update index index = index + 4 + size - 1; // Write zero buffer[index++] = 0x00; return index; }; var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { // Write the type buffer[index++] = BSON.BSON_DATA_OBJECT; // Number of written bytes var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); // Encode the name index = index + numberOfWrittenBytes; buffer[index++] = 0; var startIndex = index; var endIndex; // Serialize object if (null != value.db) { endIndex = serializeInto( buffer, { $ref: value.namespace, $id: value.oid, $db: value.db }, false, index, depth + 1, serializeFunctions ); } else { endIndex = serializeInto( buffer, { $ref: value.namespace, $id: value.oid }, false, index, depth + 1, serializeFunctions ); } // Calculate object size var size = endIndex - startIndex; // Write the size buffer[startIndex++] = size & 0xff; buffer[startIndex++] = (size >> 8) & 0xff; buffer[startIndex++] = (size >> 16) & 0xff; buffer[startIndex++] = (size >> 24) & 0xff; // Set index return endIndex; }; var serializeInto = function serializeInto( buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path ) { startingIndex = startingIndex || 0; path = path || []; // Push the object to the path path.push(object); // Start place to serialize into var index = startingIndex + 4; // var self = this; // Special case isArray if (Array.isArray(object)) { // Get object keys for (var i = 0; i < object.length; i++) { var key = '' + i; var value = object[i]; // Is there an override value if (value && value.toBSON) { if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); value = value.toBSON(); } var type = typeof value; if (type === 'string') { index = serializeString(buffer, key, value, index, true); } else if (type === 'number') { index = serializeNumber(buffer, key, value, index, true); } else if (type === 'boolean') { index = serializeBoolean(buffer, key, value, index, true); } else if (value instanceof Date || isDate(value)) { index = serializeDate(buffer, key, value, index, true); } else if (value === undefined) { index = serializeNull(buffer, key, value, index, true); } else if (value === null) { index = serializeNull(buffer, key, value, index, true); } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { index = serializeObjectId(buffer, key, value, index, true); } else if (Buffer.isBuffer(value)) { index = serializeBuffer(buffer, key, value, index, true); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer, key, value, index, true); } else if (type === 'object' && value['_bsontype'] == null) { index = serializeObject( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path ); } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { index = serializeDecimal128(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { index = serializeLong(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Double') { index = serializeDouble(buffer, key, value, index, true); } else if (typeof value === 'function' && serializeFunctions) { index = serializeFunction( buffer, key, value, index, checkKeys, depth, serializeFunctions, true ); } else if (value['_bsontype'] === 'Code') { index = serializeCode( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true ); } else if (value['_bsontype'] === 'Binary') { index = serializeBinary(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Symbol') { index = serializeSymbol(buffer, key, value, index, true); } else if (value['_bsontype'] === 'DBRef') { index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); } else if (value['_bsontype'] === 'BSONRegExp') { index = serializeBSONRegExp(buffer, key, value, index, true); } else if (value['_bsontype'] === 'Int32') { index = serializeInt32(buffer, key, value, index, true); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index, true); } else if (typeof value['_bsontype'] !== 'undefined') { throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else if (object instanceof Map) { var iterator = object.entries(); var done = false; while (!done) { // Unpack the next entry var entry = iterator.next(); done = entry.done; // Are we done, then skip and terminate if (done) continue; // Get the entry values key = entry.value[0]; value = entry.value[1]; // Check the type of the value type = typeof value; // Check the key and throw error if it's illegal if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { if (key.match(regexp) != null) { // The BSON spec doesn't allow keys with null bytes because keys are // null-terminated. throw Error('key ' + key + ' must not contain null bytes'); } if (checkKeys) { if ('$' === key[0]) { throw Error('key ' + key + " must not start with '$'"); } else if (~key.indexOf('.')) { throw Error('key ' + key + " must not contain '.'"); } } } if (type === 'string') { index = serializeString(buffer, key, value, index); } else if (type === 'number') { index = serializeNumber(buffer, key, value, index); } else if (type === 'boolean') { index = serializeBoolean(buffer, key, value, index); } else if (value instanceof Date || isDate(value)) { index = serializeDate(buffer, key, value, index); // } else if (value === undefined && ignoreUndefined === true) { } else if (value === null || (value === undefined && ignoreUndefined === false)) { index = serializeNull(buffer, key, value, index); } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { index = serializeObjectId(buffer, key, value, index); } else if (Buffer.isBuffer(value)) { index = serializeBuffer(buffer, key, value, index); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer, key, value, index); } else if (type === 'object' && value['_bsontype'] == null) { index = serializeObject( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path ); } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { index = serializeDecimal128(buffer, key, value, index); } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { index = serializeLong(buffer, key, value, index); } else if (value['_bsontype'] === 'Double') { index = serializeDouble(buffer, key, value, index); } else if (value['_bsontype'] === 'Code') { index = serializeCode( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined ); } else if (typeof value === 'function' && serializeFunctions) { index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); } else if (value['_bsontype'] === 'Binary') { index = serializeBinary(buffer, key, value, index); } else if (value['_bsontype'] === 'Symbol') { index = serializeSymbol(buffer, key, value, index); } else if (value['_bsontype'] === 'DBRef') { index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); } else if (value['_bsontype'] === 'BSONRegExp') { index = serializeBSONRegExp(buffer, key, value, index); } else if (value['_bsontype'] === 'Int32') { index = serializeInt32(buffer, key, value, index); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index); } else if (typeof value['_bsontype'] !== 'undefined') { throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else { // Did we provide a custom serialization method if (object.toBSON) { if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); object = object.toBSON(); if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); } // Iterate over all the keys for (key in object) { value = object[key]; // Is there an override value if (value && value.toBSON) { if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); value = value.toBSON(); } // Check the type of the value type = typeof value; // Check the key and throw error if it's illegal if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { if (key.match(regexp) != null) { // The BSON spec doesn't allow keys with null bytes because keys are // null-terminated. throw Error('key ' + key + ' must not contain null bytes'); } if (checkKeys) { if ('$' === key[0]) { throw Error('key ' + key + " must not start with '$'"); } else if (~key.indexOf('.')) { throw Error('key ' + key + " must not contain '.'"); } } } if (type === 'string') { index = serializeString(buffer, key, value, index); } else if (type === 'number') { index = serializeNumber(buffer, key, value, index); } else if (type === 'boolean') { index = serializeBoolean(buffer, key, value, index); } else if (value instanceof Date || isDate(value)) { index = serializeDate(buffer, key, value, index); } else if (value === undefined) { if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); } else if (value === null) { index = serializeNull(buffer, key, value, index); } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { index = serializeObjectId(buffer, key, value, index); } else if (Buffer.isBuffer(value)) { index = serializeBuffer(buffer, key, value, index); } else if (value instanceof RegExp || isRegExp(value)) { index = serializeRegExp(buffer, key, value, index); } else if (type === 'object' && value['_bsontype'] == null) { index = serializeObject( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path ); } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { index = serializeDecimal128(buffer, key, value, index); } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { index = serializeLong(buffer, key, value, index); } else if (value['_bsontype'] === 'Double') { index = serializeDouble(buffer, key, value, index); } else if (value['_bsontype'] === 'Code') { index = serializeCode( buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined ); } else if (typeof value === 'function' && serializeFunctions) { index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); } else if (value['_bsontype'] === 'Binary') { index = serializeBinary(buffer, key, value, index); } else if (value['_bsontype'] === 'Symbol') { index = serializeSymbol(buffer, key, value, index); } else if (value['_bsontype'] === 'DBRef') { index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); } else if (value['_bsontype'] === 'BSONRegExp') { index = serializeBSONRegExp(buffer, key, value, index); } else if (value['_bsontype'] === 'Int32') { index = serializeInt32(buffer, key, value, index); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index); } else if (typeof value['_bsontype'] !== 'undefined') { throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } // Remove the path path.pop(); // Final padding byte for object buffer[index++] = 0x00; // Final size var size = index - startingIndex; // Write the size of the object buffer[startingIndex++] = size & 0xff; buffer[startingIndex++] = (size >> 8) & 0xff; buffer[startingIndex++] = (size >> 16) & 0xff; buffer[startingIndex++] = (size >> 24) & 0xff; return index; }; var BSON = {}; /** * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 * * @ignore * @api private */ // var functionCache = (BSON.functionCache = {}); /** * Number BSON Type * * @classconstant BSON_DATA_NUMBER **/ BSON.BSON_DATA_NUMBER = 1; /** * String BSON Type * * @classconstant BSON_DATA_STRING **/ BSON.BSON_DATA_STRING = 2; /** * Object BSON Type * * @classconstant BSON_DATA_OBJECT **/ BSON.BSON_DATA_OBJECT = 3; /** * Array BSON Type * * @classconstant BSON_DATA_ARRAY **/ BSON.BSON_DATA_ARRAY = 4; /** * Binary BSON Type * * @classconstant BSON_DATA_BINARY **/ BSON.BSON_DATA_BINARY = 5; /** * ObjectID BSON Type, deprecated * * @classconstant BSON_DATA_UNDEFINED **/ BSON.BSON_DATA_UNDEFINED = 6; /** * ObjectID BSON Type * * @classconstant BSON_DATA_OID **/ BSON.BSON_DATA_OID = 7; /** * Boolean BSON Type * * @classconstant BSON_DATA_BOOLEAN **/ BSON.BSON_DATA_BOOLEAN = 8; /** * Date BSON Type * * @classconstant BSON_DATA_DATE **/ BSON.BSON_DATA_DATE = 9; /** * null BSON Type * * @classconstant BSON_DATA_NULL **/ BSON.BSON_DATA_NULL = 10; /** * RegExp BSON Type * * @classconstant BSON_DATA_REGEXP **/ BSON.BSON_DATA_REGEXP = 11; /** * Code BSON Type * * @classconstant BSON_DATA_CODE **/ BSON.BSON_DATA_CODE = 13; /** * Symbol BSON Type * * @classconstant BSON_DATA_SYMBOL **/ BSON.BSON_DATA_SYMBOL = 14; /** * Code with Scope BSON Type * * @classconstant BSON_DATA_CODE_W_SCOPE **/ BSON.BSON_DATA_CODE_W_SCOPE = 15; /** * 32 bit Integer BSON Type * * @classconstant BSON_DATA_INT **/ BSON.BSON_DATA_INT = 16; /** * Timestamp BSON Type * * @classconstant BSON_DATA_TIMESTAMP **/ BSON.BSON_DATA_TIMESTAMP = 17; /** * Long BSON Type * * @classconstant BSON_DATA_LONG **/ BSON.BSON_DATA_LONG = 18; /** * Long BSON Type * * @classconstant BSON_DATA_DECIMAL128 **/ BSON.BSON_DATA_DECIMAL128 = 19; /** * MinKey BSON Type * * @classconstant BSON_DATA_MIN_KEY **/ BSON.BSON_DATA_MIN_KEY = 0xff; /** * MaxKey BSON Type * * @classconstant BSON_DATA_MAX_KEY **/ BSON.BSON_DATA_MAX_KEY = 0x7f; /** * Binary Default Type * * @classconstant BSON_BINARY_SUBTYPE_DEFAULT **/ BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; /** * Binary Function Type * * @classconstant BSON_BINARY_SUBTYPE_FUNCTION **/ BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; /** * Binary Byte Array Type * * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY **/ BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; /** * Binary UUID Type * * @classconstant BSON_BINARY_SUBTYPE_UUID **/ BSON.BSON_BINARY_SUBTYPE_UUID = 3; /** * Binary MD5 Type * * @classconstant BSON_BINARY_SUBTYPE_MD5 **/ BSON.BSON_BINARY_SUBTYPE_MD5 = 4; /** * Binary User Defined Type * * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED **/ BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; // BSON MAX VALUES BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; BSON.BSON_INT64_MIN = -Math.pow(2, 63); // JS MAX PRECISE VALUES BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // Internal long versions // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. module.exports = serializeInto; }).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) },{"../../../../is-buffer/index.js":255,"../binary":95,"../float_parser":101,"../long":103,"../map":104,"./utils":111}],111:[function(require,module,exports){ (function (Buffer){ 'use strict'; /** * Normalizes our expected stringified form of a function across versions of node * @param {Function} fn The function to stringify */ function normalizedFunctionString(fn) { return fn.toString().replace(/function *\(/, 'function ('); } function newBuffer(item, encoding) { return new Buffer(item, encoding); } function allocBuffer() { return Buffer.alloc.apply(Buffer, arguments); } function toBuffer() { return Buffer.from.apply(Buffer, arguments); } module.exports = { normalizedFunctionString: normalizedFunctionString, allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer }; }).call(this,require("buffer").Buffer) },{"buffer":115}],112:[function(require,module,exports){ /** * A class representation of the BSON RegExp type. * * @class * @return {BSONRegExp} A MinKey instance */ function BSONRegExp(pattern, options) { if (!(this instanceof BSONRegExp)) return new BSONRegExp(); // Execute this._bsontype = 'BSONRegExp'; this.pattern = pattern || ''; this.options = options || ''; // Validate options for (var i = 0; i < this.options.length; i++) { if ( !( this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u' ) ) { throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); } } } module.exports = BSONRegExp; module.exports.BSONRegExp = BSONRegExp; },{}],113:[function(require,module,exports){ (function (Buffer){ // Custom inspect property name / symbol. var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; /** * A class representation of the BSON Symbol type. * * @class * @deprecated * @param {string} value the string representing the symbol. * @return {Symbol} */ function Symbol(value) { if (!(this instanceof Symbol)) return new Symbol(value); this._bsontype = 'Symbol'; this.value = value; } /** * Access the wrapped string value. * * @method * @return {String} returns the wrapped string. */ Symbol.prototype.valueOf = function() { return this.value; }; /** * @ignore */ Symbol.prototype.toString = function() { return this.value; }; /** * @ignore */ Symbol.prototype[inspect] = function() { return this.value; }; /** * @ignore */ Symbol.prototype.toJSON = function() { return this.value; }; module.exports = Symbol; module.exports.Symbol = Symbol; }).call(this,require("buffer").Buffer) },{"buffer":115,"util":414}],114:[function(require,module,exports){ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Copyright 2009 Google Inc. All Rights Reserved /** * This type is for INTERNAL use in MongoDB only and should not be used in applications. * The appropriate corresponding type is the JavaScript Date type. * * Defines a Timestamp class for representing a 64-bit two's-complement * integer value, which faithfully simulates the behavior of a Java "Timestamp". This * implementation is derived from TimestampLib in GWT. * * Constructs a 64-bit two's-complement integer, given its low and high 32-bit * values as *signed* integers. See the from* functions below for more * convenient ways of constructing Timestamps. * * The internal representation of a Timestamp is the two given signed, 32-bit values. * We use 32-bit pieces because these are the size of integers on which * Javascript performs bit-operations. For operations like addition and * multiplication, we split each number into 16-bit pieces, which can easily be * multiplied within Javascript's floating-point representation without overflow * or change in sign. * * In the algorithms below, we frequently reduce the negative case to the * positive case by negating the input(s) and then post-processing the result. * Note that we must ALWAYS check specially whether those values are MIN_VALUE * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as * a positive number, it overflows back into a negative). Not handling this * case would often result in infinite recursion. * * @class * @param {number} low the low (signed) 32 bits of the Timestamp. * @param {number} high the high (signed) 32 bits of the Timestamp. */ function Timestamp(low, high) { if (!(this instanceof Timestamp)) return new Timestamp(low, high); this._bsontype = 'Timestamp'; /** * @type {number} * @ignore */ this.low_ = low | 0; // force into 32 signed bits. /** * @type {number} * @ignore */ this.high_ = high | 0; // force into 32 signed bits. } /** * Return the int value. * * @return {number} the value, assuming it is a 32-bit integer. */ Timestamp.prototype.toInt = function() { return this.low_; }; /** * Return the Number value. * * @method * @return {number} the closest floating-point representation to this value. */ Timestamp.prototype.toNumber = function() { return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); }; /** * Return the JSON value. * * @method * @return {string} the JSON representation. */ Timestamp.prototype.toJSON = function() { return this.toString(); }; /** * Return the String value. * * @method * @param {number} [opt_radix] the radix in which the text should be written. * @return {string} the textual representation of this value. */ Timestamp.prototype.toString = function(opt_radix) { var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (this.isZero()) { return '0'; } if (this.isNegative()) { if (this.equals(Timestamp.MIN_VALUE)) { // We need to change the Timestamp value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. var radixTimestamp = Timestamp.fromNumber(radix); var div = this.div(radixTimestamp); var rem = div.multiply(radixTimestamp).subtract(this); return div.toString(radix) + rem.toInt().toString(radix); } else { return '-' + this.negate().toString(radix); } } // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); rem = this; var result = ''; while (!rem.isZero()) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) { return digits + result; } else { while (digits.length < 6) { digits = '0' + digits; } result = '' + digits + result; } } }; /** * Return the high 32-bits value. * * @method * @return {number} the high 32-bits as a signed value. */ Timestamp.prototype.getHighBits = function() { return this.high_; }; /** * Return the low 32-bits value. * * @method * @return {number} the low 32-bits as a signed value. */ Timestamp.prototype.getLowBits = function() { return this.low_; }; /** * Return the low unsigned 32-bits value. * * @method * @return {number} the low 32-bits as an unsigned value. */ Timestamp.prototype.getLowBitsUnsigned = function() { return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; }; /** * Returns the number of bits needed to represent the absolute value of this Timestamp. * * @method * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. */ Timestamp.prototype.getNumBitsAbs = function() { if (this.isNegative()) { if (this.equals(Timestamp.MIN_VALUE)) { return 64; } else { return this.negate().getNumBitsAbs(); } } else { var val = this.high_ !== 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { if ((val & (1 << bit)) !== 0) { break; } } return this.high_ !== 0 ? bit + 33 : bit + 1; } }; /** * Return whether this value is zero. * * @method * @return {boolean} whether this value is zero. */ Timestamp.prototype.isZero = function() { return this.high_ === 0 && this.low_ === 0; }; /** * Return whether this value is negative. * * @method * @return {boolean} whether this value is negative. */ Timestamp.prototype.isNegative = function() { return this.high_ < 0; }; /** * Return whether this value is odd. * * @method * @return {boolean} whether this value is odd. */ Timestamp.prototype.isOdd = function() { return (this.low_ & 1) === 1; }; /** * Return whether this Timestamp equals the other * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp equals the other */ Timestamp.prototype.equals = function(other) { return this.high_ === other.high_ && this.low_ === other.low_; }; /** * Return whether this Timestamp does not equal the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp does not equal the other. */ Timestamp.prototype.notEquals = function(other) { return this.high_ !== other.high_ || this.low_ !== other.low_; }; /** * Return whether this Timestamp is less than the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is less than the other. */ Timestamp.prototype.lessThan = function(other) { return this.compare(other) < 0; }; /** * Return whether this Timestamp is less than or equal to the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is less than or equal to the other. */ Timestamp.prototype.lessThanOrEqual = function(other) { return this.compare(other) <= 0; }; /** * Return whether this Timestamp is greater than the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is greater than the other. */ Timestamp.prototype.greaterThan = function(other) { return this.compare(other) > 0; }; /** * Return whether this Timestamp is greater than or equal to the other. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} whether this Timestamp is greater than or equal to the other. */ Timestamp.prototype.greaterThanOrEqual = function(other) { return this.compare(other) >= 0; }; /** * Compares this Timestamp with the given one. * * @method * @param {Timestamp} other Timestamp to compare against. * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. */ Timestamp.prototype.compare = function(other) { if (this.equals(other)) { return 0; } var thisNeg = this.isNegative(); var otherNeg = other.isNegative(); if (thisNeg && !otherNeg) { return -1; } if (!thisNeg && otherNeg) { return 1; } // at this point, the signs are the same, so subtraction will not overflow if (this.subtract(other).isNegative()) { return -1; } else { return 1; } }; /** * The negation of this value. * * @method * @return {Timestamp} the negation of this value. */ Timestamp.prototype.negate = function() { if (this.equals(Timestamp.MIN_VALUE)) { return Timestamp.MIN_VALUE; } else { return this.not().add(Timestamp.ONE); } }; /** * Returns the sum of this and the given Timestamp. * * @method * @param {Timestamp} other Timestamp to add to this one. * @return {Timestamp} the sum of this and the given Timestamp. */ Timestamp.prototype.add = function(other) { // Divide each number into 4 chunks of 16 bits, and then sum the chunks. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 + b48; c48 &= 0xffff; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns the difference of this and the given Timestamp. * * @method * @param {Timestamp} other Timestamp to subtract from this. * @return {Timestamp} the difference of this and the given Timestamp. */ Timestamp.prototype.subtract = function(other) { return this.add(other.negate()); }; /** * Returns the product of this and the given Timestamp. * * @method * @param {Timestamp} other Timestamp to multiply with this. * @return {Timestamp} the product of this and the other. */ Timestamp.prototype.multiply = function(other) { if (this.isZero()) { return Timestamp.ZERO; } else if (other.isZero()) { return Timestamp.ZERO; } if (this.equals(Timestamp.MIN_VALUE)) { return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; } else if (other.equals(Timestamp.MIN_VALUE)) { return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { return this.negate() .multiply(other) .negate(); } } else if (other.isNegative()) { return this.multiply(other.negate()).negate(); } // If both Timestamps are small, use float multiplication if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { return Timestamp.fromNumber(this.toNumber() * other.toNumber()); } // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. // We can skip products that would overflow. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xffff; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xffff; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xffff; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns this Timestamp divided by the given one. * * @method * @param {Timestamp} other Timestamp by which to divide. * @return {Timestamp} this Timestamp divided by the given one. */ Timestamp.prototype.div = function(other) { if (other.isZero()) { throw Error('division by zero'); } else if (this.isZero()) { return Timestamp.ZERO; } if (this.equals(Timestamp.MIN_VALUE)) { if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE } else if (other.equals(Timestamp.MIN_VALUE)) { return Timestamp.ONE; } else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. var halfThis = this.shiftRight(1); var approx = halfThis.div(other).shiftLeft(1); if (approx.equals(Timestamp.ZERO)) { return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; } else { var rem = this.subtract(other.multiply(approx)); var result = approx.add(rem.div(other)); return result; } } } else if (other.equals(Timestamp.MIN_VALUE)) { return Timestamp.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { return this.negate() .div(other) .negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); } // Repeat the following until the remainder is less than other: find a // floating-point that approximates remainder / other *from below*, add this // into the result, and subtract it from the remainder. It is critical that // the approximate value is less than or equal to the real value so that the // remainder never becomes negative. var res = Timestamp.ZERO; rem = this; while (rem.greaterThanOrEqual(other)) { // Approximate the result of division. This may be a little greater or // smaller than the actual value. approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or // the smallest non-fractional digit, whichever is larger. var log2 = Math.ceil(Math.log(approx) / Math.LN2); var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. var approxRes = Timestamp.fromNumber(approx); var approxRem = approxRes.multiply(other); while (approxRem.isNegative() || approxRem.greaterThan(rem)) { approx -= delta; approxRes = Timestamp.fromNumber(approx); approxRem = approxRes.multiply(other); } // We know the answer can't be zero... and actually, zero would cause // infinite recursion since we would make no progress. if (approxRes.isZero()) { approxRes = Timestamp.ONE; } res = res.add(approxRes); rem = rem.subtract(approxRem); } return res; }; /** * Returns this Timestamp modulo the given one. * * @method * @param {Timestamp} other Timestamp by which to mod. * @return {Timestamp} this Timestamp modulo the given one. */ Timestamp.prototype.modulo = function(other) { return this.subtract(this.div(other).multiply(other)); }; /** * The bitwise-NOT of this value. * * @method * @return {Timestamp} the bitwise-NOT of this value. */ Timestamp.prototype.not = function() { return Timestamp.fromBits(~this.low_, ~this.high_); }; /** * Returns the bitwise-AND of this Timestamp and the given one. * * @method * @param {Timestamp} other the Timestamp with which to AND. * @return {Timestamp} the bitwise-AND of this and the other. */ Timestamp.prototype.and = function(other) { return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); }; /** * Returns the bitwise-OR of this Timestamp and the given one. * * @method * @param {Timestamp} other the Timestamp with which to OR. * @return {Timestamp} the bitwise-OR of this and the other. */ Timestamp.prototype.or = function(other) { return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); }; /** * Returns the bitwise-XOR of this Timestamp and the given one. * * @method * @param {Timestamp} other the Timestamp with which to XOR. * @return {Timestamp} the bitwise-XOR of this and the other. */ Timestamp.prototype.xor = function(other) { return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); }; /** * Returns this Timestamp with bits shifted to the left by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the left by the given amount. */ Timestamp.prototype.shiftLeft = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var low = this.low_; if (numBits < 32) { var high = this.high_; return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return Timestamp.fromBits(0, low << (numBits - 32)); } } }; /** * Returns this Timestamp with bits shifted to the right by the given amount. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the right by the given amount. */ Timestamp.prototype.shiftRight = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); } } }; /** * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. * * @method * @param {number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. */ Timestamp.prototype.shiftRightUnsigned = function(numBits) { numBits &= 63; if (numBits === 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); } else if (numBits === 32) { return Timestamp.fromBits(high, 0); } else { return Timestamp.fromBits(high >>> (numBits - 32), 0); } } }; /** * Returns a Timestamp representing the given (32-bit) integer value. * * @method * @param {number} value the 32-bit integer in question. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromInt = function(value) { if (-128 <= value && value < 128) { var cachedObj = Timestamp.INT_CACHE_[value]; if (cachedObj) { return cachedObj; } } var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); if (-128 <= value && value < 128) { Timestamp.INT_CACHE_[value] = obj; } return obj; }; /** * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. * * @method * @param {number} value the number in question. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromNumber = function(value) { if (isNaN(value) || !isFinite(value)) { return Timestamp.ZERO; } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { return Timestamp.MIN_VALUE; } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { return Timestamp.MAX_VALUE; } else if (value < 0) { return Timestamp.fromNumber(-value).negate(); } else { return new Timestamp( (value % Timestamp.TWO_PWR_32_DBL_) | 0, (value / Timestamp.TWO_PWR_32_DBL_) | 0 ); } }; /** * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. * * @method * @param {number} lowBits the low 32-bits. * @param {number} highBits the high 32-bits. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromBits = function(lowBits, highBits) { return new Timestamp(lowBits, highBits); }; /** * Returns a Timestamp representation of the given string, written using the given radix. * * @method * @param {string} str the textual representation of the Timestamp. * @param {number} opt_radix the radix in which the text is written. * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromString = function(str, opt_radix) { if (str.length === 0) { throw Error('number format error: empty string'); } var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (str.charAt(0) === '-') { return Timestamp.fromString(str.substring(1), radix).negate(); } else if (str.indexOf('-') >= 0) { throw Error('number format error: interior "-" character: ' + str); } // Do several (8) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); var result = Timestamp.ZERO; for (var i = 0; i < str.length; i += 8) { var size = Math.min(8, str.length - i); var value = parseInt(str.substring(i, i + size), radix); if (size < 8) { var power = Timestamp.fromNumber(Math.pow(radix, size)); result = result.multiply(power).add(Timestamp.fromNumber(value)); } else { result = result.multiply(radixToPower); result = result.add(Timestamp.fromNumber(value)); } } return result; }; // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the // from* methods on which they depend. /** * A cache of the Timestamp representations of small integer values. * @type {Object} * @ignore */ Timestamp.INT_CACHE_ = {}; // NOTE: the compiler should inline these constant values below and then remove // these variables, so there should be no runtime penalty for these. /** * Number used repeated below in calculations. This must appear before the * first call to any from* function below. * @type {number} * @ignore */ Timestamp.TWO_PWR_16_DBL_ = 1 << 16; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_24_DBL_ = 1 << 24; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; /** * @type {number} * @ignore */ Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; /** @type {Timestamp} */ Timestamp.ZERO = Timestamp.fromInt(0); /** @type {Timestamp} */ Timestamp.ONE = Timestamp.fromInt(1); /** @type {Timestamp} */ Timestamp.NEG_ONE = Timestamp.fromInt(-1); /** @type {Timestamp} */ Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); /** @type {Timestamp} */ Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); /** * @type {Timestamp} * @ignore */ Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); /** * Expose. */ module.exports = Timestamp; module.exports.Timestamp = Timestamp; },{}],115:[function(require,module,exports){ (function (Buffer){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayLike(value) } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } var valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } var b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length ) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf) } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } var len = string.length var mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 } encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('Index out of range') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } if (val.length === 1) { var code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding) var len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } }).call(this,require("buffer").Buffer) },{"base64-js":93,"buffer":115,"ieee754":254}],116:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Code, CodeService, ValueSet, ref; ref = require('./datatypes/datatypes'), Code = ref.Code, ValueSet = ref.ValueSet; CodeService = (function() { function CodeService(valueSetsJson) { var code, codes, oid, version; if (valueSetsJson == null) { valueSetsJson = {}; } this.valueSets = {}; for (oid in valueSetsJson) { this.valueSets[oid] = {}; for (version in valueSetsJson[oid]) { codes = (function() { var i, len, ref1, results1; ref1 = valueSetsJson[oid][version]; results1 = []; for (i = 0, len = ref1.length; i < len; i++) { code = ref1[i]; results1.push(new Code(code.code, code.system, code.version)); } return results1; })(); this.valueSets[oid][version] = new ValueSet(oid, version, codes); } } } CodeService.prototype.findValueSetsByOid = function(oid) { var ref1, results1, valueSet, version; ref1 = this.valueSets[oid]; results1 = []; for (version in ref1) { valueSet = ref1[version]; results1.push(valueSet); } return results1; }; CodeService.prototype.findValueSet = function(oid, version) { var ref1, results; if (version != null) { return (ref1 = this.valueSets[oid]) != null ? ref1[version] : void 0; } else { results = this.findValueSetsByOid(oid); if (results.length === 0) { return null; } else { return results.reduce(function(a, b) { if (a.version > b.version) { return a; } else { return b; } }); } } }; return CodeService; })(); module.exports.CodeService = CodeService; }).call(this); },{"./datatypes/datatypes":121}],117:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DT, element, i, len, ref; DT = require("./datatypes/datatypes"); ref = Object.keys(DT); for (i = 0, len = ref.length; i < len; i++) { element = ref[i]; module.exports[element] = DT[element]; } }).call(this); },{"./datatypes/datatypes":121}],118:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DT, FHIR, Patient, PatientSource, Record, toDate, typeIsArray; DT = require('./datatypes/datatypes'); FHIR = require('./fhir/models'); typeIsArray = require('./util/util').typeIsArray; toDate = function(str) { if (typeof str === 'string') { return new Date(str); } else { return null; } }; Record = (function() { function Record(json1) { this.json = json1; } Record.prototype.get = function(field) { return this.json[field]; }; Record.prototype.getDate = function(field) { var val; val = this.get(field); if (val != null) { return DT.DateTime.parse(val); } else { return null; } }; Record.prototype.getInterval = function(field) { var end, start, val; val = this.get(field); if ((val != null) && typeof val === 'object') { start = val.start != null ? DT.DateTime.parse(val.start) : null; end = val.end != null ? DT.DateTime.parse(val.end) : null; return new DT.Interval(start, end); } }; Record.prototype.getDateOrInterval = function(field) { var val; val = this.get(field); if ((val != null) && typeof val === 'object') { return this.getInterval(field); } else { return this.getDate(field); } }; Record.prototype.getCode = function(field) { var val; val = this.get(field); if ((val != null) && typeof val === 'object') { return new DT.Code(val.code, val.system, val.version); } }; return Record; })(); Patient = (function() { function Patient(json) { var base, i, len, name, r, ref, ref1; this.identifier = json.identifier; this.name = json.name; this.gender = json.gender; this.birthDate = json.birthDate != null ? DT.DateTime.parse(json.birthDate) : void 0; this.records = {}; ref1 = (ref = json.records) != null ? ref : []; for (i = 0, len = ref1.length; i < len; i++) { r = ref1[i]; if ((base = this.records)[name = r.profile] == null) { base[name] = []; } this.records[r.profile].push(new Record(r)); } } Patient.prototype.findRecords = function(profile) { var ref; if (profile === 'patient-qicore-qicore-patient') { return [this]; } else { return (ref = this.records[profile]) != null ? ref : []; } }; return Patient; })(); FHIR.Patient.prototype.records = function() { var base, i, len, name, r, ref, ref1; this._records = {}; ref1 = (ref = this.json.records) != null ? ref : []; for (i = 0, len = ref1.length; i < len; i++) { r = ref1[i]; if ((base = this._records)[name = r.profile] == null) { base[name] = []; } this._records[r.profile].push(new Record(r)); } return this._records; }; FHIR.Patient.prototype.findRecords = function(profile) { var ref, ref1; if (profile === 'patient-qicore-qicore-patient') { return [this]; } else { return (ref = (ref1 = this._bundle) != null ? ref1.findRecords(profile) : void 0) != null ? ref : []; } }; FHIR.Bundle.prototype.findRecords = function(profile) { var e, filtered, i, len, r, results; filtered = this.entry().filter(function(e) { var ref, ref1, ref2; return ((ref = e.resource()) != null ? (ref1 = ref.meta()) != null ? (ref2 = ref1.profile()) != null ? ref2.indexOf(profile) : void 0 : void 0 : void 0) > -1; }); results = []; for (i = 0, len = filtered.length; i < len; i++) { e = filtered[i]; r = e.resource(); r._bundle = this; results.push(r); } return results; }; FHIR.Bundle.prototype.findRecord = function(profile) { return this.findRecords(profile)[0]; }; FHIR.Base.prototype.get = function(field) { var ref; return (ref = this[field]) != null ? ref.call(this) : void 0; }; FHIR.Base.prototype.getDate = function(field) { var val; val = this.get(field); if (val instanceof DT.DateTime) { return val; } else if (typeof val === "string") { return DT.DateTime.parse(val); } }; FHIR.Base.prototype.getInterval = function(field) { var val; val = this.get(field); if (val(instannceOf(FHIR.Period))) { return this.periodToInterval(val); } }; FHIR.Base.prototype.getDateOrInterval = function(field) { var val; val = this.get(field); if (val instanceof FHIR.Period) { return this.periodToInterval(val); } else if (typeof val === "string") { return DT.DateTime.parse(val); } else if (val instanceof DT.DateTime) { return val; } }; FHIR.Base.prototype.getCode = function(field) { var val; val = this.get(field); return this.toCode(val); }; FHIR.Base.prototype.toCode = function(val) { var c, i, len, results; if (typeIsArray(val)) { results = []; for (i = 0, len = val.length; i < len; i++) { c = val[i]; results.push(this.toCode(c)); } return results; } else if (val instanceof FHIR.CodeableConcept) { return this.codableConceptToCodes(val); } else if (val instanceof FHIR.Coding) { return this.codingToCode(val); } }; FHIR.Base.prototype.codableConceptToCodes = function(cc) { var c, i, len, ref, results; ref = cc.coding(); results = []; for (i = 0, len = ref.length; i < len; i++) { c = ref[i]; results.push(this.codingToCode(c)); } return results; }; FHIR.Base.prototype.codingToCode = function(coding) { return new DT.Code(coding.code(), coding.system(), coding.version()); }; FHIR.Base.prototype.periodToInterval = function(val) { var end, start; if (val instanceof FHIR.Period) { start = val.getDate("start"); end = val.getDate("end"); return new DT.Interval(start, end); } }; PatientSource = (function() { function PatientSource(patients) { this.patients = patients; this.nextPatient(); } PatientSource.prototype.currentPatient = function() { return this.current_patient; }; PatientSource.prototype.nextPatient = function() { var ref; this.current = this.patients.shift(); this.current_bundle = this.current ? new FHIR.Bundle(this.current) : void 0; return this.current_patient = (ref = this.current_bundle) != null ? ref.findRecord("patient-qicore-qicore-patient") : void 0; }; return PatientSource; })(); module.exports.Patient = Patient; module.exports.PatientSource = PatientSource; }).call(this); },{"./datatypes/datatypes":121,"./fhir/models":207,"./util/util":252}],119:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var codeservice, context, datatypes, exec, expression, library, patient, quantity, repository, results; library = require('./elm/library'); quantity = require('./elm/quantity'); expression = require('./elm/expression'); repository = require('./runtime/repository'); context = require('./runtime/context'); exec = require('./runtime/executor'); results = require('./runtime/results'); datatypes = require('./datatypes/datatypes'); patient = require('./cql-patient'); codeservice = require('./cql-code-service'); module.exports.Library = library.Library; module.exports.Repository = repository.Repository; module.exports.Expression = expression.Expression; module.exports.Context = context.Context; module.exports.Executor = exec.Executor; module.exports.PatientContext = context.PatientContext; module.exports.UnfilteredContext = context.UnfilteredContext; module.exports.Results = results.Results; module.exports.Patient = patient.Patient; module.exports.PatientSource = patient.PatientSource; module.exports.CodeService = codeservice.CodeService; module.exports.Code = datatypes.Code; module.exports.CodeSystem = datatypes.CodeSystem; module.exports.Concept = datatypes.Concept; module.exports.Date = datatypes.Date; module.exports.DateTime = datatypes.DateTime; module.exports.Interval = datatypes.Interval; module.exports.Quantity = datatypes.Quantity; module.exports.Ratio = datatypes.Ratio; module.exports.ValueSet = datatypes.ValueSet; }).call(this); },{"./cql-code-service":116,"./cql-patient":118,"./datatypes/datatypes":121,"./elm/expression":137,"./elm/library":142,"./elm/quantity":149,"./runtime/context":246,"./runtime/executor":247,"./runtime/repository":248,"./runtime/results":249}],120:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Code, CodeSystem, Concept, ValueSet, codesInList, codesMatch, toCodeList, typeIsArray; typeIsArray = require('../util/util').typeIsArray; module.exports.Code = Code = (function() { function Code(code3, system, version, display) { this.code = code3; this.system = system; this.version = version; this.display = display; } Object.defineProperties(Code.prototype, { isCode: { get: function() { return true; } } }); Code.prototype.hasMatch = function(code) { if (typeof code === 'string') { return code === this.code; } else { return codesInList(toCodeList(code), [this]); } }; return Code; })(); module.exports.Concept = Concept = (function() { function Concept(codes, display) { this.codes = codes != null ? codes : []; this.display = display; } Object.defineProperties(Concept.prototype, { isConcept: { get: function() { return true; } } }); Concept.prototype.hasMatch = function(code) { return codesInList(toCodeList(code), this.codes); }; return Concept; })(); module.exports.ValueSet = ValueSet = (function() { function ValueSet(oid, version, codes) { this.oid = oid; this.version = version; this.codes = codes != null ? codes : []; } Object.defineProperties(ValueSet.prototype, { isValueSet: { get: function() { return true; } } }); ValueSet.prototype.hasMatch = function(code) { var codeItem, codesList, i, len, matchFound, multipleCodeSystemsExist, ref; codesList = toCodeList(code); if (codesList.length === 1 && typeof codesList[0] === 'string') { matchFound = false; multipleCodeSystemsExist = false; ref = this.codes; for (i = 0, len = ref.length; i < len; i++) { codeItem = ref[i]; if (codeItem.system !== this.codes[0].system) { multipleCodeSystemsExist = true; } if (codeItem.code === codesList[0]) { matchFound = true; } if (multipleCodeSystemsExist && matchFound) { throw new Error('In (valueset) is ambiguous -- multiple codes with multiple code systems exist in value set.'); } } return matchFound; } else { return codesInList(codesList, this.codes); } }; return ValueSet; })(); toCodeList = function(c) { var c2, i, len, list; if (c == null) { return []; } else if (typeIsArray(c)) { list = []; for (i = 0, len = c.length; i < len; i++) { c2 = c[i]; list = list.concat(toCodeList(c2)); } return list; } else if (typeIsArray(c.codes)) { return c.codes; } else { return [c]; } }; codesInList = function(cl1, cl2) { return cl1.some(function(c1) { return cl2.some(function(c2) { if (typeof c1 === 'string') { return c1 === c2.code; } else { return codesMatch(c1, c2); } }); }); }; codesMatch = function(code1, code2) { return code1.code === code2.code && code1.system === code2.system; }; module.exports.CodeSystem = CodeSystem = (function() { function CodeSystem(id, version) { this.id = id; this.version = version; } return CodeSystem; })(); }).call(this); },{"../util/util":252}],121:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var clinical, datetime, element, i, interval, j, len, len1, lib, libs, logic, quantity, ratio, ref, uncertainty; logic = require('./logic'); clinical = require('./clinical'); uncertainty = require('./uncertainty'); datetime = require('./datetime'); interval = require('./interval'); quantity = require('./quantity'); ratio = require('./ratio'); libs = [logic, clinical, uncertainty, datetime, interval, quantity, ratio]; for (i = 0, len = libs.length; i < len; i++) { lib = libs[i]; ref = Object.keys(lib); for (j = 0, len1 = ref.length; j < len1; j++) { element = ref[j]; module.exports[element] = lib[element]; } } }).call(this); },{"./clinical":120,"./datetime":122,"./interval":124,"./logic":125,"./quantity":126,"./ratio":127,"./uncertainty":128}],122:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Date, DateTime, Uncertainty, compareWithDefaultResult, cqlFormatStringToMomentFormatString, daysInMonth, getTimezoneSeparatorFromString, isValidDateStringFormat, isValidDateTimeStringFormat, jsDate, moment, normalizeMillisecondsField, normalizeMillisecondsFieldInString, ref, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; Uncertainty = require('./uncertainty').Uncertainty; ref = require('../util/util'), jsDate = ref.jsDate, normalizeMillisecondsField = ref.normalizeMillisecondsField, normalizeMillisecondsFieldInString = ref.normalizeMillisecondsFieldInString, getTimezoneSeparatorFromString = ref.getTimezoneSeparatorFromString; moment = require('moment'); DateTime = (function() { Object.defineProperties(DateTime.prototype, { isDateTime: { get: function() { return true; } } }); DateTime.Unit = { YEAR: 'year', MONTH: 'month', WEEK: 'week', DAY: 'day', HOUR: 'hour', MINUTE: 'minute', SECOND: 'second', MILLISECOND: 'millisecond' }; DateTime.FIELDS = [DateTime.Unit.YEAR, DateTime.Unit.MONTH, DateTime.Unit.DAY, DateTime.Unit.HOUR, DateTime.Unit.MINUTE, DateTime.Unit.SECOND, DateTime.Unit.MILLISECOND]; DateTime.parse = function(string) { var arg, args, days, hours, matches, milliseconds, minutes, months, num, seconds, years; if (string === null) { return null; } matches = /(\d{4})(-(\d{2}))?(-(\d{2}))?(T((\d{2})(\:(\d{2})(\:(\d{2})(\.(\d+))?)?)?)?(Z|(([+-])(\d{2})(\:?(\d{2}))?))?)?/.exec(string); if (matches == null) { return null; } years = matches[1]; months = matches[3]; days = matches[5]; hours = matches[8]; minutes = matches[10]; seconds = matches[12]; milliseconds = matches[14]; if (milliseconds != null) { milliseconds = normalizeMillisecondsField(milliseconds); } if (milliseconds != null) { string = normalizeMillisecondsFieldInString(string, matches[14]); } if (!isValidDateTimeStringFormat(string)) { return null; } args = [years, months, days, hours, minutes, seconds, milliseconds]; args = (function() { var i, len, results; results = []; for (i = 0, len = args.length; i < len; i++) { arg = args[i]; results.push(arg != null ? parseInt(arg, 10) : void 0); } return results; })(); if (matches[18] != null) { num = parseInt(matches[18], 10) + (matches[20] != null ? parseInt(matches[20], 10) / 60 : 0); args.push(matches[17] === '+' ? num : num * -1); } else if (matches[15] === 'Z') { args.push(0); } return (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(DateTime, args, function(){}); }; DateTime.fromJSDate = function(date, timezoneOffset) { if (date instanceof DateTime) { return date; } if (timezoneOffset != null) { date = new jsDate(date.getTime() + (timezoneOffset * 60 * 60 * 1000)); return new DateTime(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds(), timezoneOffset); } else { return new DateTime(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()); } }; function DateTime(year1, month1, day, hour, minute, second, millisecond, timezoneOffset1) { this.year = year1 != null ? year1 : null; this.month = month1 != null ? month1 : null; this.day = day != null ? day : null; this.hour = hour != null ? hour : null; this.minute = minute != null ? minute : null; this.second = second != null ? second : null; this.millisecond = millisecond != null ? millisecond : null; this.timezoneOffset = timezoneOffset1; if (typeof this.timezoneOffset === 'undefined') { this.timezoneOffset = (new jsDate()).getTimezoneOffset() / 60 * -1; } } DateTime.prototype.copy = function() { return new DateTime(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond, this.timezoneOffset); }; DateTime.prototype.successor = function() { if (this.millisecond != null) { return this.add(1, DateTime.Unit.MILLISECOND); } else if (this.second != null) { return this.add(1, DateTime.Unit.SECOND); } else if (this.minute != null) { return this.add(1, DateTime.Unit.MINUTE); } else if (this.hour != null) { return this.add(1, DateTime.Unit.HOUR); } else if (this.day != null) { return this.add(1, DateTime.Unit.DAY); } else if (this.month != null) { return this.add(1, DateTime.Unit.MONTH); } else if (this.year != null) { return this.add(1, DateTime.Unit.YEAR); } }; DateTime.prototype.predecessor = function() { if (this.millisecond != null) { return this.add(-1, DateTime.Unit.MILLISECOND); } else if (this.second != null) { return this.add(-1, DateTime.Unit.SECOND); } else if (this.minute != null) { return this.add(-1, DateTime.Unit.MINUTE); } else if (this.hour != null) { return this.add(-1, DateTime.Unit.HOUR); } else if (this.day != null) { return this.add(-1, DateTime.Unit.DAY); } else if (this.month != null) { return this.add(-1, DateTime.Unit.MONTH); } else if (this.year != null) { return this.add(-1, DateTime.Unit.YEAR); } }; DateTime.prototype.convertToTimezoneOffset = function(timezoneOffset) { var d; if (timezoneOffset == null) { timezoneOffset = 0; } d = DateTime.fromJSDate(this.toJSDate(), timezoneOffset); return d.reducedPrecision(this.getPrecision()); }; DateTime.prototype.differenceBetween = function(other, unitField) { var a, aHighMoment, aJS, aLowMoment, aUncertainty, b, bHighMoment, bJS, bLowMoment, bUncertainty, tzDiff; other = this._implicitlyConvert(other); if (!(other != null ? other.isDateTime : void 0)) { return null; } a = this.copy(); b = other.copy(); if (unitField === DateTime.Unit.MONTH || unitField === DateTime.Unit.YEAR || unitField === DateTime.Unit.WEEK || unitField === DateTime.Unit.DAY) { if (a.timezoneOffset !== b.timezoneOffset) { b = b.convertToTimezoneOffset(a.timezoneOffset); } if (!a.isUTC() || !b.isUTC()) { aJS = a.toJSDate(true); bJS = b.toJSDate(true); tzDiff = aJS.getTimezoneOffset() - bJS.getTimezoneOffset(); if (tzDiff !== 0) { if ((b.year != null) && (b.month != null) && (b.day != null) && (b.hour != null) && (b.minute != null)) { b = b.add(tzDiff, DateTime.Unit.MINUTE); } else if ((b.year != null) && (b.month != null) && (b.day != null) && (b.hour != null)) { b = b.add(tzDiff / 60, DateTime.Unit.HOUR); } else { b.timezoneOffset = b.timezoneOffset + (tzDiff / 60); } } } } if (unitField === DateTime.Unit.YEAR) { a = new DateTime(a.year, 1, 1, 12, 0, 0, 0, a.timezoneOffset); b = new DateTime(b.year, 1, 1, 12, 0, 0, 0, b.timezoneOffset); } else if (unitField === DateTime.Unit.MONTH) { a = new DateTime(a.year, a.month, 1, 12, 0, 0, 0, a.timezoneOffset); b = new DateTime(b.year, b.month, 1, 12, 0, 0, 0, b.timezoneOffset); } else if (unitField === DateTime.Unit.WEEK) { a = this._floorWeek(a); b = this._floorWeek(b); } else if (unitField === DateTime.Unit.DAY) { a = new DateTime(a.year, a.month, a.day, 12, 0, 0, 0, a.timezoneOffset); b = new DateTime(b.year, b.month, b.day, 12, 0, 0, 0, b.timezoneOffset); } else if (unitField === DateTime.Unit.HOUR) { a = new DateTime(a.year, a.month, a.day, a.hour, 30, 0, 0, a.timezoneOffset); b = new DateTime(b.year, b.month, b.day, b.hour, 30, 0, 0, b.timezoneOffset); } else if (unitField === DateTime.Unit.MINUTE) { a = new DateTime(a.year, a.month, a.day, a.hour, a.minute, 0, 0, a.timezoneOffset); b = new DateTime(b.year, b.month, b.day, b.hour, b.minute, 0, 0, b.timezoneOffset); } else if (unitField === DateTime.Unit.SECOND) { a = new DateTime(a.year, a.month, a.day, a.hour, a.minute, a.second, 0, a.timezoneOffset); b = new DateTime(b.year, b.month, b.day, b.hour, b.minute, b.second, 0, b.timezoneOffset); } if (unitField === DateTime.Unit.YEAR || unitField === DateTime.Unit.MONTH) { return a.durationBetween(b, unitField); } else { aUncertainty = a.toUncertainty(); bUncertainty = b.toUncertainty(); aLowMoment = moment(aUncertainty.low).utc(); aHighMoment = moment(aUncertainty.high).utc(); bLowMoment = moment(bUncertainty.low).utc(); bHighMoment = moment(bUncertainty.high).utc(); return new Uncertainty(bLowMoment.diff(aHighMoment, unitField + 's'), bHighMoment.diff(aLowMoment, unitField + 's')); } }; DateTime.prototype._floorWeek = function(d) { var floored; if (d.day == null) { return d; } floored = new jsDate(d.year, d.month - 1, d.day); while (floored.getDay() > 0) { floored.setDate(floored.getDate() - 1); } return new DateTime(floored.getFullYear(), floored.getMonth() + 1, floored.getDate(), 12, 0, 0, 0, d.timezoneOffset); }; DateTime.prototype.durationBetween = function(other, unitField) { var a, b; other = this._implicitlyConvert(other); if (!(other != null ? other.isDateTime : void 0)) { return null; } a = this.toUncertainty(); b = other.toUncertainty(); return new Uncertainty(this._durationBetweenDates(a.high, b.low, unitField), this._durationBetweenDates(a.low, b.high, unitField)); }; DateTime.prototype._durationBetweenDates = function(a, b, unitField) { var aInMonth, aInMonthOriginalOffset, months, msDiff, truncFunc; msDiff = b.getTime() - a.getTime(); if (msDiff === 0) { return 0; } truncFunc = msDiff > 0 ? Math.floor : Math.ceil; if (unitField === DateTime.Unit.MILLISECOND) { return msDiff; } else if (unitField === DateTime.Unit.SECOND) { return truncFunc(msDiff / 1000); } else if (unitField === DateTime.Unit.MINUTE) { return truncFunc(msDiff / (60 * 1000)); } else if (unitField === DateTime.Unit.HOUR) { return truncFunc(msDiff / (60 * 60 * 1000)); } else if (unitField === DateTime.Unit.DAY) { return truncFunc(msDiff / (24 * 60 * 60 * 1000)); } else if (unitField === DateTime.Unit.WEEK) { return truncFunc(msDiff / (7 * 24 * 60 * 60 * 1000)); } else if (unitField === DateTime.Unit.MONTH || unitField === DateTime.Unit.YEAR) { months = (b.getFullYear() - a.getFullYear()) * 12 + (b.getMonth() - a.getMonth()); aInMonth = new jsDate(a.getTime()); aInMonthOriginalOffset = aInMonth.getTimezoneOffset(); aInMonth.setMonth(a.getMonth() + months); if (aInMonthOriginalOffset !== aInMonth.getTimezoneOffset()) { aInMonth.setMinutes(aInMonth.getMinutes() + (aInMonthOriginalOffset - aInMonth.getTimezoneOffset())); } if (msDiff > 0 && aInMonth > b) { months = months - 1; } else if (msDiff < 0 && aInMonth < b) { months = months + 1; } if (unitField === DateTime.Unit.MONTH) { return months; } else { return truncFunc(months / 12); } } else { return null; } }; DateTime.prototype.isUTC = function() { return !this.timezoneOffset; }; DateTime.prototype.getPrecision = function() { var result; result = null; if (this.year != null) { result = DateTime.Unit.YEAR; } else { return result; } if (this.month != null) { result = DateTime.Unit.MONTH; } else { return result; } if (this.day != null) { result = DateTime.Unit.DAY; } else { return result; } if (this.hour != null) { result = DateTime.Unit.HOUR; } else { return result; } if (this.minute != null) { result = DateTime.Unit.MINUTE; } else { return result; } if (this.second != null) { result = DateTime.Unit.SECOND; } else { return result; } if (this.millisecond != null) { result = DateTime.Unit.MILLISECOND; } return result; }; DateTime.prototype.toUncertainty = function(ignoreTimezone) { var high, low, ref1, ref2, ref3, ref4, ref5, ref6, ref7; if (ignoreTimezone == null) { ignoreTimezone = false; } low = this.toJSDate(ignoreTimezone); high = (new DateTime(this.year, (ref1 = this.month) != null ? ref1 : 12, (ref2 = this.day) != null ? ref2 : (new jsDate(this.year, (ref3 = this.month) != null ? ref3 : 12, 0)).getDate(), (ref4 = this.hour) != null ? ref4 : 23, (ref5 = this.minute) != null ? ref5 : 59, (ref6 = this.second) != null ? ref6 : 59, (ref7 = this.millisecond) != null ? ref7 : 999, this.timezoneOffset)).toJSDate(ignoreTimezone); return new Uncertainty(low, high); }; DateTime.prototype.toJSDate = function(ignoreTimezone) { var d, date, h, mi, mo, ms, ref1, ref2, ref3, ref4, ref5, ref6, s, y; if (ignoreTimezone == null) { ignoreTimezone = false; } ref6 = [this.year, (this.month != null ? this.month - 1 : 0), (ref1 = this.day) != null ? ref1 : 1, (ref2 = this.hour) != null ? ref2 : 0, (ref3 = this.minute) != null ? ref3 : 0, (ref4 = this.second) != null ? ref4 : 0, (ref5 = this.millisecond) != null ? ref5 : 0], y = ref6[0], mo = ref6[1], d = ref6[2], h = ref6[3], mi = ref6[4], s = ref6[5], ms = ref6[6]; if ((this.timezoneOffset != null) && !ignoreTimezone) { date = new jsDate(jsDate.UTC(y, mo, d, h, mi, s, ms) - (this.timezoneOffset * 60 * 60 * 1000)); if (y < 100) { date.setUTCFullYear(y); } return date; } else { date = new jsDate(y, mo, d, h, mi, s, ms); if (y < 100) { date.setFullYear(y); } return date; } }; DateTime.prototype.toJSON = function() { return this.toString(); }; DateTime.prototype._pad = function(num) { return String("0" + num).slice(-2); }; DateTime.prototype.toString = function() { if (this.isTime()) { return this.toStringTime(); } else { return this.toStringDateTime(); } }; DateTime.prototype.toStringTime = function() { var str; str = ''; if (this.hour != null) { str += +this._pad(this.hour); if (this.minute != null) { str += ':' + this._pad(this.minute); if (this.second != null) { str += ':' + this._pad(this.second); if (this.millisecond != null) { str += '.' + String("00" + this.millisecond).slice(-3); } } } } return str; }; DateTime.prototype.toStringDateTime = function() { var offsetHours, offsetMin, str; str = ''; if (this.year != null) { str += this.year; if (this.month != null) { str += '-' + this._pad(this.month); if (this.day != null) { str += '-' + this._pad(this.day); if (this.hour != null) { str += 'T' + this._pad(this.hour); if (this.minute != null) { str += ':' + this._pad(this.minute); if (this.second != null) { str += ':' + this._pad(this.second); if (this.millisecond != null) { str += '.' + String("00" + this.millisecond).slice(-3); } } } } } } } if (str.indexOf('T') !== -1 && (this.timezoneOffset != null)) { str += this.timezoneOffset < 0 ? '-' : '+'; offsetHours = Math.floor(Math.abs(this.timezoneOffset)); str += this._pad(offsetHours); offsetMin = (Math.abs(this.timezoneOffset) - offsetHours) * 60; str += ':' + this._pad(offsetMin); } return str; }; DateTime.prototype.getDateTime = function() { return this; }; DateTime.prototype.getDate = function() { return new Date(this.year, this.month, this.day); }; DateTime.prototype.getTime = function() { return new DateTime(0, 1, 1, this.hour, this.minute, this.second, this.millisecond, null); }; DateTime.prototype.isTime = function() { return this.year === 0 && this.month === 1 && this.day === 1; }; DateTime.prototype._implicitlyConvert = function(other) { if ((other != null ? other.isDate : void 0)) { return other.getDateTime(); } return other; }; DateTime.prototype.reducedPrecision = function(unitField) { var field, fieldIndex, fieldsToRemove, i, len, reduced; if (unitField == null) { unitField = DateTime.Unit.MILLISECOND; } reduced = this.copy(); if (unitField !== DateTime.Unit.MILLISECOND) { fieldIndex = DateTime.FIELDS.indexOf(unitField); fieldsToRemove = DateTime.FIELDS.slice(fieldIndex + 1); for (i = 0, len = fieldsToRemove.length; i < len; i++) { field = fieldsToRemove[i]; reduced[field] = null; } } return reduced; }; return DateTime; })(); Date = (function() { Object.defineProperties(Date.prototype, { isDate: { get: function() { return true; } } }); Date.Unit = { YEAR: 'year', MONTH: 'month', WEEK: 'week', DAY: 'day' }; Date.FIELDS = [Date.Unit.YEAR, Date.Unit.MONTH, Date.Unit.DAY]; Date.parse = function(string) { var arg, args, days, matches, months, years; if (string === null) { return null; } matches = /(\d{4})(-(\d{2}))?(-(\d{2}))?/.exec(string); if (matches == null) { return null; } years = matches[1]; months = matches[3]; days = matches[5]; if (!isValidDateStringFormat(string)) { return null; } args = [years, months, days]; args = (function() { var i, len, results; results = []; for (i = 0, len = args.length; i < len; i++) { arg = args[i]; results.push(arg != null ? parseInt(arg, 10) : void 0); } return results; })(); return (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(Date, args, function(){}); }; function Date(year1, month1, day) { this.year = year1 != null ? year1 : null; this.month = month1 != null ? month1 : null; this.day = day != null ? day : null; return; } Date.prototype.copy = function() { return new Date(this.year, this.month, this.day); }; Date.prototype.successor = function() { if (this.day != null) { return this.add(1, Date.Unit.DAY); } else if (this.month != null) { return this.add(1, Date.Unit.MONTH); } else if (this.year != null) { return this.add(1, Date.Unit.YEAR); } }; Date.prototype.predecessor = function() { if (this.day != null) { return this.add(-1, Date.Unit.DAY); } else if (this.month != null) { return this.add(-1, Date.Unit.MONTH); } else if (this.year != null) { return this.add(-1, Date.Unit.YEAR); } }; Date.prototype.differenceBetween = function(other, unitField) { var a, b; if ((other != null ? other.isDateTime : void 0)) { return this.getDateTime().differenceBetween(other, unitField); } if (!(other != null ? other.isDate : void 0)) { return null; } a = this; b = other; if (unitField === Date.Unit.YEAR) { a = new Date(a.year, 1, 1); b = new Date(b.year, 1, 1); } else if (unitField === Date.Unit.MONTH) { a = new Date(a.year, a.month, 1); b = new Date(b.year, b.month, 1); } else if (unitField === Date.Unit.WEEK) { a = this._floorWeek(a); b = this._floorWeek(b); } return a.durationBetween(b, unitField); }; Date.prototype._floorWeek = function(d) { var floored; if (d.day == null) { return d; } floored = new jsDate(d.year, d.month - 1, d.day); while (floored.getDay() > 0) { floored.setDate(floored.getDate() - 1); } return new Date(floored.getFullYear(), floored.getMonth() + 1, floored.getDate()); }; Date.prototype.durationBetween = function(other, unitField) { var a, b; if ((other != null ? other.isDateTime : void 0)) { return this.getDateTime().durationBetween(other, unitField); } if (!(other != null ? other.isDate : void 0)) { return null; } a = this.toUncertainty(); b = other.toUncertainty(); return new Uncertainty(this._durationBetweenDates(a.high, b.low, unitField), this._durationBetweenDates(a.low, b.high, unitField)); }; Date.prototype._durationBetweenDates = function(a, b, unitField) { var aInMonth, aInMonthOriginalOffset, months, msDiff, truncFunc, tzdiff; a.setTime(a.getTime() + (12 * 60 * 60 * 1000)); b.setTime(b.getTime() + (12 * 60 * 60 * 1000)); tzdiff = a.getTimezoneOffset() - b.getTimezoneOffset(); b.setTime(b.getTime() + (tzdiff * 60 * 1000)); msDiff = b.getTime() - a.getTime(); if (msDiff === 0) { return 0; } truncFunc = msDiff > 0 ? Math.floor : Math.ceil; if (unitField === Date.Unit.DAY) { return truncFunc(msDiff / (24 * 60 * 60 * 1000)); } else if (unitField === Date.Unit.WEEK) { return truncFunc(msDiff / (7 * 24 * 60 * 60 * 1000)); } else if (unitField === Date.Unit.MONTH || unitField === Date.Unit.YEAR) { months = (b.getFullYear() - a.getFullYear()) * 12 + (b.getMonth() - a.getMonth()); aInMonth = new jsDate(a.getTime()); aInMonthOriginalOffset = aInMonth.getTimezoneOffset(); aInMonth.setMonth(a.getMonth() + months); if (aInMonthOriginalOffset !== aInMonth.getTimezoneOffset()) { aInMonth.setMinutes(aInMonth.getMinutes() + (aInMonthOriginalOffset - aInMonth.getTimezoneOffset())); } if (msDiff > 0 && aInMonth > b) { months = months - 1; } else if (msDiff < 0 && aInMonth < b) { months = months + 1; } if (unitField === Date.Unit.MONTH) { return months; } else { return truncFunc(months / 12); } } else { return null; } }; Date.prototype.getPrecision = function() { var result; result = null; if (this.year != null) { result = Date.Unit.YEAR; } else { return result; } if (this.month != null) { result = Date.Unit.MONTH; } else { return result; } if (this.day != null) { result = Date.Unit.DAY; } else { return result; } return result; }; Date.prototype.toUncertainty = function() { var high, low, ref1, ref2, ref3; low = this.toJSDate(); high = new Date(this.year, (ref1 = this.month) != null ? ref1 : 12, (ref2 = this.day) != null ? ref2 : (new jsDate(this.year, (ref3 = this.month) != null ? ref3 : 12, 0)).getDate()).toJSDate(); return new Uncertainty(low, high); }; Date.prototype.toJSDate = function() { var d, mo, ref1, ref2, y; ref2 = [this.year, (this.month != null ? this.month - 1 : 0), (ref1 = this.day) != null ? ref1 : 1], y = ref2[0], mo = ref2[1], d = ref2[2]; return new jsDate(y, mo, d); }; Date.fromJSDate = function(date) { if (date instanceof Date) { return date; } return new Date(date.getFullYear(), date.getMonth() + 1, date.getDate()); }; Date.prototype.toJSON = function() { return this.toString(); }; Date.prototype.toString = function() { var str; str = ''; if (this.year != null) { str += this.year.toString(); if (this.month != null) { str += '-' + this.month.toString().padStart(2, "0"); if (this.day != null) { str += '-' + this.day.toString().padStart(2, "0"); } } } return str; }; Date.prototype.getDateTime = function() { if ((this.year != null) && (this.month != null) && (this.day != null)) { return new DateTime(this.year, this.month, this.day, 0, 0, 0, 0); } else { return new DateTime(this.year, this.month, this.day); } }; Date.prototype.reducedPrecision = function(unitField) { var field, fieldIndex, fieldsToRemove, i, len, reduced; if (unitField == null) { unitField = Date.Unit.DAY; } reduced = this.copy(); if (unitField !== Date.Unit.DAY) { fieldIndex = Date.FIELDS.indexOf(unitField); fieldsToRemove = Date.FIELDS.slice(fieldIndex + 1); for (i = 0, len = fieldsToRemove.length; i < len; i++) { field = fieldsToRemove[i]; reduced[field] = null; } } return reduced; }; return Date; })(); DateTime.prototype.isPrecise = Date.prototype.isPrecise = function() { return this.constructor.FIELDS.every((function(_this) { return function(field) { return _this[field] != null; }; })(this)); }; DateTime.prototype.isImprecise = Date.prototype.isImprecise = function() { return !this.isPrecise(); }; DateTime.prototype.isMorePrecise = Date.prototype.isMorePrecise = function(other) { var field, i, len, ref1; if (typeof other === 'string' && indexOf.call(this.constructor.FIELDS, other) >= 0) { if (this[other] == null) { return false; } } else { ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((other[field] != null) && (this[field] == null)) { return false; } } } return !this.isSamePrecision(other); }; DateTime.prototype.isLessPrecise = Date.prototype.isLessPrecise = function(other) { return !this.isSamePrecision(other) && !this.isMorePrecise(other); }; DateTime.prototype.isSamePrecision = Date.prototype.isSamePrecision = function(other) { var field, i, len, ref1; if (typeof other === 'string' && indexOf.call(this.constructor.FIELDS, other) >= 0) { return other === this.getPrecision(); } ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((this[field] != null) && (other[field] == null)) { return false; } if ((this[field] == null) && (other[field] != null)) { return false; } } return true; }; DateTime.prototype.equals = Date.prototype.equals = function(other) { return compareWithDefaultResult(this, other, null); }; DateTime.prototype.equivalent = Date.prototype.equivalent = function(other) { return compareWithDefaultResult(this, other, false); }; DateTime.prototype.sameAs = Date.prototype.sameAs = function(other, precision) { var field, i, len, ref1; if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().sameAs(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if ((precision != null) && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: " + precision); } if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((this[field] != null) && (other[field] != null)) { if (this[field] !== other[field]) { return false; } } else if ((this[field] == null) && (other[field] == null)) { if (precision == null) { return true; } else { return null; } } else { return null; } if ((precision != null) && precision === field) { break; } } return true; }; DateTime.prototype.sameOrBefore = Date.prototype.sameOrBefore = function(other, precision) { var field, i, len, ref1; if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().sameOrBefore(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if ((precision != null) && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: " + precision); } if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((this[field] != null) && (other[field] != null)) { if (this[field] < other[field]) { return true; } else if (this[field] > other[field]) { return false; } } else if ((this[field] == null) && (other[field] == null)) { if (precision == null) { return true; } else { return null; } } else { return null; } if ((precision != null) && precision === field) { break; } } return true; }; DateTime.prototype.sameOrAfter = Date.prototype.sameOrAfter = function(other, precision) { var field, i, len, ref1; if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().sameOrAfter(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if ((precision != null) && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: " + precision); } if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((this[field] != null) && (other[field] != null)) { if (this[field] > other[field]) { return true; } else if (this[field] < other[field]) { return false; } } else if ((this[field] == null) && (other[field] == null)) { if (precision == null) { return true; } else { return null; } } else { return null; } if ((precision != null) && precision === field) { break; } } return true; }; DateTime.prototype.before = Date.prototype.before = function(other, precision) { var field, i, len, ref1; if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().before(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if ((precision != null) && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: " + precision); } if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((this[field] != null) && (other[field] != null)) { if (this[field] < other[field]) { return true; } else if (this[field] > other[field]) { return false; } } else if ((this[field] == null) && (other[field] == null)) { if (precision == null) { return false; } else { return null; } } else { return null; } if ((precision != null) && precision === field) { break; } } return false; }; DateTime.prototype.after = Date.prototype.after = function(other, precision) { var field, i, len, ref1; if (!(other.isDate || other.isDateTime)) { return null; } else if (this.isDate && other.isDateTime) { return this.getDateTime().after(other, precision); } else if (this.isDateTime && other.isDate) { other = other.getDateTime(); } if ((precision != null) && this.constructor.FIELDS.indexOf(precision) < 0) { throw new Error("Invalid precision: " + precision); } if (this.timezoneOffset !== other.timezoneOffset) { other = other.convertToTimezoneOffset(this.timezoneOffset); } ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((this[field] != null) && (other[field] != null)) { if (this[field] > other[field]) { return true; } else if (this[field] < other[field]) { return false; } } else if ((this[field] == null) && (other[field] == null)) { if (precision == null) { return false; } else { return null; } } else { return null; } if ((precision != null) && precision === field) { break; } } return false; }; DateTime.prototype.add = Date.prototype.add = function(offset, field) { var f, fieldFloorOrCiel, i, j, k, len, len1, len2, normalized, offsetIsMorePrecise, ref1, ref2, ref3, ref4, result; result = this.copy(); if (offset === 0) { return result; } if (field === this.constructor.Unit.WEEK) { offset = offset * 7; field = this.constructor.Unit.DAY; } offsetIsMorePrecise = result[field] == null; if (offsetIsMorePrecise) { if (!this.year) { result.year = new jsDate().getFullYear(); } fieldFloorOrCiel = offset >= 0 ? this.getFieldFloor : this.getFieldCieling; ref1 = this.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { f = ref1[i]; result[f] = (ref2 = result[f]) != null ? ref2 : fieldFloorOrCiel.call(result, f); if (result[field] != null) { break; } } } result[field] = result[field] + offset; normalized = this.constructor.fromJSDate(result.toJSDate(), this.timezoneOffset); ref3 = this.constructor.FIELDS; for (j = 0, len1 = ref3.length; j < len1; j++) { field = ref3[j]; if (result[field] != null) { result[field] = normalized[field]; } } if (offsetIsMorePrecise) { ref4 = this.constructor.FIELDS; for (k = 0, len2 = ref4.length; k < len2; k++) { f = ref4[k]; if (this[f] == null) { result[f] = null; } } } return result; }; DateTime.prototype.getFieldFloor = Date.prototype.getFieldFloor = function(field) { if (field === 'month') { return 1; } if (field === 'day') { return 1; } if (field === 'hour') { return 0; } if (field === 'minute') { return 0; } if (field === 'second') { return 0; } if (field === 'millisecond') { return 0; } throw new Error('Tried to floor a field that has no floor value: ' + field); }; DateTime.prototype.getFieldCieling = Date.prototype.getFieldCieling = function(field) { if (field === 'month') { return 12; } if (field === 'day') { return daysInMonth(this.year, this.month); } if (field === 'hour') { return 23; } if (field === 'minute') { return 59; } if (field === 'second') { return 59; } if (field === 'millisecond') { return 999; } throw new Error('Tried to clieling a field that has no cieling value: ' + field); }; compareWithDefaultResult = function(a, b, defaultResult) { var aMillisecond, aSecondAndMillisecond, bMillisecond, bSecondAndMillisecond, field, i, len, ref1; if (!((a.isDate && b.isDate) || (a.isDateTime && b.isDateTime))) { return false; } if (a.timezoneOffset !== b.timezoneOffset) { b = b.convertToTimezoneOffset(a.timezoneOffset); } ref1 = a.constructor.FIELDS; for (i = 0, len = ref1.length; i < len; i++) { field = ref1[i]; if ((a[field] != null) && (b[field] != null)) { if (field === 'second') { aMillisecond = a['millisecond'] != null ? a['millisecond'] : 0; aSecondAndMillisecond = a[field] + aMillisecond / 1000; bMillisecond = b['millisecond'] != null ? b['millisecond'] : 0; bSecondAndMillisecond = b[field] + bMillisecond / 1000; return aSecondAndMillisecond === bSecondAndMillisecond; } if (a[field] !== b[field]) { return false; } } else if ((a[field] == null) && (b[field] == null)) { return true; } else { return defaultResult; } } return true; }; daysInMonth = function(year, month) { if (!((year != null) && (month != null))) { throw new Error('daysInMonth requires year and month as arguments'); } return new jsDate(year, month, 0).getDate(); }; normalizeMillisecondsField = function(msString) { return msString = (msString + "00").substring(0, 3); }; isValidDateStringFormat = function(string) { var cqlFormatStringWithLength, cqlFormats, format, i, len, strict; if (typeof string !== 'string') { return false; } cqlFormats = ['YYYY', 'YYYY-MM', 'YYYY-MM-DD']; cqlFormatStringWithLength = {}; for (i = 0, len = cqlFormats.length; i < len; i++) { format = cqlFormats[i]; cqlFormatStringWithLength[format.length] = format; } if (cqlFormatStringWithLength[string.length] == null) { return false; } strict = true; return moment(string, cqlFormatStringWithLength[string.length], strict).isValid(); }; isValidDateTimeStringFormat = function(string) { var cqlFormatStringWithLength, cqlFormats, format, i, len, strict; if (typeof string !== 'string') { return false; } cqlFormats = ['YYYY', 'YYYY-MM', 'YYYY-MM-DD', 'YYYY-MM-DDTZ', 'YYYY-MM-DDT+hh', 'YYYY-MM-DDT+hh:mm', 'YYYY-MM-DDT-hh', 'YYYY-MM-DDT-hh:mm', 'YYYY-MM-DDThh', 'YYYY-MM-DDThhZ', 'YYYY-MM-DDThh+hh', 'YYYY-MM-DDThh+hh:mm', 'YYYY-MM-DDThh-hh', 'YYYY-MM-DDThh-hh:mm', 'YYYY-MM-DDThh:mm', 'YYYY-MM-DDThh:mmZ', 'YYYY-MM-DDThh:mm+hh', 'YYYY-MM-DDThh:mm+hh:mm', 'YYYY-MM-DDThh:mm-hh', 'YYYY-MM-DDThh:mm-hh:mm', 'YYYY-MM-DDThh:mm:ss', 'YYYY-MM-DDThh:mm:ssZ', 'YYYY-MM-DDThh:mm:ss+hh', 'YYYY-MM-DDThh:mm:ss+hh:mm', 'YYYY-MM-DDThh:mm:ss-hh', 'YYYY-MM-DDThh:mm:ss-hh:mm', 'YYYY-MM-DDThh:mm:ss.fff', 'YYYY-MM-DDThh:mm:ss.fffZ', 'YYYY-MM-DDThh:mm:ss.fff+hh', 'YYYY-MM-DDThh:mm:ss.fff+hh:mm', 'YYYY-MM-DDThh:mm:ss.fff-hh', 'YYYY-MM-DDThh:mm:ss.fff-hh:mm']; cqlFormatStringWithLength = {}; for (i = 0, len = cqlFormats.length; i < len; i++) { format = cqlFormats[i]; cqlFormatStringWithLength[format.length] = format; } if (cqlFormatStringWithLength[string.length] == null) { return false; } strict = false; return moment(string, cqlFormatStringToMomentFormatString(cqlFormatStringWithLength[string.length]), strict).isValid(); }; cqlFormatStringToMomentFormatString = function(string) { var momentString, ref1, timeAndTimeZoneOffset, timezoneSeparator, yearMonthDay; ref1 = string.split('T'), yearMonthDay = ref1[0], timeAndTimeZoneOffset = ref1[1]; if (timeAndTimeZoneOffset != null) { timezoneSeparator = getTimezoneSeparatorFromString(timeAndTimeZoneOffset); } momentString = yearMonthDay; if (string.match(/T/) != null) { momentString += '[T]'; } if (!!timezoneSeparator) { momentString += timeAndTimeZoneOffset.substring(0, timeAndTimeZoneOffset.search(timezoneSeparator)) + '[Z]'; } else { momentString += timeAndTimeZoneOffset; } return momentString = momentString.replace(/f/g, 'S'); }; module.exports.DateTime = DateTime; module.exports.Date = Date; }).call(this); },{"../util/util":252,"./uncertainty":128,"moment":257}],123:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Exception; module.exports.Exception = Exception = (function() { function Exception(message, wrapped) { this.message = message; this.wrapped = wrapped; } return Exception; })(); }).call(this); },{}],124:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DateTime, Interval, Quantity, ThreeValuedLogic, Uncertainty, cmp, doSubtraction, maxValueForInstance, minValueForInstance, predecessor, ref, ref1, successor; DateTime = require('./datetime').DateTime; Uncertainty = require('./uncertainty').Uncertainty; ref = require('../datatypes/quantity'), Quantity = ref.Quantity, doSubtraction = ref.doSubtraction; ThreeValuedLogic = require('./logic').ThreeValuedLogic; ref1 = require('../util/math'), successor = ref1.successor, predecessor = ref1.predecessor, maxValueForInstance = ref1.maxValueForInstance, minValueForInstance = ref1.minValueForInstance; cmp = require('../util/comparison'); module.exports.Interval = Interval = (function() { var areDateTimes, areNumeric, highestNumericUncertainty, lowestNumericUncertainty; function Interval(low1, high1, lowClosed, highClosed) { this.low = low1; this.high = high1; this.lowClosed = lowClosed != null ? lowClosed : true; this.highClosed = highClosed != null ? highClosed : true; } Object.defineProperties(Interval.prototype, { isInterval: { get: function() { return true; } } }); Interval.prototype.copy = function() { var newHigh, newLow; newLow = this.low; newHigh = this.high; if ((this.low != null) && typeof this.low.copy === 'function') { newLow = this.low.copy(); } if ((this.high != null) && typeof this.high.copy === 'function') { newHigh = this.high.copy(); } return new Interval(newLow, newHigh, this.lowClosed, this.highClosed); }; Interval.prototype.contains = function(item, precision) { var highFn, lowFn; if (this.lowClosed && (this.low != null) && cmp.equals(this.low, item)) { return true; } if (this.highClosed && (this.high != null) && cmp.equals(this.high, item)) { return true; } if (item != null ? item.isInterval : void 0) { throw new Error("Argument to contains must be a point"); } lowFn = (function() { switch (false) { case !(this.lowClosed && (this.low == null)): return function() { return true; }; case !this.lowClosed: return cmp.lessThanOrEquals; default: return cmp.lessThan; } }).call(this); highFn = (function() { switch (false) { case !(this.highClosed && (this.high == null)): return function() { return true; }; case !this.highClosed: return cmp.greaterThanOrEquals; default: return cmp.greaterThan; } }).call(this); return ThreeValuedLogic.and(lowFn(this.low, item, precision), highFn(this.high, item, precision)); }; Interval.prototype.properlyIncludes = function(other, precision) { if (!(other != null ? other.isInterval : void 0)) { throw new Error("Argument to properlyIncludes must be an interval"); } return ThreeValuedLogic.and(this.includes(other, precision), ThreeValuedLogic.not(other.includes(this, precision))); }; Interval.prototype.includes = function(other, precision) { var a, b; if (!(other != null ? other.isInterval : void 0)) { return this.contains(other, precision); } a = this.toClosed(); b = other.toClosed(); return ThreeValuedLogic.and(cmp.lessThanOrEquals(a.low, b.low, precision), cmp.greaterThanOrEquals(a.high, b.high, precision)); }; Interval.prototype.includedIn = function(other, precision) { if (!(other != null ? other.isInterval : void 0)) { return this.contains(other, precision); } else { return other.includes(this); } }; Interval.prototype.overlaps = function(item, precision) { var closed, high, itemClosed, low, ref2; closed = this.toClosed(); ref2 = (item != null ? item.isInterval : void 0) ? (itemClosed = item.toClosed(), [itemClosed.low, itemClosed.high]) : [item, item], low = ref2[0], high = ref2[1]; return ThreeValuedLogic.and(cmp.lessThanOrEquals(closed.low, high, precision), cmp.greaterThanOrEquals(closed.high, low, precision)); }; Interval.prototype.overlapsAfter = function(item, precision) { var closed, high; closed = this.toClosed(); high = (item != null ? item.isInterval : void 0) ? item.toClosed().high : item; return ThreeValuedLogic.and(cmp.lessThanOrEquals(closed.low, high, precision), cmp.greaterThan(closed.high, high, precision)); }; Interval.prototype.overlapsBefore = function(item, precision) { var closed, low; closed = this.toClosed(); low = (item != null ? item.isInterval : void 0) ? item.toClosed().low : item; return ThreeValuedLogic.and(cmp.lessThan(closed.low, low, precision), cmp.greaterThanOrEquals(closed.high, low, precision)); }; areDateTimes = function(x, y) { return [x, y].every(function(z) { return z != null ? z.isDateTime : void 0; }); }; areNumeric = function(x, y) { return [x, y].every(function(z) { return typeof z === 'number' || ((z != null ? z.isUncertainty : void 0) && typeof z.low === 'number'); }); }; lowestNumericUncertainty = function(x, y) { var high, low; if (!(x != null ? x.isUncertainty : void 0)) { x = new Uncertainty(x); } if (!(y != null ? y.isUncertainty : void 0)) { y = new Uncertainty(y); } low = x.low < y.low ? x.low : y.low; high = x.high < y.high ? x.high : y.high; if (low !== high) { return new Uncertainty(low, high); } else { return low; } }; highestNumericUncertainty = function(x, y) { var high, low; if (!(x != null ? x.isUncertainty : void 0)) { x = new Uncertainty(x); } if (!(y != null ? y.isUncertainty : void 0)) { y = new Uncertainty(y); } low = x.low > y.low ? x.low : y.low; high = x.high > y.high ? x.high : y.high; if (low !== high) { return new Uncertainty(low, high); } else { return low; } }; Interval.prototype.union = function(other) { var a, b, h, hc, l, lc, ref2, ref3, ref4; if (!(other != null ? other.isInterval : void 0)) { throw new Error("Argument to union must be an interval"); } if (this.overlaps(other) || this.meets(other)) { ref2 = [this.toClosed(), other.toClosed()], a = ref2[0], b = ref2[1]; ref3 = (function() { switch (false) { case !cmp.lessThanOrEquals(a.low, b.low): return [this.low, this.lowClosed]; case !cmp.greaterThanOrEquals(a.low, b.low): return [other.low, other.lowClosed]; case !areNumeric(a.low, b.low): return [lowestNumericUncertainty(a.low, b.low), true]; case !(areDateTimes(a.low, b.low) && a.low.isMorePrecise(b.low)): return [other.low, other.lowClosed]; default: return [this.low, this.lowClosed]; } }).call(this), l = ref3[0], lc = ref3[1]; ref4 = (function() { switch (false) { case !cmp.greaterThanOrEquals(a.high, b.high): return [this.high, this.highClosed]; case !cmp.lessThanOrEquals(a.high, b.high): return [other.high, other.highClosed]; case !areNumeric(a.high, b.high): return [highestNumericUncertainty(a.high, b.high), true]; case !(areDateTimes(a.high, b.high) && a.high.isMorePrecise(b.high)): return [other.high, other.highClosed]; default: return [this.high, this.highClosed]; } }).call(this), h = ref4[0], hc = ref4[1]; return new Interval(l, h, lc, hc); } else { return null; } }; Interval.prototype.intersect = function(other) { var a, b, h, hc, l, lc, ref2, ref3, ref4; if (!(other != null ? other.isInterval : void 0)) { throw new Error("Argument to union must be an interval"); } if (this.overlaps(other)) { ref2 = [this.toClosed(), other.toClosed()], a = ref2[0], b = ref2[1]; ref3 = (function() { switch (false) { case !cmp.greaterThanOrEquals(a.low, b.low): return [this.low, this.lowClosed]; case !cmp.lessThanOrEquals(a.low, b.low): return [other.low, other.lowClosed]; case !areNumeric(a.low, b.low): return [highestNumericUncertainty(a.low, b.low), true]; case !(areDateTimes(a.low, b.low) && b.low.isMorePrecise(a.low)): return [other.low, other.lowClosed]; default: return [this.low, this.lowClosed]; } }).call(this), l = ref3[0], lc = ref3[1]; ref4 = (function() { switch (false) { case !cmp.lessThanOrEquals(a.high, b.high): return [this.high, this.highClosed]; case !cmp.greaterThanOrEquals(a.high, b.high): return [other.high, other.highClosed]; case !areNumeric(a.high, b.high): return [lowestNumericUncertainty(a.high, b.high), true]; case !(areDateTimes(a.high, b.high) && b.high.isMorePrecise(a.high)): return [other.high, other.highClosed]; default: return [this.high, this.highClosed]; } }).call(this), h = ref4[0], hc = ref4[1]; return new Interval(l, h, lc, hc); } else { return null; } }; Interval.prototype.except = function(other) { var ol, ola, olb; if (other === null) { return null; } if (!(other != null ? other.isInterval : void 0)) { throw new Error("Argument to except must be an interval"); } ol = this.overlaps(other); if (ol === true) { olb = this.overlapsBefore(other); ola = this.overlapsAfter(other); if (olb === true && ola === false) { return new Interval(this.low, other.low, this.lowClosed, !other.lowClosed); } else if (ola === true && olb === false) { return new Interval(other.high, this.high, !other.highClosed, this.highClosed); } else { return null; } } else if (ol === false) { return this; } else { return null; } }; Interval.prototype.sameAs = function(other, precision) { if (((this.low != null) && (other.low != null) && (this.high == null) && (other.high != null) && !this.highClosed) || ((this.low != null) && (other.low != null) && (this.high != null) && (other.high == null) && !other.highClosed) || ((this.low != null) && (other.low != null) && (this.high == null) && (other.high == null) && !other.highClosed && !this.highClosed)) { if (typeof this.low === 'number') { if (!(this.start() === other.start())) { return false; } } else { if (!(this.start().sameAs(other.start(), precision))) { return false; } } } else if (((this.low != null) && (other.low == null) && (this.high != null) && (other.high != null)) || ((this.low == null) && (other.low != null) && (this.high != null) && (other.high != null)) || ((this.low == null) && (other.low == null) && (this.high != null) && (other.high != null))) { if (typeof this.high === 'number') { if (!(this.end() === other.end())) { return false; } } else { if (!(this.end().sameAs(other.end(), precision))) { return false; } } } if (((this.low == null) && !this.lowClosed) || ((this.high == null) && !this.highClosed) || ((other.low == null) && !other.lowClosed) || ((other.high == null) && !other.highClosed)) { return null; } if (this.lowClosed && (this.low == null) && this.highClosed && (this.high == null)) { return other.lowClosed && (other.low == null) && other.highClosed && (other.high == null); } if (other.lowClosed && (other.low == null) && other.highClosed && (other.high == null)) { return false; } if (typeof this.low === 'number') { return this.start() === other.start() && this.end() === other.end(); } else { return this.start().sameAs(other.start(), precision) && this.end().sameAs(other.end(), precision); } }; Interval.prototype.sameOrBefore = function(other, precision) { if ((this.end() == null) || ((other != null ? other.start() : void 0) == null)) { return null; } else { return this.end().sameOrBefore(other.start(), precision); } }; Interval.prototype.sameOrAfter = function(other, precision) { if ((this.start() == null) || ((other != null ? other.end() : void 0) == null)) { return null; } else { return this.start().sameOrAfter(other.end(), precision); } }; Interval.prototype.equals = function(other) { var a, b, ref2; if (other != null ? other.isInterval : void 0) { ref2 = [this.toClosed(), other.toClosed()], a = ref2[0], b = ref2[1]; return ThreeValuedLogic.and(cmp.equals(a.low, b.low), cmp.equals(a.high, b.high)); } else { return false; } }; Interval.prototype.after = function(other, precision) { var closed; closed = this.toClosed(); if (!!other.toClosed) { return cmp.greaterThan(closed.low, other.toClosed().high, precision); } else { return cmp.greaterThan(closed.low, other, precision); } }; Interval.prototype.before = function(other, precision) { var closed; closed = this.toClosed(); if (!!other.toClosed) { return cmp.lessThan(closed.high, other.toClosed().low, precision); } else { return cmp.lessThan(closed.high, other, precision); } }; Interval.prototype.meets = function(other, precision) { return ThreeValuedLogic.or(this.meetsBefore(other, precision), this.meetsAfter(other, precision)); }; Interval.prototype.meetsAfter = function(other, precision) { var ref2, ref3; try { if ((precision != null) && ((ref2 = this.low) != null ? ref2.isDateTime : void 0)) { return this.toClosed().low.sameAs((ref3 = other.toClosed().high) != null ? ref3.add(1, precision) : void 0, precision); } else { return cmp.equals(this.toClosed().low, successor(other.toClosed().high)); } } catch (error) { return false; } }; Interval.prototype.meetsBefore = function(other, precision) { var ref2, ref3; try { if ((precision != null) && ((ref2 = this.high) != null ? ref2.isDateTime : void 0)) { return this.toClosed().high.sameAs((ref3 = other.toClosed().low) != null ? ref3.add(-1, precision) : void 0, precision); } else { return cmp.equals(this.toClosed().high, predecessor(other.toClosed().low)); } } catch (error) { return false; } }; Interval.prototype.start = function() { if (this.low == null) { if (this.lowClosed) { return minValueForInstance(this.high); } else { return this.low; } } return this.toClosed().low; }; Interval.prototype.end = function() { if (this.high == null) { if (this.highClosed) { return maxValueForInstance(this.low); } else { return this.high; } } return this.toClosed().high; }; Interval.prototype.starts = function(other, precision) { var endLessThanOrEqual, ref2, startEqual; if ((precision != null) && ((ref2 = this.low) != null ? ref2.isDateTime : void 0)) { startEqual = this.low.sameAs(other.low, precision); } else { startEqual = cmp.equals(this.low, other.low); } endLessThanOrEqual = cmp.lessThanOrEquals(this.high, other.high, precision); return startEqual && endLessThanOrEqual; }; Interval.prototype.ends = function(other, precision) { var endEqual, ref2, startGreaterThanOrEqual; startGreaterThanOrEqual = cmp.greaterThanOrEquals(this.low, other.low, precision); if ((precision != null) && ((ref2 = this.low) != null ? ref2.isDateTime : void 0)) { endEqual = this.high.sameAs(other.high, precision); } else { endEqual = cmp.equals(this.high, other.high); } return startGreaterThanOrEqual && endEqual; }; Interval.prototype.width = function() { var closed, diff, highValue, lowValue, ref2, ref3; if (((this.low != null) && (this.low.isDateTime || this.low.isDate || this.low.isTime)) || ((this.high != null) && (this.high.isDateTime || this.high.isDate || this.high.isTime))) { throw new Error("Width of Date, DateTime, and Time intervals is not supported"); } closed = this.toClosed(); if (((ref2 = closed.low) != null ? ref2.isUncertainty : void 0) || ((ref3 = closed.high) != null ? ref3.isUncertainty : void 0)) { return null; } else if (closed.low.isQuantity) { if (closed.low.unit !== closed.high.unit) { throw new Error("Cannot calculate width of Quantity Interval with different units"); } lowValue = closed.low.value; highValue = closed.high.value; diff = Math.abs(highValue - lowValue); Math.round(diff * Math.pow(10, 8)) / Math.pow(10, 8); return new Quantity(diff, closed.low.unit); } else { diff = Math.abs(closed.high - closed.low); return Math.round(diff * Math.pow(10, 8)) / Math.pow(10, 8); } }; Interval.prototype.size = function() { var closed, diff, highValue, lowValue, pointSize, ref2, ref3; pointSize = this.getPointSize(); if (((this.low != null) && (this.low.isDateTime || this.low.isDate || this.low.isTime)) || ((this.high != null) && (this.high.isDateTime || this.high.isDate || this.high.isTime))) { throw new Error("Size of Date, DateTime, and Time intervals is not supported"); } closed = this.toClosed(); if (((ref2 = closed.low) != null ? ref2.isUncertainty : void 0) || ((ref3 = closed.high) != null ? ref3.isUncertainty : void 0)) { return null; } else if (closed.low.isQuantity) { if (closed.low.unit !== closed.high.unit) { throw new Error("Cannot calculate size of Quantity Interval with different units"); } lowValue = closed.low.value; highValue = closed.high.value; diff = Math.abs(highValue - lowValue) + pointSize.value; Math.round(diff * Math.pow(10, 8)) / Math.pow(10, 8); return new Quantity(diff, closed.low.unit); } else { diff = Math.abs(closed.high - closed.low) + pointSize.value; return Math.round(diff * Math.pow(10, 8)) / Math.pow(10, 8); } }; Interval.prototype.getPointSize = function() { var pointSize, precisionUnits; if (this.low != null) { if (this.low.isDateTime) { precisionUnits = this.low.getPrecision(); pointSize = new Quantity(1, precisionUnits); } else if (this.low.isQuantity) { pointSize = doSubtraction(successor(this.low), this.low); } else { pointSize = successor(this.low) - this.low; } } else if (this.high != null) { if (this.high.isDateTime) { precisionUnits = this.high.getPrecision(); pointSize = new Quantity(1, precisionUnits); } else if (this.high.isQuantity) { pointSize = doSubtraction(successor(this.high), this.high); } else { pointSize = successor(this.high) - this.high; } } else { throw new Error("Point type of intervals cannot be determined."); } if (typeof pointSize === 'number') { pointSize = new Quantity(pointSize, '1'); } return pointSize; }; Interval.prototype.toClosed = function() { var high, low, point, ref2; point = (ref2 = this.low) != null ? ref2 : this.high; if (typeof point === 'number' || (point != null ? point.isDateTime : void 0) || (point != null ? point.isQuantity : void 0) || (point != null ? point.isDate : void 0)) { low = (function() { switch (false) { case !(this.lowClosed && (this.low == null)): return minValueForInstance(point); case !(!this.lowClosed && (this.low != null)): return successor(this.low); default: return this.low; } }).call(this); high = (function() { switch (false) { case !(this.highClosed && (this.high == null)): return maxValueForInstance(point); case !(!this.highClosed && (this.high != null)): return predecessor(this.high); default: return this.high; } }).call(this); if (low == null) { low = new Uncertainty(minValueForInstance(point), high); } if (high == null) { high = new Uncertainty(low, maxValueForInstance(point)); } return new Interval(low, high, true, true); } else { return new Interval(this.low, this.high, true, true); } }; Interval.prototype.toString = function() { var end, start; start = this.lowClosed ? '[' : '('; end = this.highClosed ? ']' : ')'; return start + this.low.toString() + ', ' + this.high.toString() + end; }; return Interval; })(); }).call(this); },{"../datatypes/quantity":126,"../util/comparison":250,"../util/math":251,"./datetime":122,"./logic":125,"./uncertainty":128}],125:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var ThreeValuedLogic, slice = [].slice, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; module.exports.ThreeValuedLogic = ThreeValuedLogic = (function() { function ThreeValuedLogic() {} ThreeValuedLogic.and = function() { var val; val = 1 <= arguments.length ? slice.call(arguments, 0) : []; if (indexOf.call(val, false) >= 0) { return false; } else if (indexOf.call(val, null) >= 0) { return null; } else { return true; } }; ThreeValuedLogic.or = function() { var val; val = 1 <= arguments.length ? slice.call(arguments, 0) : []; if (indexOf.call(val, true) >= 0) { return true; } else if (indexOf.call(val, null) >= 0) { return null; } else { return false; } }; ThreeValuedLogic.xor = function() { var val; val = 1 <= arguments.length ? slice.call(arguments, 0) : []; if (indexOf.call(val, null) >= 0) { return null; } else { return val.reduce(function(a, b) { return (!a ^ !b) === 1; }); } }; ThreeValuedLogic.not = function(val) { if (val != null) { return !val; } else { return null; } }; return ThreeValuedLogic; })(); }).call(this); },{}],126:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Quantity, clean_unit, coalesceToOne, convert_value, decimalAdjust, doScaledAddition, isValidDecimal, is_valid_ucum_unit, ref, ucum, ucum_multiply, ucum_time_units, ucum_to_cql_units, ucum_unit, unitValidityCache, units_to_string; ref = require('../util/math'), decimalAdjust = ref.decimalAdjust, isValidDecimal = ref.isValidDecimal; ucum = require('ucum'); module.exports.Quantity = Quantity = (function() { Object.defineProperties(Quantity.prototype, { isQuantity: { get: function() { return true; } } }); function Quantity(value1, unit1) { this.value = value1; this.unit = unit1; if ((this.value == null) || isNaN(this.value)) { throw new Error("Cannot create a quantity with an undefined value"); } else { if (!isValidDecimal(this.value)) { throw new Error("Cannot create a quantity with an invalid decimal value"); } } if ((this.unit != null) && !is_valid_ucum_unit(this.unit)) { throw new Error("\'" + this.unit + "\' is not a valid UCUM unit."); } } Quantity.prototype.clone = function() { return new Quantity(this.value, this.unit); }; Quantity.prototype.toString = function() { return this.value + " '" + this.unit + "'"; }; Quantity.prototype.sameOrBefore = function(other) { var other_v; if (other != null ? other.isQuantity : void 0) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); if (other_v == null) { return null; } else { return this.value <= other_v; } } }; Quantity.prototype.sameOrAfter = function(other) { var other_v; if (other != null ? other.isQuantity : void 0) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); if (other_v == null) { return null; } else { return this.value >= other_v; } } }; Quantity.prototype.after = function(other) { var other_v; if (other != null ? other.isQuantity : void 0) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); if (other_v == null) { return null; } else { return this.value > other_v; } } }; Quantity.prototype.before = function(other) { var other_v; if (other != null ? other.isQuantity : void 0) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); if (other_v == null) { return null; } else { return this.value < other_v; } } }; Quantity.prototype.equals = function(other) { var other_v; if (other != null ? other.isQuantity : void 0) { if ((!this.unit && other.unit) || (this.unit && !other.unit)) { return false; } else if (!this.unit && !other.unit) { return this.value === other.value; } else { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); if (other_v == null) { return null; } else { return decimalAdjust("round", this.value, -8) === decimalAdjust("round", other_v, -8); } } } }; Quantity.prototype.convertUnit = function(to_unit) { var unit, value; value = convert_value(this.value, this.unit, to_unit); unit = to_unit; return new Quantity(value, unit); }; Quantity.prototype.dividedBy = function(other) { return this.multiplyDivide(other, "/"); }; Quantity.prototype.multiplyBy = function(other) { return this.multiplyDivide(other, "."); }; Quantity.prototype.multiplyDivide = function(other, operator) { var a, b, can_val, other_can_value, ucum_value, value; if (other != null ? other.isQuantity : void 0) { a = this.unit != null ? this : new Quantity(this.value, '1'); b = other.unit != null ? other : new Quantity(other.value, { unit: '1' }); can_val = a.to_ucum(); other_can_value = b.to_ucum(); ucum_value = ucum_multiply(can_val, [[operator, other_can_value]]); try { return new Quantity(ucum_value.value, units_to_string(ucum_value.units)); } catch (error) { return null; } } else { value = operator === "/" ? this.value / other : this.value * other; try { return new Quantity(decimalAdjust("round", value, -8), coalesceToOne(this.unit)); } catch (error) { return null; } } }; Quantity.prototype.to_ucum = function() { var u; u = ucum.parse(ucum_unit(this.unit)); u.value *= this.value; return u; }; return Quantity; })(); clean_unit = function(units) { if (ucum_time_units[units]) { return ucum_to_cql_units[ucum_time_units[units]]; } else { return units; } }; ucum_time_units = { 'years': 'a_g', 'year': 'a_g', 'YEARS': 'a_g', 'YEAR': 'a_g', 'a_g': 'a_g', 'a': 'a_j', 'ANN': 'a_j', 'ann': 'a_j', 'A': 'a_j', 'a_j': 'a_j', 'months': 'mo_g', 'month': 'mo_g', 'mo_g': 'mo_g', 'mo': 'mo_j', 'MO': 'mo_j', 'mo_j': 'mo_j', 'weeks': 'wk', 'week': 'wk', 'wk': 'wk', 'WK': 'wk', 'days': 'd', 'day': 'd', 'd': 'd', 'D': 'd', 'hours': 'h', 'hour': 'h', 'h': 'h', 'H': 'h', 'minutes': 'min', 'minute': 'min', 'min': 'min', 'MIN': 'min', 'seconds': 's', 'second': 's', 's': 's', 'S': 's', 'milliseconds': 'ms', 'millisecond': 'ms', 'ms': 'ms', 'MS': 'ms' }; ucum_to_cql_units = { 'a_j': 'year', 'a_g': 'year', 'mo_j': 'month', 'mo_g': 'month', 'wk': 'week', 'd': 'day', 'h': 'hour', 'min': 'minute', 's': 'second', 'ms': 'millisecond' }; ucum_unit = function(unit) { return ucum_time_units[unit] || unit || ''; }; convert_value = function(value, from, to) { var e; try { if (from === to) { return value; } else { return decimalAdjust("round", ucum.convert(value, ucum_unit(from), ucum_unit(to)), -8); } } catch (error) { e = error; return null; } }; unitValidityCache = {}; is_valid_ucum_unit = function(unit) { if (unitValidityCache.hasOwnProperty(unit)) { return unitValidityCache[unit]; } else { try { ucum.parse(ucum_unit(unit)); unitValidityCache[unit] = true; return true; } catch (error) { unitValidityCache[unit] = false; return false; } } }; module.exports.convert_value = convert_value; units_to_string = function(units) { var denom, i, key, len, numer, pow, ref1, str, unit_string, v; if (units == null) { units = {}; } numer = []; denom = []; ref1 = Object.keys(units); for (i = 0, len = ref1.length; i < len; i++) { key = ref1[i]; v = units[key]; pow = Math.abs(v); str = pow === 1 ? key : key + pow; if (v < 0) { denom.push(str); } else { numer.push(str); } } unit_string = ""; unit_string += numer.join("."); if (denom.length > 0) { unit_string += "/" + denom.join("/"); } if (unit_string === "") { return "1"; } else { return unit_string; } }; ucum_multiply = function(t, ms) { var b, i, k, len, mterm, ref1, ret, sign, v; if (ms == null) { ms = []; } if (ms.length === 0) { return t; } ret = t; for (i = 0, len = ms.length; i < len; i++) { mterm = ms[i]; sign = mterm[0] === '.' ? 1 : -1; b = mterm[1]; ret.value *= Math.pow(b.value, sign); ref1 = b.units; for (k in ref1) { v = ref1[k]; ret.units[k] = ret.units[k] || 0; ret.units[k] = ret.units[k] + sign * v; if (ret.units[k] === 0) { delete ret.units[k]; } } } return ret; }; module.exports.parseQuantity = function(str) { var components, unit, value; components = /([+|-]?\d+\.?\d*)\s*('(.+)')?/.exec(str); if ((components != null) && (components[1] != null)) { value = parseFloat(components[1]); if (!isValidDecimal(value)) { return null; } if (components[3] != null) { unit = components[3].trim(); } else { unit = ""; } return new Quantity(value, unit); } else { return null; } }; doScaledAddition = function(a, b, scaleForB) { var a_unit, b_unit, ref1, val; if ((a != null ? a.isQuantity : void 0) && (b != null ? b.isQuantity : void 0)) { ref1 = [coalesceToOne(a.unit), coalesceToOne(b.unit)], a_unit = ref1[0], b_unit = ref1[1]; val = convert_value(b.value * scaleForB, b_unit, a_unit); if (val == null) { return null; } return new Quantity(a.value + val, a_unit); } else if (a.copy && a.add) { b_unit = (b != null ? b.isQuantity : void 0) ? coalesceToOne(b.unit) : b.unit; return a.copy().add(b.value * scaleForB, clean_unit(b_unit)); } else { throw new Error("Unsupported argument types."); } }; module.exports.doAddition = function(a, b) { return doScaledAddition(a, b, 1); }; module.exports.doSubtraction = function(a, b) { return doScaledAddition(a, b, -1); }; module.exports.doDivision = function(a, b) { if (a != null ? a.isQuantity : void 0) { return a.dividedBy(b); } }; module.exports.doMultiplication = function(a, b) { if (a != null ? a.isQuantity : void 0) { return a.multiplyBy(b); } else { return b.multiplyBy(a); } }; coalesceToOne = function(o) { if ((o == null) || ((o.trim != null) && !o.trim())) { return '1'; } else { return o; } }; module.exports.compare_units = function(unit_a, unit_b) { var c, e; try { c = ucum.convert(1, ucum_unit(unit_a), ucum_unit(unit_b)); if (c > 1) { return 1; } if (c < 1) { return -1; } return 0; } catch (error) { e = error; return null; } }; }).call(this); },{"../util/math":251,"ucum":411}],127:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Ratio; module.exports.Ratio = Ratio = (function() { function Ratio(numerator, denominator) { this.numerator = numerator; this.denominator = denominator; if (this.numerator == null) { throw new Error("Cannot create a ratio with an undefined numerator"); } if (this.denominator == null) { throw new Error("Cannot create a ratio with an undefined denominator"); } } Object.defineProperties(Ratio.prototype, { isRatio: { get: function() { return true; } } }); Ratio.prototype.clone = function() { return new Ratio(this.numerator.clone(), this.denominator.clone()); }; Ratio.prototype.toString = function() { return (this.numerator.toString()) + " : " + (this.denominator.toString()); }; Ratio.prototype.equals = function(other) { var divided_other, divided_this; if (other != null ? other.isRatio : void 0) { divided_this = this.numerator.dividedBy(this.denominator); divided_other = other.numerator.dividedBy(other.denominator); return divided_this.equals(divided_other); } else { return false; } }; Ratio.prototype.equivalent = function(other) { var equal; equal = this.equals(other); if (equal == null) { return false; } return equal; }; return Ratio; })(); }).call(this); },{}],128:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var ThreeValuedLogic, Uncertainty; ThreeValuedLogic = require('./logic').ThreeValuedLogic; module.exports.Uncertainty = Uncertainty = (function() { Uncertainty.from = function(obj) { if (obj != null ? obj.isUncertainty : void 0) { return obj; } else { return new Uncertainty(obj); } }; function Uncertainty(low, high) { var gt, isNonEnumerable, ref; this.low = low != null ? low : null; this.high = high; gt = function(a, b) { if (typeof a !== typeof b) { return false; } if (typeof a.after === 'function') { return a.after(b); } else { return a > b; } }; isNonEnumerable = function(val) { return (val != null) && (val.isCode || val.isConcept || val.isValueSet); }; if (typeof this.high === 'undefined') { this.high = this.low; } if (isNonEnumerable(this.low) || isNonEnumerable(this.high)) { this.low = this.high = null; } if ((this.low != null) && (this.high != null) && gt(this.low, this.high)) { ref = [this.high, this.low], this.low = ref[0], this.high = ref[1]; } } Object.defineProperties(Uncertainty.prototype, { isUncertainty: { get: function() { return true; } } }); Uncertainty.prototype.copy = function() { var newHigh, newLow; newLow = this.low; newHigh = this.high; if (typeof this.low.copy === 'function') { newLow = this.low.copy(); } if (typeof this.high.copy === 'function') { newHigh = this.high.copy(); } return new Uncertainty(newLow, newHigh); }; Uncertainty.prototype.isPoint = function() { var gte, lte; lte = function(a, b) { if (typeof a !== typeof b) { return false; } if (typeof a.sameOrBefore === 'function') { return a.sameOrBefore(b); } else { return a <= b; } }; gte = function(a, b) { if (typeof a !== typeof b) { return false; } if (typeof a.sameOrBefore === 'function') { return a.sameOrAfter(b); } else { return a >= b; } }; return (this.low != null) && (this.high != null) && lte(this.low, this.high) && gte(this.low, this.high); }; Uncertainty.prototype.equals = function(other) { other = Uncertainty.from(other); return ThreeValuedLogic.not(ThreeValuedLogic.or(this.lessThan(other), this.greaterThan(other))); }; Uncertainty.prototype.lessThan = function(other) { var bestCase, lt, worstCase; lt = function(a, b) { if (typeof a !== typeof b) { return false; } if (typeof a.before === 'function') { return a.before(b); } else { return a < b; } }; other = Uncertainty.from(other); bestCase = (this.low == null) || (other.high == null) || lt(this.low, other.high); worstCase = (this.high != null) && (other.low != null) && lt(this.high, other.low); if (bestCase === worstCase) { return bestCase; } else { return null; } }; Uncertainty.prototype.greaterThan = function(other) { other = Uncertainty.from(other); return other.lessThan(this); }; Uncertainty.prototype.lessThanOrEquals = function(other) { other = Uncertainty.from(other); return ThreeValuedLogic.not(this.greaterThan(other)); }; Uncertainty.prototype.greaterThanOrEquals = function(other) { other = Uncertainty.from(other); return ThreeValuedLogic.not(this.lessThan(other)); }; return Uncertainty; })(); }).call(this); },{"./logic":125}],129:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var AggregateExpression, AllTrue, AnyTrue, Avg, Count, Exception, Expression, GeometricMean, Max, Median, Min, Mode, PopulationStdDev, PopulationVariance, Product, Quantity, StdDev, Sum, Variance, allTrue, anyTrue, build, convertAllUnits, doAddition, doMultiplication, getValuesFromQuantities, greaterThan, hasOnlyQuantities, hasSomeQuantities, lessThan, medianOfNumbers, numerical_sort, processQuantities, ref, ref1, ref2, removeNulls, typeIsArray, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; Expression = require('./expression').Expression; ref = require('../util/util'), typeIsArray = ref.typeIsArray, allTrue = ref.allTrue, anyTrue = ref.anyTrue, removeNulls = ref.removeNulls, numerical_sort = ref.numerical_sort; build = require('./builder').build; Exception = require('../datatypes/exception').Exception; ref1 = require('../util/comparison'), greaterThan = ref1.greaterThan, lessThan = ref1.lessThan; ref2 = require('../datatypes/quantity'), Quantity = ref2.Quantity, doAddition = ref2.doAddition, doMultiplication = ref2.doMultiplication; AggregateExpression = (function(superClass) { extend(AggregateExpression, superClass); function AggregateExpression(json) { AggregateExpression.__super__.constructor.apply(this, arguments); this.source = build(json.source); } return AggregateExpression; })(Expression); module.exports.Count = Count = (function(superClass) { extend(Count, superClass); function Count(json) { Count.__super__.constructor.apply(this, arguments); } Count.prototype.exec = function(ctx) { var items; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } return removeNulls(items).length; }; return Count; })(AggregateExpression); module.exports.Sum = Sum = (function(superClass) { extend(Sum, superClass); function Sum(json) { Sum.__super__.constructor.apply(this, arguments); } Sum.prototype.exec = function(ctx) { var e, items, sum, values; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (error) { e = error; return null; } if (!(items.length > 0)) { return null; } if (hasOnlyQuantities(items)) { values = getValuesFromQuantities(items); sum = values.reduce(function(x, y) { return x + y; }); return new Quantity(sum, items[0].unit); } else { return items.reduce(function(x, y) { return x + y; }); } }; return Sum; })(AggregateExpression); module.exports.Min = Min = (function(superClass) { extend(Min, superClass); function Min(json) { Min.__super__.constructor.apply(this, arguments); } Min.prototype.exec = function(ctx) { var e, element, i, len, list, listWithoutNulls, minimum; list = this.source.execute(ctx); if (list == null) { return null; } listWithoutNulls = removeNulls(list); try { processQuantities(list); } catch (error) { e = error; return null; } if (!(listWithoutNulls.length > 0)) { return null; } minimum = listWithoutNulls[0]; for (i = 0, len = listWithoutNulls.length; i < len; i++) { element = listWithoutNulls[i]; if (lessThan(element, minimum)) { minimum = element; } } return minimum; }; return Min; })(AggregateExpression); module.exports.Max = Max = (function(superClass) { extend(Max, superClass); function Max(json) { Max.__super__.constructor.apply(this, arguments); } Max.prototype.exec = function(ctx) { var e, element, i, items, len, listWithoutNulls, maximum; items = this.source.execute(ctx); if (items == null) { return null; } listWithoutNulls = removeNulls(items); try { processQuantities(items); } catch (error) { e = error; return null; } if (!(listWithoutNulls.length > 0)) { return null; } maximum = listWithoutNulls[0]; for (i = 0, len = listWithoutNulls.length; i < len; i++) { element = listWithoutNulls[i]; if (greaterThan(element, maximum)) { maximum = element; } } return maximum; }; return Max; })(AggregateExpression); module.exports.Avg = Avg = (function(superClass) { extend(Avg, superClass); function Avg(json) { Avg.__super__.constructor.apply(this, arguments); } Avg.prototype.exec = function(ctx) { var e, items, sum, values; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (error) { e = error; return null; } if (items.length === 0) { return null; } if (hasOnlyQuantities(items)) { values = getValuesFromQuantities(items); sum = values.reduce(function(x, y) { return x + y; }); return new Quantity(sum / values.length, items[0].unit); } else { sum = items.reduce(function(x, y) { return x + y; }); return sum / items.length; } }; return Avg; })(AggregateExpression); module.exports.Median = Median = (function(superClass) { extend(Median, superClass); function Median(json) { Median.__super__.constructor.apply(this, arguments); } Median.prototype.exec = function(ctx) { var e, items, median, values; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } if (!(items.length > 0)) { return null; } try { items = processQuantities(items); } catch (error) { e = error; return null; } if (!hasOnlyQuantities(items)) { return medianOfNumbers(items); } values = getValuesFromQuantities(items); median = medianOfNumbers(values); return new Quantity(median, items[0].unit); }; return Median; })(AggregateExpression); module.exports.Mode = Mode = (function(superClass) { extend(Mode, superClass); function Mode(json) { Mode.__super__.constructor.apply(this, arguments); } Mode.prototype.exec = function(ctx) { var e, filtered, items, mode, values; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } if (!(items.length > 0)) { return null; } try { filtered = processQuantities(items); } catch (error) { e = error; return null; } if (hasOnlyQuantities(filtered)) { values = getValuesFromQuantities(filtered); mode = this.mode(values); if (mode.length === 1) { mode = mode[0]; } return new Quantity(mode, items[0].unit); } else { mode = this.mode(filtered); if (mode.length === 1) { return mode[0]; } else { return mode; } } }; Mode.prototype.mode = function(arr) { var cnt, counts, elem, i, len, max, ref3, results; max = 0; counts = {}; results = []; for (i = 0, len = arr.length; i < len; i++) { elem = arr[i]; cnt = counts[elem] = ((ref3 = counts[elem]) != null ? ref3 : 0) + 1; if (cnt === max && indexOf.call(results, elem) < 0) { results.push(elem); } else if (cnt > max) { results = [elem]; max = cnt; } } return results; }; return Mode; })(AggregateExpression); module.exports.StdDev = StdDev = (function(superClass) { extend(StdDev, superClass); function StdDev(json) { StdDev.__super__.constructor.apply(this, arguments); this.type = "standard_deviation"; } StdDev.prototype.exec = function(ctx) { var e, items, stdDev, values; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (error) { e = error; return null; } if (!(items.length > 0)) { return null; } if (hasOnlyQuantities(items)) { values = getValuesFromQuantities(items); stdDev = this.standardDeviation(values); return new Quantity(stdDev, items[0].unit); } else { return this.standardDeviation(items); } }; StdDev.prototype.standardDeviation = function(list) { var val; val = this.stats(list); if (val) { return val[this.type]; } }; StdDev.prototype.stats = function(list) { var i, len, mean, pop_dev, pop_var, sq, std_dev, std_var, sum, sumOfSquares; sum = list.reduce(function(x, y) { return x + y; }); mean = sum / list.length; sumOfSquares = 0; for (i = 0, len = list.length; i < len; i++) { sq = list[i]; sumOfSquares += Math.pow(sq - mean, 2); } std_var = (1 / list.length) * sumOfSquares; pop_var = (1 / (list.length - 1)) * sumOfSquares; std_dev = Math.sqrt(std_var); pop_dev = Math.sqrt(pop_var); return { standard_variance: std_var, population_variance: pop_var, standard_deviation: std_dev, population_deviation: pop_dev }; }; return StdDev; })(AggregateExpression); module.exports.Product = Product = (function(superClass) { extend(Product, superClass); function Product(json) { Product.__super__.constructor.apply(this, arguments); } Product.prototype.exec = function(ctx) { var e, items, product, values; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (error) { e = error; return null; } if (!(items.length > 0)) { return null; } if (hasOnlyQuantities(items)) { values = getValuesFromQuantities(items); product = values.reduce(function(x, y) { return x * y; }); return new Quantity(product, items[0].unit); } else { return items.reduce(function(x, y) { return x * y; }); } }; return Product; })(AggregateExpression); module.exports.GeometricMean = GeometricMean = (function(superClass) { extend(GeometricMean, superClass); function GeometricMean(json) { GeometricMean.__super__.constructor.apply(this, arguments); } GeometricMean.prototype.exec = function(ctx) { var e, geoMean, items, product, values; items = this.source.execute(ctx); if (!typeIsArray(items)) { return null; } try { items = processQuantities(items); } catch (error) { e = error; return null; } if (!(items.length > 0)) { return null; } if (hasOnlyQuantities(items)) { values = getValuesFromQuantities(items); product = values.reduce(function(x, y) { return x * y; }); geoMean = Math.pow(product, 1.0 / items.length); return new Quantity(geoMean, items[0].unit); } else { product = items.reduce(function(x, y) { return x * y; }); return Math.pow(product, 1.0 / items.length); } }; return GeometricMean; })(AggregateExpression); module.exports.PopulationStdDev = PopulationStdDev = (function(superClass) { extend(PopulationStdDev, superClass); function PopulationStdDev(json) { PopulationStdDev.__super__.constructor.apply(this, arguments); this.type = "population_deviation"; } return PopulationStdDev; })(StdDev); module.exports.Variance = Variance = (function(superClass) { extend(Variance, superClass); function Variance(json) { Variance.__super__.constructor.apply(this, arguments); this.type = "standard_variance"; } return Variance; })(StdDev); module.exports.PopulationVariance = PopulationVariance = (function(superClass) { extend(PopulationVariance, superClass); function PopulationVariance(json) { PopulationVariance.__super__.constructor.apply(this, arguments); this.type = "population_variance"; } return PopulationVariance; })(StdDev); module.exports.AllTrue = AllTrue = (function(superClass) { extend(AllTrue, superClass); function AllTrue(json) { AllTrue.__super__.constructor.apply(this, arguments); } AllTrue.prototype.exec = function(ctx) { var items; items = this.source.execute(ctx); return allTrue(items); }; return AllTrue; })(AggregateExpression); module.exports.AnyTrue = AnyTrue = (function(superClass) { extend(AnyTrue, superClass); function AnyTrue(json) { AnyTrue.__super__.constructor.apply(this, arguments); } AnyTrue.prototype.exec = function(ctx) { var items; items = this.source.execute(ctx); return anyTrue(items); }; return AnyTrue; })(AggregateExpression); processQuantities = function(values) { values = removeNulls(values); if (hasOnlyQuantities(values)) { return values = convertAllUnits(values); } else if (hasSomeQuantities(values)) { throw new Exception("Cannot perform aggregate operations on mixed values of Quantities and non Quantities"); } else { return values; } }; getValuesFromQuantities = function(quantities) { return quantities.map(function(quantity) { return quantity.value; }); }; hasOnlyQuantities = function(arr) { return arr.every(function(x) { return x.isQuantity; }); }; hasSomeQuantities = function(arr) { return arr.some(function(x) { return x.isQuantity; }); }; convertAllUnits = function(arr) { var converted, i, len, quantity; converted = []; for (i = 0, len = arr.length; i < len; i++) { quantity = arr[i]; converted.push(quantity.convertUnit(arr[0].unit)); } return converted; }; medianOfNumbers = function(numbers) { numbers = numerical_sort(numbers, "asc"); if (numbers.length % 2 === 1) { return numbers[(numbers.length - 1) / 2]; } else { return (numbers[(numbers.length / 2) - 1] + numbers[numbers.length / 2]) / 2; } }; }).call(this); },{"../datatypes/exception":123,"../datatypes/quantity":126,"../util/comparison":250,"../util/util":252,"./builder":131,"./expression":137}],130:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Abs, Add, Ceiling, Divide, Exp, Expression, Floor, Ln, Log, MathUtil, MaxValue, MinValue, Modulo, Multiply, Negate, Power, Predecessor, Quantity, Round, Subtract, Successor, Truncate, TruncatedDivide, allTrue, anyTrue, build, doAddition, doDivision, doMultiplication, doSubtraction, ref, ref1, typeIsArray, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; ref = require('../util/util'), typeIsArray = ref.typeIsArray, allTrue = ref.allTrue, anyTrue = ref.anyTrue; build = require('./builder').build; MathUtil = require('../util/math'); ref1 = require('../datatypes/quantity'), Quantity = ref1.Quantity, doAddition = ref1.doAddition, doSubtraction = ref1.doSubtraction, doMultiplication = ref1.doMultiplication, doDivision = ref1.doDivision; module.exports.Add = Add = (function(superClass) { extend(Add, superClass); function Add(json) { Add.__super__.constructor.apply(this, arguments); } Add.prototype.exec = function(ctx) { var args, sum; args = this.execArgs(ctx); sum = null; if ((args == null) || args.some(function(x) { return x == null; })) { null; } else { if (args != null) { args.reduce(function(x, y) { if (x.isQuantity || x.isDateTime || x.isDate || x.isTime) { return sum = doAddition(x, y); } else { return sum = x + y; } }); } } if (MathUtil.overflowsOrUnderflows(sum)) { return null; } return sum; }; return Add; })(Expression); module.exports.Subtract = Subtract = (function(superClass) { extend(Subtract, superClass); function Subtract(json) { Subtract.__super__.constructor.apply(this, arguments); } Subtract.prototype.exec = function(ctx) { var args, difference; args = this.execArgs(ctx); difference = null; if ((args == null) || args.some(function(x) { return x == null; })) { null; } else { args.reduce(function(x, y) { if (x.isQuantity || x.isDateTime || x.isDate) { return difference = doSubtraction(x, y); } else { return difference = x - y; } }); } if (MathUtil.overflowsOrUnderflows(difference)) { return null; } return difference; }; return Subtract; })(Expression); module.exports.Multiply = Multiply = (function(superClass) { extend(Multiply, superClass); function Multiply(json) { Multiply.__super__.constructor.apply(this, arguments); } Multiply.prototype.exec = function(ctx) { var args, product; args = this.execArgs(ctx); product = null; if ((args == null) || args.some(function(x) { return x == null; })) { null; } else { if (args != null) { args.reduce(function(x, y) { if (x.isQuantity || y.isQuantity) { return product = doMultiplication(x, y); } else { return product = x * y; } }); } } if (MathUtil.overflowsOrUnderflows(product)) { return null; } return product; }; return Multiply; })(Expression); module.exports.Divide = Divide = (function(superClass) { extend(Divide, superClass); function Divide(json) { Divide.__super__.constructor.apply(this, arguments); } Divide.prototype.exec = function(ctx) { var args, quotient; args = this.execArgs(ctx); quotient = null; if ((args == null) || args.some(function(x) { return x == null; })) { null; } else { if (args != null) { args.reduce(function(x, y) { if (x.isQuantity) { return quotient = doDivision(x, y); } else { return quotient = x / y; } }); } } if (MathUtil.overflowsOrUnderflows(quotient)) { return null; } return quotient; }; return Divide; })(Expression); module.exports.TruncatedDivide = TruncatedDivide = (function(superClass) { extend(TruncatedDivide, superClass); function TruncatedDivide(json) { TruncatedDivide.__super__.constructor.apply(this, arguments); } TruncatedDivide.prototype.exec = function(ctx) { var args, quotient; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { null; } else { quotient = Math.floor(args.reduce(function(x, y) { return x / y; })); } if (MathUtil.overflowsOrUnderflows(quotient)) { return null; } return quotient; }; return TruncatedDivide; })(Expression); module.exports.Modulo = Modulo = (function(superClass) { extend(Modulo, superClass); function Modulo(json) { Modulo.__super__.constructor.apply(this, arguments); } Modulo.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { return null; } else { return args.reduce(function(x, y) { return x % y; }); } }; return Modulo; })(Expression); module.exports.Ceiling = Ceiling = (function(superClass) { extend(Ceiling, superClass); function Ceiling(json) { Ceiling.__super__.constructor.apply(this, arguments); } Ceiling.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return Math.ceil(arg); } }; return Ceiling; })(Expression); module.exports.Floor = Floor = (function(superClass) { extend(Floor, superClass); function Floor(json) { Floor.__super__.constructor.apply(this, arguments); } Floor.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return Math.floor(arg); } }; return Floor; })(Expression); module.exports.Truncate = Truncate = (function(superClass) { extend(Truncate, superClass); function Truncate() { return Truncate.__super__.constructor.apply(this, arguments); } return Truncate; })(Floor); module.exports.Abs = Abs = (function(superClass) { extend(Abs, superClass); function Abs(json) { Abs.__super__.constructor.apply(this, arguments); } Abs.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isQuantity) { return new Quantity(Math.abs(arg.value), arg.unit); } else { return Math.abs(arg); } }; return Abs; })(Expression); module.exports.Negate = Negate = (function(superClass) { extend(Negate, superClass); function Negate(json) { Negate.__super__.constructor.apply(this, arguments); } Negate.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isQuantity) { return new Quantity(arg.value * -1, arg.unit); } else { return arg * -1; } }; return Negate; })(Expression); module.exports.Round = Round = (function(superClass) { extend(Round, superClass); function Round(json) { Round.__super__.constructor.apply(this, arguments); this.precision = build(json.precision); } Round.prototype.exec = function(ctx) { var arg, dec; arg = this.execArgs(ctx); if (arg == null) { return null; } else { dec = this.precision != null ? this.precision.execute(ctx) : 0; return Math.round(arg * Math.pow(10, dec)) / Math.pow(10, dec); } }; return Round; })(Expression); module.exports.Ln = Ln = (function(superClass) { extend(Ln, superClass); function Ln(json) { Ln.__super__.constructor.apply(this, arguments); } Ln.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return Math.log(arg); } }; return Ln; })(Expression); module.exports.Exp = Exp = (function(superClass) { extend(Exp, superClass); function Exp(json) { Exp.__super__.constructor.apply(this, arguments); } Exp.prototype.exec = function(ctx) { var arg, power; arg = this.execArgs(ctx); if (arg == null) { null; } else { power = Math.exp(arg); } if (MathUtil.overflowsOrUnderflows(power)) { return null; } return power; }; return Exp; })(Expression); module.exports.Log = Log = (function(superClass) { extend(Log, superClass); function Log(json) { Log.__super__.constructor.apply(this, arguments); } Log.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { return null; } else { return args.reduce(function(x, y) { return Math.log(x) / Math.log(y); }); } }; return Log; })(Expression); module.exports.Power = Power = (function(superClass) { extend(Power, superClass); function Power(json) { Power.__super__.constructor.apply(this, arguments); } Power.prototype.exec = function(ctx) { var args, power; args = this.execArgs(ctx); power = null; if ((args == null) || args.some(function(x) { return x == null; })) { null; } else { power = args.reduce(function(x, y) { return Math.pow(x, y); }); } if (MathUtil.overflowsOrUnderflows(power)) { return null; } return power; }; return Power; })(Expression); module.exports.MinValue = MinValue = (function(superClass) { var MIN_VALUES; extend(MinValue, superClass); MIN_VALUES = {}; MIN_VALUES['{urn:hl7-org:elm-types:r1}Integer'] = MathUtil.MIN_INT_VALUE; MIN_VALUES['{urn:hl7-org:elm-types:r1}Decimal'] = MathUtil.MIN_FLOAT_VALUE; MIN_VALUES['{urn:hl7-org:elm-types:r1}DateTime'] = MathUtil.MIN_DATETIME_VALUE; MIN_VALUES['{urn:hl7-org:elm-types:r1}Date'] = MathUtil.MIN_DATE_VALUE; MIN_VALUES['{urn:hl7-org:elm-types:r1}Time'] = MathUtil.MIN_TIME_VALUE; function MinValue(json) { MinValue.__super__.constructor.apply(this, arguments); this.valueType = json.valueType; } MinValue.prototype.exec = function(ctx) { var minDateTime; if (MIN_VALUES[this.valueType]) { if (this.valueType === '{urn:hl7-org:elm-types:r1}DateTime') { minDateTime = MIN_VALUES[this.valueType].copy(); minDateTime.timezoneOffset = ctx.getTimezoneOffset(); return minDateTime; } else { return MIN_VALUES[this.valueType]; } } else { throw new Error("Minimum not supported for " + this.valueType); } }; return MinValue; })(Expression); module.exports.MaxValue = MaxValue = (function(superClass) { var MAX_VALUES; extend(MaxValue, superClass); MAX_VALUES = {}; MAX_VALUES['{urn:hl7-org:elm-types:r1}Integer'] = MathUtil.MAX_INT_VALUE; MAX_VALUES['{urn:hl7-org:elm-types:r1}Decimal'] = MathUtil.MAX_FLOAT_VALUE; MAX_VALUES['{urn:hl7-org:elm-types:r1}DateTime'] = MathUtil.MAX_DATETIME_VALUE; MAX_VALUES['{urn:hl7-org:elm-types:r1}Date'] = MathUtil.MAX_DATE_VALUE; MAX_VALUES['{urn:hl7-org:elm-types:r1}Time'] = MathUtil.MAX_TIME_VALUE; function MaxValue(json) { MaxValue.__super__.constructor.apply(this, arguments); this.valueType = json.valueType; } MaxValue.prototype.exec = function(ctx) { var maxDateTime; if (MAX_VALUES[this.valueType] != null) { if (this.valueType === '{urn:hl7-org:elm-types:r1}DateTime') { maxDateTime = MAX_VALUES[this.valueType].copy(); maxDateTime.timezoneOffset = ctx.getTimezoneOffset(); return maxDateTime; } else { return MAX_VALUES[this.valueType]; } } else { throw new Error("Maximum not supported for " + this.valueType); } }; return MaxValue; })(Expression); module.exports.Successor = Successor = (function(superClass) { extend(Successor, superClass); function Successor(json) { Successor.__super__.constructor.apply(this, arguments); } Successor.prototype.exec = function(ctx) { var arg, e, successor; arg = this.execArgs(ctx); successor = null; if (arg == null) { null; } else { try { successor = MathUtil.successor(arg); } catch (error) { e = error; if (e instanceof MathUtil.OverFlowException) { return null; } } } if (MathUtil.overflowsOrUnderflows(successor)) { return null; } return successor; }; return Successor; })(Expression); module.exports.Predecessor = Predecessor = (function(superClass) { extend(Predecessor, superClass); function Predecessor(json) { Predecessor.__super__.constructor.apply(this, arguments); } Predecessor.prototype.exec = function(ctx) { var arg, e, predecessor; arg = this.execArgs(ctx); predecessor = null; if (arg == null) { null; } else { try { predecessor = MathUtil.predecessor(arg); } catch (error) { e = error; if (e instanceof MathUtil.OverFlowException) { return null; } } } if (MathUtil.overflowsOrUnderflows(predecessor)) { return null; } return predecessor; }; return Predecessor; })(Expression); }).call(this); },{"../datatypes/quantity":126,"../util/math":251,"../util/util":252,"./builder":131,"./expression":137}],131:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var E, build, constructByName, functionExists, typeIsArray; E = require('./expressions'); typeIsArray = require('../util/util').typeIsArray; module.exports.build = build = function(json) { var child; if (json == null) { return json; } if (typeIsArray(json)) { return (function() { var i, len, results; results = []; for (i = 0, len = json.length; i < len; i++) { child = json[i]; results.push(build(child)); } return results; })(); } if (json.type === "FunctionRef") { return new E.FunctionRef(json); } else if (json.type === "Literal") { return E.Literal.from(json); } else if (functionExists(json.type)) { return constructByName(json.type, json); } else { return null; } }; functionExists = function(name) { return typeof E[name] === "function"; }; constructByName = function(name, json) { return new E[name](json); }; }).call(this); },{"../util/util":252,"./expressions":138}],132:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var AnyInValueSet, CalculateAge, CalculateAgeAt, Code, CodeDef, CodeRef, CodeSystemDef, Concept, ConceptDef, ConceptRef, Expression, InValueSet, ValueSetDef, ValueSetRef, build, dt, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; dt = require('../datatypes/datatypes'); build = require('./builder').build; module.exports.ValueSetDef = ValueSetDef = (function(superClass) { extend(ValueSetDef, superClass); function ValueSetDef(json) { ValueSetDef.__super__.constructor.apply(this, arguments); this.name = json.name; this.id = json.id; this.version = json.version; } ValueSetDef.prototype.exec = function(ctx) { var ref, valueset; valueset = (ref = ctx.codeService.findValueSet(this.id, this.version)) != null ? ref : new dt.ValueSet(this.id, this.version); ctx.rootContext().set(this.name, valueset); return valueset; }; return ValueSetDef; })(Expression); module.exports.ValueSetRef = ValueSetRef = (function(superClass) { extend(ValueSetRef, superClass); function ValueSetRef(json) { ValueSetRef.__super__.constructor.apply(this, arguments); this.name = json.name; this.libraryName = json.libraryName; } ValueSetRef.prototype.exec = function(ctx) { var valueset; valueset = ctx.getValueSet(this.name, this.libraryName); if (valueset instanceof Expression) { valueset = valueset.execute(ctx); } return valueset; }; return ValueSetRef; })(Expression); module.exports.AnyInValueSet = AnyInValueSet = (function(superClass) { extend(AnyInValueSet, superClass); function AnyInValueSet(json) { AnyInValueSet.__super__.constructor.apply(this, arguments); this.codes = build(json.codes); this.valueset = new ValueSetRef(json.valueset); } AnyInValueSet.prototype.exec = function(ctx) { var code, codes, i, len, valueset; valueset = this.valueset.execute(ctx); if (!((valueset != null) && valueset.isValueSet)) { throw new Error("ValueSet must be provided to InValueSet function"); } codes = this.codes.exec(ctx); if (codes == null) { return false; } for (i = 0, len = codes.length; i < len; i++) { code = codes[i]; if (valueset.hasMatch(code)) { return true; } } return false; }; return AnyInValueSet; })(Expression); module.exports.InValueSet = InValueSet = (function(superClass) { extend(InValueSet, superClass); function InValueSet(json) { InValueSet.__super__.constructor.apply(this, arguments); this.code = build(json.code); this.valueset = new ValueSetRef(json.valueset); } InValueSet.prototype.exec = function(ctx) { var code, valueset; if (this.code == null) { return false; } if (this.valueset == null) { throw new Error("ValueSet must be provided to InValueSet function"); } code = this.code.execute(ctx); if (code == null) { return false; } valueset = this.valueset.execute(ctx); if (!((valueset != null) && valueset.isValueSet)) { throw new Error("ValueSet must be provided to InValueSet function"); } return valueset.hasMatch(code); }; return InValueSet; })(Expression); module.exports.CodeSystemDef = CodeSystemDef = (function(superClass) { extend(CodeSystemDef, superClass); function CodeSystemDef(json) { CodeSystemDef.__super__.constructor.apply(this, arguments); this.name = json.name; this.id = json.id; this.version = json.version; } CodeSystemDef.prototype.exec = function(ctx) { return new dt.CodeSystem(this.id, this.version); }; return CodeSystemDef; })(Expression); module.exports.CodeDef = CodeDef = (function(superClass) { extend(CodeDef, superClass); function CodeDef(json) { CodeDef.__super__.constructor.apply(this, arguments); this.name = json.name; this.id = json.id; this.systemName = json.codeSystem.name; this.display = json.display; } CodeDef.prototype.exec = function(ctx) { var ref, system; system = (ref = ctx.getCodeSystem(this.systemName)) != null ? ref.execute(ctx) : void 0; return new dt.Code(this.id, system.id, system.version, this.display); }; return CodeDef; })(Expression); module.exports.CodeRef = CodeRef = (function(superClass) { extend(CodeRef, superClass); function CodeRef(json) { CodeRef.__super__.constructor.apply(this, arguments); this.name = json.name; this.library = json.libraryName; } CodeRef.prototype.exec = function(ctx) { var ref; ctx = this.library ? ctx.getLibraryContext(this.library) : ctx; return (ref = ctx.getCode(this.name)) != null ? ref.execute(ctx) : void 0; }; return CodeRef; })(Expression); module.exports.Code = Code = (function(superClass) { extend(Code, superClass); function Code(json) { Code.__super__.constructor.apply(this, arguments); this.code = json.code; this.systemName = json.system.name; this.version = json.version; this.display = json.display; } Object.defineProperties(Code.prototype, { isCode: { get: function() { return true; } } }); Code.prototype.exec = function(ctx) { var ref, system; system = (ref = ctx.getCodeSystem(this.systemName)) != null ? ref.id : void 0; return new dt.Code(this.code, system, this.version, this.display); }; return Code; })(Expression); module.exports.ConceptDef = ConceptDef = (function(superClass) { extend(ConceptDef, superClass); function ConceptDef(json) { ConceptDef.__super__.constructor.apply(this, arguments); this.name = json.name; this.display = json.display; this.codes = json.code; } ConceptDef.prototype.exec = function(ctx) { var code, codes; codes = (function() { var i, len, ref, ref1, results; ref = this.codes; results = []; for (i = 0, len = ref.length; i < len; i++) { code = ref[i]; results.push((ref1 = ctx.getCode(code.name)) != null ? ref1.execute(ctx) : void 0); } return results; }).call(this); return new dt.Concept(codes, this.display); }; return ConceptDef; })(Expression); module.exports.ConceptRef = ConceptRef = (function(superClass) { extend(ConceptRef, superClass); function ConceptRef(json) { ConceptRef.__super__.constructor.apply(this, arguments); this.name = json.name; } ConceptRef.prototype.exec = function(ctx) { var ref; return (ref = ctx.getConcept(this.name)) != null ? ref.execute(ctx) : void 0; }; return ConceptRef; })(Expression); module.exports.Concept = Concept = (function(superClass) { extend(Concept, superClass); function Concept(json) { Concept.__super__.constructor.apply(this, arguments); this.codes = json.code; this.display = json.display; } Object.defineProperties(Concept.prototype, { isConcept: { get: function() { return true; } } }); Concept.prototype.toCode = function(ctx, code) { var ref, system; system = (ref = ctx.getCodeSystem(code.system.name)) != null ? ref.id : void 0; return new dt.Code(code.code, system, code.version, code.display); }; Concept.prototype.exec = function(ctx) { var code, codes; codes = (function() { var i, len, ref, results; ref = this.codes; results = []; for (i = 0, len = ref.length; i < len; i++) { code = ref[i]; results.push(this.toCode(ctx, code)); } return results; }).call(this); return new dt.Concept(codes, this.display); }; return Concept; })(Expression); module.exports.CalculateAge = CalculateAge = (function(superClass) { extend(CalculateAge, superClass); function CalculateAge(json) { CalculateAge.__super__.constructor.apply(this, arguments); this.precision = json.precision; } CalculateAge.prototype.exec = function(ctx) { var date1, date2, result; date1 = this.execArgs(ctx); date2 = dt.DateTime.fromJSDate(ctx.getExecutionDateTime()); result = date1 != null ? date1.durationBetween(date2, this.precision.toLowerCase()) : void 0; if ((result != null) && result.isPoint()) { return result.low; } else { return result; } }; return CalculateAge; })(Expression); module.exports.CalculateAgeAt = CalculateAgeAt = (function(superClass) { extend(CalculateAgeAt, superClass); function CalculateAgeAt(json) { CalculateAgeAt.__super__.constructor.apply(this, arguments); this.precision = json.precision; } CalculateAgeAt.prototype.exec = function(ctx) { var date1, date2, ref, result; ref = this.execArgs(ctx), date1 = ref[0], date2 = ref[1]; if ((date1 != null) && (date2 != null)) { if (date2.isDate && date1.isDateTime) { date1 = date1.getDate(); } result = date1.durationBetween(date2, this.precision.toLowerCase()); if ((result != null) && result.isPoint()) { return result.low; } else { return result; } } else { return null; } }; return CalculateAgeAt; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"./builder":131,"./expression":137}],133:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, Greater, GreaterOrEqual, Less, LessOrEqual, Uncertainty, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; Uncertainty = require('../datatypes/datatypes').Uncertainty; module.exports.Less = Less = (function(superClass) { extend(Less, superClass); function Less(json) { Less.__super__.constructor.apply(this, arguments); } Less.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); if (!((args[0] != null) && (args[1] != null))) { return null; } return args[0].lessThan(args[1]); }; return Less; })(Expression); module.exports.LessOrEqual = LessOrEqual = (function(superClass) { extend(LessOrEqual, superClass); function LessOrEqual(json) { LessOrEqual.__super__.constructor.apply(this, arguments); } LessOrEqual.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); if (!((args[0] != null) && (args[1] != null))) { return null; } return args[0].lessThanOrEquals(args[1]); }; return LessOrEqual; })(Expression); module.exports.Greater = Greater = (function(superClass) { extend(Greater, superClass); function Greater(json) { Greater.__super__.constructor.apply(this, arguments); } Greater.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); if (!((args[0] != null) && (args[1] != null))) { return null; } return args[0].greaterThan(args[1]); }; return Greater; })(Expression); module.exports.GreaterOrEqual = GreaterOrEqual = (function(superClass) { extend(GreaterOrEqual, superClass); function GreaterOrEqual(json) { GreaterOrEqual.__super__.constructor.apply(this, arguments); } GreaterOrEqual.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); if (!((args[0] != null) && (args[1] != null))) { return null; } return args[0].greaterThanOrEquals(args[1]); }; return GreaterOrEqual; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"./expression":137}],134:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Case, CaseItem, Expression, If, build, equals, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; build = require('./builder').build; equals = require('../util/comparison').equals; module.exports.If = If = (function(superClass) { extend(If, superClass); function If(json) { If.__super__.constructor.apply(this, arguments); this.condition = build(json.condition); this.th = build(json.then); this.els = build(json["else"]); } If.prototype.exec = function(ctx) { if (this.condition.execute(ctx)) { return this.th.execute(ctx); } else { return this.els.execute(ctx); } }; return If; })(Expression); module.exports.CaseItem = CaseItem = CaseItem = (function() { function CaseItem(json) { this.when = build(json.when); this.then = build(json.then); } return CaseItem; })(); module.exports.Case = Case = (function(superClass) { extend(Case, superClass); function Case(json) { var ci; Case.__super__.constructor.apply(this, arguments); this.comparand = build(json.comparand); this.caseItems = (function() { var i, len, ref, results; ref = json.caseItem; results = []; for (i = 0, len = ref.length; i < len; i++) { ci = ref[i]; results.push(new CaseItem(ci)); } return results; })(); this.els = build(json["else"]); } Case.prototype.exec = function(ctx) { if (this.comparand) { return this.exec_selected(ctx); } else { return this.exec_standard(ctx); } }; Case.prototype.exec_selected = function(ctx) { var ci, i, len, ref, val; val = this.comparand.execute(ctx); ref = this.caseItems; for (i = 0, len = ref.length; i < len; i++) { ci = ref[i]; if (equals(ci.when.execute(ctx), val)) { return ci.then.execute(ctx); } } return this.els.execute(ctx); }; Case.prototype.exec_standard = function(ctx) { var ci, i, len, ref; ref = this.caseItems; for (i = 0, len = ref.length; i < len; i++) { ci = ref[i]; if (ci.when.execute(ctx)) { return ci.then.execute(ctx); } } return this.els.execute(ctx); }; return Case; })(Expression); }).call(this); },{"../util/comparison":250,"./builder":131,"./expression":137}],135:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DT, Date, DateFrom, DateTime, DateTimeComponentFrom, DifferenceBetween, DurationBetween, Expression, Literal, Now, Time, TimeFrom, TimeOfDay, TimezoneOffsetFrom, Today, build, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, slice = [].slice; Expression = require('./expression').Expression; build = require('./builder').build; Literal = require('./literal').Literal; DT = require('../datatypes/datatypes'); module.exports.DateTime = DateTime = (function(superClass) { extend(DateTime, superClass); DateTime.PROPERTIES = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond', 'timezoneOffset']; function DateTime(json1) { this.json = json1; DateTime.__super__.constructor.apply(this, arguments); } DateTime.prototype.exec = function(ctx) { var args, i, len, p, property, ref; ref = DateTime.PROPERTIES; for (i = 0, len = ref.length; i < len; i++) { property = ref[i]; if (this.json[property] != null) { this[property] = build(this.json[property]); } else if (property === 'timezoneOffset' && (ctx.getTimezoneOffset() != null)) { this[property] = Literal.from({ "type": "Literal", "value": ctx.getTimezoneOffset(), "valueType": "{urn:hl7-org:elm-types:r1}Integer" }); } } args = (function() { var j, len1, ref1, results; ref1 = DateTime.PROPERTIES; results = []; for (j = 0, len1 = ref1.length; j < len1; j++) { p = ref1[j]; results.push(this[p] != null ? this[p].execute(ctx) : void 0); } return results; }).call(this); return (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(DT.DateTime, args, function(){}); }; return DateTime; })(Expression); module.exports.Date = Date = (function(superClass) { extend(Date, superClass); Date.PROPERTIES = ['year', 'month', 'day']; function Date(json1) { this.json = json1; Date.__super__.constructor.apply(this, arguments); } Date.prototype.exec = function(ctx) { var args, i, len, p, property, ref; ref = Date.PROPERTIES; for (i = 0, len = ref.length; i < len; i++) { property = ref[i]; if (this.json[property] != null) { this[property] = build(this.json[property]); } } args = (function() { var j, len1, ref1, results; ref1 = Date.PROPERTIES; results = []; for (j = 0, len1 = ref1.length; j < len1; j++) { p = ref1[j]; results.push(this[p] != null ? this[p].execute(ctx) : void 0); } return results; }).call(this); return (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(DT.Date, args, function(){}); }; return Date; })(Expression); module.exports.Time = Time = (function(superClass) { extend(Time, superClass); Time.PROPERTIES = ['hour', 'minute', 'second', 'millisecond']; function Time(json) { var i, len, property, ref; Time.__super__.constructor.apply(this, arguments); ref = Time.PROPERTIES; for (i = 0, len = ref.length; i < len; i++) { property = ref[i]; if (json[property] != null) { this[property] = build(json[property]); } } } Time.prototype.exec = function(ctx) { var args, p; args = (function() { var i, len, ref, results; ref = Time.PROPERTIES; results = []; for (i = 0, len = ref.length; i < len; i++) { p = ref[i]; results.push(this[p] != null ? this[p].execute(ctx) : void 0); } return results; }).call(this); return ((function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(DT.DateTime, [0, 1, 1].concat(slice.call(args)), function(){})).getTime(); }; return Time; })(Expression); module.exports.Today = Today = (function(superClass) { extend(Today, superClass); function Today(json) { Today.__super__.constructor.apply(this, arguments); } Today.prototype.exec = function(ctx) { return ctx.getExecutionDateTime().getDate(); }; return Today; })(Expression); module.exports.Now = Now = (function(superClass) { extend(Now, superClass); function Now(json) { Now.__super__.constructor.apply(this, arguments); } Now.prototype.exec = function(ctx) { return ctx.getExecutionDateTime(); }; return Now; })(Expression); module.exports.TimeOfDay = TimeOfDay = (function(superClass) { extend(TimeOfDay, superClass); function TimeOfDay(json) { TimeOfDay.__super__.constructor.apply(this, arguments); } TimeOfDay.prototype.exec = function(ctx) { return ctx.getExecutionDateTime().getTime(); }; return TimeOfDay; })(Expression); module.exports.DateTimeComponentFrom = DateTimeComponentFrom = (function(superClass) { extend(DateTimeComponentFrom, superClass); function DateTimeComponentFrom(json) { DateTimeComponentFrom.__super__.constructor.apply(this, arguments); this.precision = json.precision; } DateTimeComponentFrom.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg != null) { return arg[this.precision.toLowerCase()]; } else { return null; } }; return DateTimeComponentFrom; })(Expression); module.exports.DateFrom = DateFrom = (function(superClass) { extend(DateFrom, superClass); function DateFrom(json) { DateFrom.__super__.constructor.apply(this, arguments); } DateFrom.prototype.exec = function(ctx) { var date; date = this.execArgs(ctx); if (date != null) { return date.getDate(); } else { return null; } }; return DateFrom; })(Expression); module.exports.TimeFrom = TimeFrom = (function(superClass) { extend(TimeFrom, superClass); function TimeFrom(json) { TimeFrom.__super__.constructor.apply(this, arguments); } TimeFrom.prototype.exec = function(ctx) { var date; date = this.execArgs(ctx); if (date != null) { return date.getTime(); } else { return null; } }; return TimeFrom; })(Expression); module.exports.TimezoneOffsetFrom = TimezoneOffsetFrom = (function(superClass) { extend(TimezoneOffsetFrom, superClass); function TimezoneOffsetFrom(json) { TimezoneOffsetFrom.__super__.constructor.apply(this, arguments); } TimezoneOffsetFrom.prototype.exec = function(ctx) { var date; date = this.execArgs(ctx); if (date != null) { return date.timezoneOffset; } else { return null; } }; return TimezoneOffsetFrom; })(Expression); module.exports.doAfter = function(a, b, precision) { return a.after(b, precision); }; module.exports.doBefore = function(a, b, precision) { return a.before(b, precision); }; module.exports.DifferenceBetween = DifferenceBetween = (function(superClass) { extend(DifferenceBetween, superClass); function DifferenceBetween(json) { DifferenceBetween.__super__.constructor.apply(this, arguments); this.precision = json.precision; } DifferenceBetween.prototype.exec = function(ctx) { var args, ref, result; args = this.execArgs(ctx); if ((args[0] == null) || (args[1] == null) || typeof args[0].differenceBetween !== 'function' || typeof args[1].differenceBetween !== 'function') { return null; } result = args[0].differenceBetween(args[1], (ref = this.precision) != null ? ref.toLowerCase() : void 0); if ((result != null) && result.isPoint()) { return result.low; } else { return result; } }; return DifferenceBetween; })(Expression); module.exports.DurationBetween = DurationBetween = (function(superClass) { extend(DurationBetween, superClass); function DurationBetween(json) { DurationBetween.__super__.constructor.apply(this, arguments); this.precision = json.precision; } DurationBetween.prototype.exec = function(ctx) { var args, ref, result; args = this.execArgs(ctx); if ((args[0] == null) || (args[1] == null) || typeof args[0].durationBetween !== 'function' || typeof args[1].durationBetween !== 'function') { return null; } result = args[0].durationBetween(args[1], (ref = this.precision) != null ? ref.toLowerCase() : void 0); if ((result != null) && result.isPoint()) { return result.low; } else { return result; } }; return DurationBetween; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"./builder":131,"./expression":137,"./literal":144}],136:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, IncludeDef, UnimplementedExpression, UsingDef, VersionedIdentifier, ref, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; module.exports.UsingDef = UsingDef = (function(superClass) { extend(UsingDef, superClass); function UsingDef() { return UsingDef.__super__.constructor.apply(this, arguments); } return UsingDef; })(UnimplementedExpression); module.exports.IncludeDef = IncludeDef = (function(superClass) { extend(IncludeDef, superClass); function IncludeDef() { return IncludeDef.__super__.constructor.apply(this, arguments); } return IncludeDef; })(UnimplementedExpression); module.exports.VersionedIdentifier = VersionedIdentifier = (function(superClass) { extend(VersionedIdentifier, superClass); function VersionedIdentifier() { return VersionedIdentifier.__super__.constructor.apply(this, arguments); } return VersionedIdentifier; })(UnimplementedExpression); }).call(this); },{"./expression":137}],137:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, UnimplementedExpression, build, typeIsArray, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; build = require('./builder').build; typeIsArray = require('../util/util').typeIsArray; module.exports.Expression = Expression = (function() { function Expression(json) { var op; if (json.operand != null) { op = build(json.operand); if (typeIsArray(json.operand)) { this.args = op; } else { this.arg = op; } } if (json.localId != null) { this.localId = json.localId; } } Expression.prototype.execute = function(ctx) { var execValue; if (this.localId != null) { execValue = this.exec(ctx); ctx.rootContext().setLocalIdWithResult(this.localId, execValue); return execValue; } else { return this.exec(ctx); } }; Expression.prototype.exec = function(ctx) { return this; }; Expression.prototype.execArgs = function(ctx) { var arg, i, len, ref, results; switch (false) { case this.args == null: ref = this.args; results = []; for (i = 0, len = ref.length; i < len; i++) { arg = ref[i]; results.push(arg.execute(ctx)); } return results; case this.arg == null: return this.arg.execute(ctx); default: return null; } }; return Expression; })(); module.exports.UnimplementedExpression = UnimplementedExpression = (function(superClass) { extend(UnimplementedExpression, superClass); function UnimplementedExpression(json1) { this.json = json1; UnimplementedExpression.__super__.constructor.apply(this, arguments); } UnimplementedExpression.prototype.exec = function(ctx) { throw new Error("Unimplemented Expression: " + this.json.type); }; return UnimplementedExpression; })(Expression); }).call(this); },{"../util/util":252,"./builder":131}],138:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var aggregate, arithmetic, clinical, comparison, conditional, datetime, declaration, element, expression, external, i, instance, interval, j, len, len1, lib, libs, list, literal, logical, nullological, overloaded, parameters, quantity, query, ratio, ref, reusable, string, structured, type; expression = require('./expression'); aggregate = require('./aggregate'); arithmetic = require('./arithmetic'); clinical = require('./clinical'); comparison = require('./comparison'); conditional = require('./conditional'); datetime = require('./datetime'); declaration = require('./declaration'); external = require('./external'); instance = require('./instance'); interval = require('./interval'); list = require('./list'); literal = require('./literal'); logical = require('./logical'); nullological = require('./nullological'); parameters = require('./parameters'); quantity = require('./quantity'); query = require('./query'); ratio = require('./ratio'); reusable = require('./reusable'); string = require('./string'); structured = require('./structured'); type = require('./type'); overloaded = require('./overloaded'); libs = [expression, aggregate, arithmetic, clinical, comparison, conditional, datetime, declaration, external, instance, interval, list, literal, logical, nullological, parameters, query, quantity, ratio, reusable, string, structured, type, overloaded]; for (i = 0, len = libs.length; i < len; i++) { lib = libs[i]; ref = Object.keys(lib); for (j = 0, len1 = ref.length; j < len1; j++) { element = ref[j]; module.exports[element] = lib[element]; } } }).call(this); },{"./aggregate":129,"./arithmetic":130,"./clinical":132,"./comparison":133,"./conditional":134,"./datetime":135,"./declaration":136,"./expression":137,"./external":139,"./instance":140,"./interval":141,"./list":143,"./literal":144,"./logical":145,"./nullological":146,"./overloaded":147,"./parameters":148,"./quantity":149,"./query":150,"./ratio":151,"./reusable":152,"./string":153,"./structured":154,"./type":155}],139:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, Retrieve, build, typeIsArray, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; build = require('./builder').build; typeIsArray = require('../util/util').typeIsArray; module.exports.Retrieve = Retrieve = (function(superClass) { extend(Retrieve, superClass); function Retrieve(json) { Retrieve.__super__.constructor.apply(this, arguments); this.datatype = json.dataType; this.templateId = json.templateId; this.codeProperty = json.codeProperty; this.codes = build(json.codes); this.dateProperty = json.dateProperty; this.dateRange = build(json.dateRange); } Retrieve.prototype.exec = function(ctx) { var codes, r, range, records, ref; records = ctx.findRecords((ref = this.templateId) != null ? ref : this.datatype); codes = this.codes; if (this.codes && typeof this.codes.exec === 'function') { codes = this.codes.execute(ctx); if (codes == null) { return []; } } if (codes) { records = records.filter((function(_this) { return function(r) { return _this.recordMatchesCodesOrVS(r, codes); }; })(this)); } if (this.dateRange && this.dateProperty) { range = this.dateRange.execute(ctx); records = (function() { var i, len, results; results = []; for (i = 0, len = records.length; i < len; i++) { r = records[i]; if (range.includes(r.getDateOrInterval(this.dateProperty))) { results.push(r); } } return results; }).call(this); } return records; }; Retrieve.prototype.recordMatchesCodesOrVS = function(record, codes) { if (typeIsArray(codes)) { return codes.some((function(_this) { return function(c) { return c.hasMatch(record.getCode(_this.codeProperty)); }; })(this)); } else { return codes.hasMatch(record.getCode(this.codeProperty)); } }; return Retrieve; })(Expression); }).call(this); },{"../util/util":252,"./builder":131,"./expression":137}],140:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Code, Concept, Element, Expression, Instance, Quantity, build, ref, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; build = require('./builder').build; Quantity = require('../datatypes/quantity').Quantity; ref = require('../datatypes/datatypes'), Code = ref.Code, Concept = ref.Concept; Element = (function() { function Element(json) { this.name = json.name; this.value = build(json.value); } Element.prototype.exec = function(ctx) { var ref1; return (ref1 = this.value) != null ? ref1.execute(ctx) : void 0; }; return Element; })(); module.exports.Instance = Instance = (function(superClass) { extend(Instance, superClass); function Instance(json) { var child; Instance.__super__.constructor.apply(this, arguments); this.classType = json.classType; this.element = (function() { var i, len, ref1, results; ref1 = json.element; results = []; for (i = 0, len = ref1.length; i < len; i++) { child = ref1[i]; results.push(new Element(child)); } return results; })(); } Instance.prototype.exec = function(ctx) { var el, i, len, obj, ref1; obj = {}; ref1 = this.element; for (i = 0, len = ref1.length; i < len; i++) { el = ref1[i]; obj[el.name] = el.exec(ctx); } switch (this.classType) { case "{urn:hl7-org:elm-types:r1}Quantity": return new Quantity(obj.value, obj.unit); case "{urn:hl7-org:elm-types:r1}Code": return new Code(obj.code, obj.system, obj.version, obj.display); case "{urn:hl7-org:elm-types:r1}Concept": return new Concept(obj.codes, obj.display); default: return obj; } }; return Instance; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"../datatypes/quantity":126,"./builder":131,"./expression":137}],141:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Collapse, End, Ends, Expand, Expression, Interval, MAX_DATETIME_VALUE, MIN_DATETIME_VALUE, Meets, MeetsAfter, MeetsBefore, Overlaps, OverlapsAfter, OverlapsBefore, Quantity, Size, Start, Starts, ThreeValuedLogic, UnimplementedExpression, Width, build, cmp, collapseIntervals, compare_units, convert_value, doAddition, doIncludes, doSubtraction, dtivl, intervalListType, predecessor, ref, ref1, ref2, successor, truncateDecimal, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; ThreeValuedLogic = require('../datatypes/logic').ThreeValuedLogic; build = require('./builder').build; ref1 = require('../datatypes/quantity'), Quantity = ref1.Quantity, doAddition = ref1.doAddition, doSubtraction = ref1.doSubtraction, compare_units = ref1.compare_units, convert_value = ref1.convert_value; ref2 = require('../util/math'), successor = ref2.successor, predecessor = ref2.predecessor, MAX_DATETIME_VALUE = ref2.MAX_DATETIME_VALUE, MIN_DATETIME_VALUE = ref2.MIN_DATETIME_VALUE; dtivl = require('../datatypes/interval'); cmp = require('../util/comparison'); module.exports.Interval = Interval = (function(superClass) { extend(Interval, superClass); function Interval(json) { Interval.__super__.constructor.apply(this, arguments); this.lowClosed = json.lowClosed; this.highClosed = json.highClosed; this.low = build(json.low); this.high = build(json.high); } Object.defineProperties(Interval.prototype, { isInterval: { get: function() { return true; } } }); Interval.prototype.exec = function(ctx) { return new dtivl.Interval(this.low.execute(ctx), this.high.execute(ctx), this.lowClosed, this.highClosed); }; return Interval; })(Expression); module.exports.doContains = function(interval, item, precision) { return interval.contains(item, precision); }; module.exports.doIncludes = doIncludes = function(interval, subinterval, precision) { return interval.includes(subinterval, precision); }; module.exports.doProperIncludes = function(interval, subinterval, precision) { return interval.properlyIncludes(subinterval, precision); }; module.exports.doAfter = function(a, b, precision) { return a.after(b, precision); }; module.exports.doBefore = function(a, b, precision) { return a.before(b, precision); }; module.exports.Meets = Meets = (function(superClass) { extend(Meets, superClass); function Meets(json) { var ref3; Meets.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } Meets.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.meets(b, this.precision); } else { return null; } }; return Meets; })(Expression); module.exports.MeetsAfter = MeetsAfter = (function(superClass) { extend(MeetsAfter, superClass); function MeetsAfter(json) { var ref3; MeetsAfter.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } MeetsAfter.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.meetsAfter(b, this.precision); } else { return null; } }; return MeetsAfter; })(Expression); module.exports.MeetsBefore = MeetsBefore = (function(superClass) { extend(MeetsBefore, superClass); function MeetsBefore(json) { var ref3; MeetsBefore.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } MeetsBefore.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.meetsBefore(b, this.precision); } else { return null; } }; return MeetsBefore; })(Expression); module.exports.Overlaps = Overlaps = (function(superClass) { extend(Overlaps, superClass); function Overlaps(json) { var ref3; Overlaps.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } Overlaps.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.overlaps(b, this.precision); } else { return null; } }; return Overlaps; })(Expression); module.exports.OverlapsAfter = OverlapsAfter = (function(superClass) { extend(OverlapsAfter, superClass); function OverlapsAfter(json) { var ref3; OverlapsAfter.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } OverlapsAfter.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.overlapsAfter(b, this.precision); } else { return null; } }; return OverlapsAfter; })(Expression); module.exports.OverlapsBefore = OverlapsBefore = (function(superClass) { extend(OverlapsBefore, superClass); function OverlapsBefore(json) { var ref3; OverlapsBefore.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } OverlapsBefore.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.overlapsBefore(b, this.precision); } else { return null; } }; return OverlapsBefore; })(Expression); module.exports.doUnion = function(a, b) { return a.union(b); }; module.exports.doExcept = function(a, b) { if ((a != null) && (b != null)) { return a.except(b); } else { return null; } }; module.exports.doIntersect = function(a, b) { if ((a != null) && (b != null)) { return a.intersect(b); } else { return null; } }; module.exports.Width = Width = (function(superClass) { extend(Width, superClass); function Width(json) { Width.__super__.constructor.apply(this, arguments); } Width.prototype.exec = function(ctx) { var ref3; return (ref3 = this.arg.execute(ctx)) != null ? ref3.width() : void 0; }; return Width; })(Expression); module.exports.Size = Size = (function(superClass) { extend(Size, superClass); function Size(json) { Size.__super__.constructor.apply(this, arguments); } Size.prototype.exec = function(ctx) { var interval; interval = this.arg.execute(ctx); if (interval == null) { return null; } return interval.size(); }; return Size; })(Expression); module.exports.Start = Start = (function(superClass) { extend(Start, superClass); function Start(json) { Start.__super__.constructor.apply(this, arguments); } Start.prototype.exec = function(ctx) { var interval, start; interval = this.arg.execute(ctx); if (interval == null) { return null; } start = interval.start(); if ((start != null ? start.isDateTime : void 0) && start.equals(MIN_DATETIME_VALUE)) { start.timezoneOffset = ctx.getTimezoneOffset(); } return start; }; return Start; })(Expression); module.exports.End = End = (function(superClass) { extend(End, superClass); function End(json) { End.__super__.constructor.apply(this, arguments); } End.prototype.exec = function(ctx) { var end, interval; interval = this.arg.execute(ctx); if (interval == null) { return null; } end = interval.end(); if ((end != null ? end.isDateTime : void 0) && end.equals(MAX_DATETIME_VALUE)) { end.timezoneOffset = ctx.getTimezoneOffset(); } return end; }; return End; })(Expression); module.exports.Starts = Starts = (function(superClass) { extend(Starts, superClass); function Starts(json) { var ref3; Starts.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } Starts.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.starts(b, this.precision); } else { return null; } }; return Starts; })(Expression); module.exports.Ends = Ends = (function(superClass) { extend(Ends, superClass); function Ends(json) { var ref3; Ends.__super__.constructor.apply(this, arguments); this.precision = (ref3 = json.precision) != null ? ref3.toLowerCase() : void 0; } Ends.prototype.exec = function(ctx) { var a, b, ref3; ref3 = this.execArgs(ctx), a = ref3[0], b = ref3[1]; if ((a != null) && (b != null)) { return a.ends(b, this.precision); } else { return null; } }; return Ends; })(Expression); intervalListType = function(intervals) { var high, i, itvl, len, low, ref3, ref4, type; type = null; for (i = 0, len = intervals.length; i < len; i++) { itvl = intervals[i]; if (itvl == null) { continue; } if ((itvl.low == null) && (itvl.high == null)) { continue; } low = (ref3 = itvl.low) != null ? ref3 : itvl.high; high = (ref4 = itvl.high) != null ? ref4 : itvl.low; if ((typeof low.isTime === "function" ? low.isTime() : void 0) && (typeof high.isTime === "function" ? high.isTime() : void 0)) { if (type == null) { type = 'time'; } else if (type === 'time') { continue; } else { return 'mismatch'; } } else if ((low.isDateTime || high.isDateTime) && (low.isDateTime || low.isDate) && (high.isDateTime || high.isDate)) { if ((type == null) || type === 'date') { type = 'datetime'; } else if (type === 'datetime') { continue; } else { return 'mismatch'; } } else if (low.isDate && high.isDate) { if (type == null) { type = 'date'; } else if (type === 'date' || 'datetime') { continue; } else { return 'mismatch'; } } else if (low.isQuantity && high.isQuantity) { if (type == null) { type = 'quantity'; } else if (type === 'quantity') { continue; } else { return 'mismatch'; } } else if (Number.isInteger(low) && Number.isInteger(high)) { if (type == null) { type = 'integer'; } else if (type === 'integer' || 'decimal') { continue; } else { return 'mismatch'; } } else if (typeof low === 'number' && typeof high === 'number') { if ((type == null) || type === 'integer') { type = 'decimal'; } else if (type === 'decimal') { continue; } else { return 'mismatch'; } } else { return 'mismatch'; } } return type; }; module.exports.Expand = Expand = (function(superClass) { extend(Expand, superClass); function Expand(json) { Expand.__super__.constructor.apply(this, arguments); } Expand.prototype.exec = function(ctx) { var defaultPer, expandFunction, i, interval, intervals, items, len, per, ref3, results, type; ref3 = this.execArgs(ctx), intervals = ref3[0], per = ref3[1]; type = intervalListType(intervals); if (type === 'mismatch') { throw new Error("List of intervals contains mismatched types."); } if (type == null) { return null; } intervals = collapseIntervals(intervals, per); if (intervals.length === 0) { return []; } if (type === "time" || type === "date" || type === "datetime") { expandFunction = this.expandDTishInterval; defaultPer = function(interval) { return new Quantity(1, interval.low.getPrecision()); }; } else if (type === "quantity") { expandFunction = this.expandQuantityInterval; defaultPer = function(interval) { return new Quantity(1, interval.low.unit); }; } else if (type === "integer" || type === "decimal") { expandFunction = this.expandNumericInterval; defaultPer = function(interval) { return new Quantity(1, '1'); }; } else { throw new Error("Interval list type not yet supported."); } results = []; for (i = 0, len = intervals.length; i < len; i++) { interval = intervals[i]; if (interval == null) { continue; } if ((interval.low == null) || (interval.high == null)) { return null; } if (type === 'datetime') { interval.low = interval.low.getDateTime(); interval.high = interval.high.getDateTime(); } per = per != null ? per : defaultPer(interval); items = expandFunction.call(this, interval, per); if (items === null) { return null; } results.push.apply(results, items); } return results; }; Expand.prototype.expandDTishInterval = function(interval, per) { var current_high, current_low, high, intervalToAdd, low, ref3, ref4, results; if ((ref3 = per.unit) === 'week' || ref3 === 'weeks') { per.value *= 7; per.unit = 'day'; } if (ref4 = per.unit, indexOf.call(interval.low.constructor.FIELDS, ref4) < 0) { return null; } if (!((interval.low != null) && (interval.high != null))) { return null; } low = interval.lowClosed ? interval.low : interval.low.successor(); high = interval.highClosed ? interval.high : interval.high.predecessor(); if (low.after(high)) { return []; } if (interval.low.isLessPrecise(per.unit) || interval.high.isLessPrecise(per.unit)) { return []; } current_low = low; results = []; low = this.truncateToPrecision(low, per.unit); high = this.truncateToPrecision(high, per.unit); current_high = current_low.add(per.value, per.unit).predecessor(); intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); while (intervalToAdd.high.sameOrBefore(high)) { results.push(intervalToAdd); current_low = current_low.add(per.value, per.unit); current_high = current_low.add(per.value, per.unit).predecessor(); intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); } return results; }; Expand.prototype.truncateToPrecision = function(value, unit) { var field, i, len, ref3, shouldTruncate; shouldTruncate = false; ref3 = value.constructor.FIELDS; for (i = 0, len = ref3.length; i < len; i++) { field = ref3[i]; if (shouldTruncate) { value[field] = null; } if (field === unit) { shouldTruncate = true; } } return value; }; Expand.prototype.expandQuantityInterval = function(interval, per) { var high_value, i, itvl, len, low_value, per_value, result_units, results; if (compare_units(interval.low.unit, per.unit) > 0) { result_units = per.unit; } else { result_units = interval.low.unit; } low_value = convert_value(interval.low.value, interval.low.unit, result_units); high_value = convert_value(interval.high.value, interval.high.unit, result_units); per_value = convert_value(per.value, per.unit, result_units); if (!((low_value != null) && (high_value != null) && (per_value != null))) { return null; } results = this.makeNumericIntervalList(low_value, high_value, interval.lowClosed, interval.highClosed, per_value); for (i = 0, len = results.length; i < len; i++) { itvl = results[i]; itvl.low = new Quantity(itvl.low, result_units); itvl.high = new Quantity(itvl.high, result_units); } return results; }; Expand.prototype.expandNumericInterval = function(interval, per) { if (!(per.unit === '1' || per.unit === '')) { return null; } return this.makeNumericIntervalList(interval.low, interval.high, interval.lowClosed, interval.highClosed, per.value); }; Expand.prototype.makeNumericIntervalList = function(low, high, lowClosed, highClosed, perValue) { var current_high, current_low, decimalPrecision, intervalToAdd, perIsDecimal, perUnitSize, results; perIsDecimal = perValue.toString().includes('.'); decimalPrecision = perIsDecimal ? 8 : 0; low = lowClosed ? low : successor(low); high = highClosed ? high : predecessor(high); low = truncateDecimal(low, decimalPrecision); high = truncateDecimal(high, decimalPrecision); if (low > high) { return []; } if (!((low != null) && (high != null))) { return []; } perUnitSize = perIsDecimal ? 0.00000001 : 1; if (low === high && Number.isInteger(low) && Number.isInteger(high) && !Number.isInteger(perValue)) { high = parseFloat((high + 1).toFixed(decimalPrecision)); } current_low = low; results = []; if (perValue > (high - low + perUnitSize)) { return []; } current_high = parseFloat((current_low + perValue - perUnitSize).toFixed(decimalPrecision)); intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); while (intervalToAdd.high <= high) { results.push(intervalToAdd); current_low = parseFloat((current_low + perValue).toFixed(decimalPrecision)); current_high = parseFloat((current_low + perValue - perUnitSize).toFixed(decimalPrecision)); intervalToAdd = new dtivl.Interval(current_low, current_high, true, true); } return results; }; return Expand; })(Expression); module.exports.Collapse = Collapse = (function(superClass) { extend(Collapse, superClass); function Collapse(json) { Collapse.__super__.constructor.apply(this, arguments); } Collapse.prototype.exec = function(ctx) { var intervals, perWidth, ref3; ref3 = this.execArgs(ctx), intervals = ref3[0], perWidth = ref3[1]; return collapseIntervals(intervals, perWidth); }; return Collapse; })(Expression); collapseIntervals = function(intervals, perWidth) { var a, b, collapsedIntervals, i, interval, intervalsClone, len, ref3, ref4, ref5, ref6; intervalsClone = []; for (i = 0, len = intervals.length; i < len; i++) { interval = intervals[i]; if (interval != null) { intervalsClone.push(interval.copy()); } } if (intervals == null) { return null; } else if ((intervalsClone != null ? intervalsClone.length : void 0) <= 1) { return intervalsClone; } else { if (perWidth == null) { perWidth = intervalsClone[0].getPointSize(); } intervalsClone.sort(function(a, b) { var ref3, ref4; if (typeof ((ref3 = a.low) != null ? ref3.before : void 0) === 'function') { if ((b.low != null) && a.low.before(b.low)) { return -1; } if ((b.low == null) || a.low.after(b.low)) { return 1; } } else if ((a.low != null) && (b.low != null)) { if (a.low < b.low) { return -1; } if (a.low > b.low) { return 1; } } else if ((a.low != null) && (b.low == null)) { return 1; } else if ((a.low == null) && (b.low != null)) { return -1; } if (typeof ((ref4 = a.high) != null ? ref4.before : void 0) === 'function') { if ((b.high == null) || a.high.before(b.high)) { return -1; } if (a.high.after(b.high)) { return 1; } } else if ((a.high != null) && (b.high != null)) { if (a.high < b.high) { return -1; } if (a.high > b.high) { return 1; } } else if ((a.high != null) && (b.high == null)) { return -1; } else if ((a.high == null) && (b.high != null)) { return 1; } return 0; }); collapsedIntervals = []; a = intervalsClone.shift(); b = intervalsClone.shift(); while (b) { if (typeof ((ref3 = b.low) != null ? ref3.durationBetween : void 0) === 'function') { if ((ref4 = a.high) != null ? ref4.sameOrAfter(b.low) : void 0) { if ((b.high == null) || b.high.after(a.high)) { a.high = b.high; } } else if (((ref5 = a.high) != null ? ref5.durationBetween(b.low, perWidth.unit).high : void 0) <= perWidth.value) { a.high = b.high; } else { collapsedIntervals.push(a); a = b; } } else if (typeof ((ref6 = b.low) != null ? ref6.sameOrBefore : void 0) === 'function') { if ((a.high != null) && b.low.sameOrBefore(doAddition(a.high, perWidth))) { if ((b.high == null) || b.high.after(a.high)) { a.high = b.high; } } else { collapsedIntervals.push(a); a = b; } } else { if ((b.low - a.high) <= perWidth.value) { if (b.high > a.high || (b.high == null)) { a.high = b.high; } } else { collapsedIntervals.push(a); a = b; } } b = intervalsClone.shift(); } collapsedIntervals.push(a); return collapsedIntervals; } }; truncateDecimal = function(decimal, decimalPlaces) { var re; re = new RegExp('^-?\\d+(?:\.\\d{0,' + (decimalPlaces || -1) + '})?'); return parseFloat(decimal.toString().match(re)[0]); }; }).call(this); },{"../datatypes/interval":124,"../datatypes/logic":125,"../datatypes/quantity":126,"../util/comparison":250,"../util/math":251,"./builder":131,"./expression":137}],142:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var CodeDef, CodeSystemDef, ConceptDef, ExpressionDef, FunctionDef, Library, ParameterDef, Results, ValueSetDef, ref; module.exports.Library = Library = (function() { function Library(json, libraryManager) { var code, codesystem, concept, expr, i, j, k, l, len, len1, len2, len3, len4, len5, len6, len7, m, n, o, p, param, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref19, ref2, ref20, ref21, ref22, ref23, ref3, ref4, ref5, ref6, ref7, ref8, ref9, u, valueset; this.source = json; this.usings = []; ref2 = (ref = (ref1 = json.library.usings) != null ? ref1.def : void 0) != null ? ref : []; for (i = 0, len = ref2.length; i < len; i++) { u = ref2[i]; if (u.localIdentifier !== "System") { this.usings.push({ "name": u.localIdentifier, "version": u.version }); } } this.parameters = {}; ref5 = (ref3 = (ref4 = json.library.parameters) != null ? ref4.def : void 0) != null ? ref3 : []; for (j = 0, len1 = ref5.length; j < len1; j++) { param = ref5[j]; this.parameters[param.name] = new ParameterDef(param); } this.codesystems = {}; ref8 = (ref6 = (ref7 = json.library.codeSystems) != null ? ref7.def : void 0) != null ? ref6 : []; for (k = 0, len2 = ref8.length; k < len2; k++) { codesystem = ref8[k]; this.codesystems[codesystem.name] = new CodeSystemDef(codesystem); } this.valuesets = {}; ref11 = (ref9 = (ref10 = json.library.valueSets) != null ? ref10.def : void 0) != null ? ref9 : []; for (l = 0, len3 = ref11.length; l < len3; l++) { valueset = ref11[l]; this.valuesets[valueset.name] = new ValueSetDef(valueset); } this.codes = {}; ref14 = (ref12 = (ref13 = json.library.codes) != null ? ref13.def : void 0) != null ? ref12 : []; for (m = 0, len4 = ref14.length; m < len4; m++) { code = ref14[m]; this.codes[code.name] = new CodeDef(code); } this.concepts = {}; ref17 = (ref15 = (ref16 = json.library.concepts) != null ? ref16.def : void 0) != null ? ref15 : []; for (n = 0, len5 = ref17.length; n < len5; n++) { concept = ref17[n]; this.concepts[concept.name] = new ConceptDef(concept); } this.expressions = {}; ref20 = (ref18 = (ref19 = json.library.statements) != null ? ref19.def : void 0) != null ? ref18 : []; for (o = 0, len6 = ref20.length; o < len6; o++) { expr = ref20[o]; this.expressions[expr.name] = expr.type === "FunctionDef" ? new FunctionDef(expr) : new ExpressionDef(expr); } this.includes = {}; ref23 = (ref21 = (ref22 = json.library.includes) != null ? ref22.def : void 0) != null ? ref21 : []; for (p = 0, len7 = ref23.length; p < len7; p++) { expr = ref23[p]; if (libraryManager) { this.includes[expr.localIdentifier] = libraryManager.resolve(expr.path, expr.version); } } } Library.prototype.get = function(identifier) { return this.expressions[identifier] || this.includes[identifier]; }; Library.prototype.getValueSet = function(identifier, libraryName) { var ref; if (this.valuesets[identifier] != null) { return this.valuesets[identifier]; } return (ref = this.includes[libraryName]) != null ? ref.valuesets[identifier] : void 0; }; Library.prototype.getCodeSystem = function(identifier) { return this.codesystems[identifier]; }; Library.prototype.getCode = function(identifier) { return this.codes[identifier]; }; Library.prototype.getConcept = function(identifier) { return this.concepts[identifier]; }; Library.prototype.getParameter = function(name) { return this.parameters[name]; }; return Library; })(); ref = require('./expressions'), ExpressionDef = ref.ExpressionDef, FunctionDef = ref.FunctionDef, ParameterDef = ref.ParameterDef, ValueSetDef = ref.ValueSetDef, CodeSystemDef = ref.CodeSystemDef, CodeDef = ref.CodeDef, ConceptDef = ref.ConceptDef; Results = require('../runtime/results').Results; }).call(this); },{"../runtime/results":249,"./expressions":138}],143:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Current, Distinct, Exists, Expression, Filter, First, Flatten, ForEach, IndexOf, Last, List, SingletonFrom, Times, ToList, UnimplementedExpression, ValueSet, build, doContains, doDistinct, doIncludes, equals, ref, removeDuplicateNulls, typeIsArray, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; ValueSet = require('../datatypes/datatypes').ValueSet; build = require('./builder').build; typeIsArray = require('../util/util').typeIsArray; equals = require('../util/comparison').equals; module.exports.List = List = (function(superClass) { extend(List, superClass); function List(json) { var ref1; List.__super__.constructor.apply(this, arguments); this.elements = (ref1 = build(json.element)) != null ? ref1 : []; } Object.defineProperties(List.prototype, { isList: { get: function() { return true; } } }); List.prototype.exec = function(ctx) { var item, j, len, ref1, results; ref1 = this.elements; results = []; for (j = 0, len = ref1.length; j < len; j++) { item = ref1[j]; results.push(item.execute(ctx)); } return results; }; return List; })(Expression); module.exports.Exists = Exists = (function(superClass) { extend(Exists, superClass); function Exists(json) { Exists.__super__.constructor.apply(this, arguments); } Exists.prototype.exec = function(ctx) { var item, j, len, list; list = this.execArgs(ctx); if ((list != null ? list.length : void 0) > 0) { for (j = 0, len = list.length; j < len; j++) { item = list[j]; if (item !== null) { return true; } } } return false; }; return Exists; })(Expression); module.exports.doUnion = function(a, b) { var distinct; distinct = doDistinct(a.concat(b)); return removeDuplicateNulls(distinct); }; module.exports.doExcept = function(a, b) { var distinct, itm, j, len, results, setList; distinct = doDistinct(a); setList = removeDuplicateNulls(distinct); results = []; for (j = 0, len = setList.length; j < len; j++) { itm = setList[j]; if (!doContains(b, itm)) { results.push(itm); } } return results; }; module.exports.doIntersect = function(a, b) { var distinct, itm, j, len, results, setList; distinct = doDistinct(a); setList = removeDuplicateNulls(distinct); results = []; for (j = 0, len = setList.length; j < len; j++) { itm = setList[j]; if (doContains(b, itm)) { results.push(itm); } } return results; }; module.exports.Times = Times = (function(superClass) { extend(Times, superClass); function Times() { return Times.__super__.constructor.apply(this, arguments); } return Times; })(UnimplementedExpression); module.exports.Filter = Filter = (function(superClass) { extend(Filter, superClass); function Filter() { return Filter.__super__.constructor.apply(this, arguments); } return Filter; })(UnimplementedExpression); module.exports.SingletonFrom = SingletonFrom = (function(superClass) { extend(SingletonFrom, superClass); function SingletonFrom(json) { SingletonFrom.__super__.constructor.apply(this, arguments); } SingletonFrom.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if ((arg != null) && arg.length > 1) { throw new Error('IllegalArgument: \'SingletonFrom\' requires a 0 or 1 arg array'); } else if ((arg != null) && arg.length === 1) { return arg[0]; } else { return null; } }; return SingletonFrom; })(Expression); module.exports.ToList = ToList = (function(superClass) { extend(ToList, superClass); function ToList(json) { ToList.__super__.constructor.apply(this, arguments); } ToList.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg != null) { return [arg]; } else { return []; } }; return ToList; })(Expression); module.exports.IndexOf = IndexOf = (function(superClass) { extend(IndexOf, superClass); function IndexOf(json) { IndexOf.__super__.constructor.apply(this, arguments); this.source = build(json.source); this.element = build(json.element); } IndexOf.prototype.exec = function(ctx) { var el, i, index, itm, j, len, src; src = this.source.execute(ctx); el = this.element.execute(ctx); if ((src == null) || (el == null)) { return null; } for (i = j = 0, len = src.length; j < len; i = ++j) { itm = src[i]; if (equals(itm, el)) { index = i; break; } } if (index != null) { return index; } else { return -1; } }; return IndexOf; })(Expression); module.exports.doContains = doContains = function(container, item) { var element, j, len; for (j = 0, len = container.length; j < len; j++) { element = container[j]; if (equals(element, item)) { return true; } } return false; }; module.exports.doIncludes = doIncludes = function(list, sublist) { return sublist.every(function(x) { return doContains(list, x); }); }; module.exports.doProperIncludes = function(list, sublist) { return list.length > sublist.length && doIncludes(list, sublist); }; module.exports.ForEach = ForEach = (function(superClass) { extend(ForEach, superClass); function ForEach() { return ForEach.__super__.constructor.apply(this, arguments); } return ForEach; })(UnimplementedExpression); module.exports.Flatten = Flatten = (function(superClass) { extend(Flatten, superClass); function Flatten(json) { Flatten.__super__.constructor.apply(this, arguments); } Flatten.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (typeIsArray(arg) && (arg.every(function(x) { return typeIsArray(x); }))) { return arg.reduce((function(x, y) { return x.concat(y); }), []); } else { return arg; } }; return Flatten; })(Expression); module.exports.Distinct = Distinct = (function(superClass) { extend(Distinct, superClass); function Distinct(json) { Distinct.__super__.constructor.apply(this, arguments); } Distinct.prototype.exec = function(ctx) { var result; result = this.execArgs(ctx); if (result == null) { return null; } return doDistinct(result); }; return Distinct; })(Expression); doDistinct = function(list) { var distinct; distinct = []; list.filter(function(item) { var isNew; isNew = distinct.every(function(seenItem) { return !equals(item, seenItem); }); if (isNew) { distinct.push(item); } return isNew; }); return distinct; }; removeDuplicateNulls = function(list) { var firstNullFound, item, j, len, setList; firstNullFound = false; setList = []; for (j = 0, len = list.length; j < len; j++) { item = list[j]; if (item !== null) { setList.push(item); } if (item === null && !firstNullFound) { setList.push(item); firstNullFound = true; } } return setList; }; module.exports.Current = Current = (function(superClass) { extend(Current, superClass); function Current() { return Current.__super__.constructor.apply(this, arguments); } return Current; })(UnimplementedExpression); module.exports.First = First = (function(superClass) { extend(First, superClass); function First(json) { First.__super__.constructor.apply(this, arguments); this.source = build(json.source); } First.prototype.exec = function(ctx) { var src; src = this.source.exec(ctx); if ((src != null) && typeIsArray(src) && src.length > 0) { return src[0]; } else { return null; } }; return First; })(Expression); module.exports.Last = Last = (function(superClass) { extend(Last, superClass); function Last(json) { Last.__super__.constructor.apply(this, arguments); this.source = build(json.source); } Last.prototype.exec = function(ctx) { var src; src = this.source.exec(ctx); if ((src != null) && typeIsArray(src) && src.length > 0) { return src[src.length - 1]; } else { return null; } }; return Last; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"../util/comparison":250,"../util/util":252,"./builder":131,"./expression":137}],144:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var BooleanLiteral, DecimalLiteral, Expression, IntegerLiteral, Literal, StringLiteral, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; module.exports.Literal = Literal = (function(superClass) { extend(Literal, superClass); Literal.from = function(json) { switch (json.valueType) { case "{urn:hl7-org:elm-types:r1}Boolean": return new BooleanLiteral(json); case "{urn:hl7-org:elm-types:r1}Integer": return new IntegerLiteral(json); case "{urn:hl7-org:elm-types:r1}Decimal": return new DecimalLiteral(json); case "{urn:hl7-org:elm-types:r1}String": return new StringLiteral(json); default: return new Literal(json); } }; function Literal(json) { Literal.__super__.constructor.apply(this, arguments); this.valueType = json.valueType; this.value = json.value; } Literal.prototype.exec = function(ctx) { return this.value; }; return Literal; })(Expression); module.exports.BooleanLiteral = BooleanLiteral = (function(superClass) { extend(BooleanLiteral, superClass); function BooleanLiteral(json) { BooleanLiteral.__super__.constructor.apply(this, arguments); this.value = this.value === 'true'; } Object.defineProperties(BooleanLiteral.prototype, { isBooleanLiteral: { get: function() { return true; } } }); BooleanLiteral.prototype.exec = function(ctx) { return this.value; }; return BooleanLiteral; })(Literal); module.exports.IntegerLiteral = IntegerLiteral = (function(superClass) { extend(IntegerLiteral, superClass); function IntegerLiteral(json) { IntegerLiteral.__super__.constructor.apply(this, arguments); this.value = parseInt(this.value, 10); } Object.defineProperties(IntegerLiteral.prototype, { isIntegerLiteral: { get: function() { return true; } } }); IntegerLiteral.prototype.exec = function(ctx) { return this.value; }; return IntegerLiteral; })(Literal); module.exports.DecimalLiteral = DecimalLiteral = (function(superClass) { extend(DecimalLiteral, superClass); function DecimalLiteral(json) { DecimalLiteral.__super__.constructor.apply(this, arguments); this.value = parseFloat(this.value); } Object.defineProperties(DecimalLiteral.prototype, { isDecimalLiteral: { get: function() { return true; } } }); DecimalLiteral.prototype.exec = function(ctx) { return this.value; }; return DecimalLiteral; })(Literal); module.exports.StringLiteral = StringLiteral = (function(superClass) { extend(StringLiteral, superClass); function StringLiteral(json) { StringLiteral.__super__.constructor.apply(this, arguments); } Object.defineProperties(StringLiteral.prototype, { isStringLiteral: { get: function() { return true; } } }); StringLiteral.prototype.exec = function(ctx) { return this.value.replace(/\\'/g, "'").replace(/\\"/g, "\""); }; return StringLiteral; })(Literal); }).call(this); },{"./expression":137}],145:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var And, Expression, IsFalse, IsTrue, Not, Or, ThreeValuedLogic, Xor, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; ThreeValuedLogic = require('../datatypes/datatypes').ThreeValuedLogic; module.exports.And = And = (function(superClass) { extend(And, superClass); function And(json) { And.__super__.constructor.apply(this, arguments); } And.prototype.exec = function(ctx) { return ThreeValuedLogic.and.apply(ThreeValuedLogic, this.execArgs(ctx)); }; return And; })(Expression); module.exports.Or = Or = (function(superClass) { extend(Or, superClass); function Or(json) { Or.__super__.constructor.apply(this, arguments); } Or.prototype.exec = function(ctx) { return ThreeValuedLogic.or.apply(ThreeValuedLogic, this.execArgs(ctx)); }; return Or; })(Expression); module.exports.Not = Not = (function(superClass) { extend(Not, superClass); function Not(json) { Not.__super__.constructor.apply(this, arguments); } Not.prototype.exec = function(ctx) { return ThreeValuedLogic.not(this.execArgs(ctx)); }; return Not; })(Expression); module.exports.Xor = Xor = (function(superClass) { extend(Xor, superClass); function Xor(json) { Xor.__super__.constructor.apply(this, arguments); } Xor.prototype.exec = function(ctx) { return ThreeValuedLogic.xor.apply(ThreeValuedLogic, this.execArgs(ctx)); }; return Xor; })(Expression); module.exports.IsTrue = IsTrue = (function(superClass) { extend(IsTrue, superClass); function IsTrue(json) { IsTrue.__super__.constructor.apply(this, arguments); } IsTrue.prototype.exec = function(ctx) { return true === this.execArgs(ctx); }; return IsTrue; })(Expression); module.exports.IsFalse = IsFalse = (function(superClass) { extend(IsFalse, superClass); function IsFalse(json) { IsFalse.__super__.constructor.apply(this, arguments); } IsFalse.prototype.exec = function(ctx) { return false === this.execArgs(ctx); }; return IsFalse; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"./expression":137}],146:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Coalesce, Expression, IsNull, Null, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; module.exports.Null = Null = (function(superClass) { extend(Null, superClass); function Null(json) { Null.__super__.constructor.apply(this, arguments); } Null.prototype.exec = function(ctx) { return null; }; return Null; })(Expression); module.exports.IsNull = IsNull = (function(superClass) { extend(IsNull, superClass); function IsNull(json) { IsNull.__super__.constructor.apply(this, arguments); } IsNull.prototype.exec = function(ctx) { return this.execArgs(ctx) == null; }; return IsNull; })(Expression); module.exports.Coalesce = Coalesce = (function(superClass) { extend(Coalesce, superClass); function Coalesce(json) { Coalesce.__super__.constructor.apply(this, arguments); } Coalesce.prototype.exec = function(ctx) { var arg, i, item, j, len, len1, ref, result; ref = this.args; for (i = 0, len = ref.length; i < len; i++) { arg = ref[i]; result = arg.execute(ctx); if (this.args.length === 1 && Array.isArray(result)) { for (j = 0, len1 = result.length; j < len1; j++) { item = result[j]; if (item != null) { return item; } } } else { if (result != null) { return result; } } } return null; }; return Coalesce; })(Expression); }).call(this); },{"./expression":137}],147:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var After, Contains, DT, DateTime, Equal, Equivalent, Except, Exception, Expression, IVL, In, IncludedIn, Includes, Indexer, Intersect, LIST, Length, NotEqual, ProperIncludedIn, ProperIncludes, STRING, SameAs, SameOrAfter, SameOrBefore, ThreeValuedLogic, Union, build, equals, equivalent, ref, typeIsArray, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; ThreeValuedLogic = require('../datatypes/logic').ThreeValuedLogic; DateTime = require('../datatypes/datetime').DateTime; Exception = require('../datatypes/exception').Exception; typeIsArray = require('../util/util').typeIsArray; ref = require('../util/comparison'), equals = ref.equals, equivalent = ref.equivalent; build = require('./builder').build; DT = require('./datetime'); LIST = require('./list'); IVL = require('./interval'); STRING = require('./string'); module.exports.Equal = Equal = (function(superClass) { extend(Equal, superClass); function Equal(json) { Equal.__super__.constructor.apply(this, arguments); } Equal.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx); if (!((args[0] != null) && (args[1] != null))) { return null; } return equals.apply(null, this.execArgs(ctx)); }; return Equal; })(Expression); module.exports.Equivalent = Equivalent = (function(superClass) { extend(Equivalent, superClass); function Equivalent(json) { Equivalent.__super__.constructor.apply(this, arguments); } Equivalent.prototype.exec = function(ctx) { var a, b, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[1]; if ((a == null) && (b == null)) { return true; } else if ((a == null) || (b == null)) { return false; } else { return equivalent(a, b); } }; return Equivalent; })(Expression); module.exports.NotEqual = NotEqual = (function(superClass) { extend(NotEqual, superClass); function NotEqual(json) { NotEqual.__super__.constructor.apply(this, arguments); } NotEqual.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx); if (!((args[0] != null) && (args[1] != null))) { return null; } return ThreeValuedLogic.not(equals.apply(null, this.execArgs(ctx))); }; return NotEqual; })(Expression); module.exports.Union = Union = (function(superClass) { extend(Union, superClass); function Union(json) { Union.__super__.constructor.apply(this, arguments); } Union.prototype.exec = function(ctx) { var a, b, lib, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[1]; if ((a == null) || (b == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(a): return LIST; default: return IVL; } })(); return lib.doUnion(a, b); }; return Union; })(Expression); module.exports.Except = Except = (function(superClass) { extend(Except, superClass); function Except(json) { Except.__super__.constructor.apply(this, arguments); } Except.prototype.exec = function(ctx) { var a, b, lib, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[1]; if ((a == null) || (b == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(a): return LIST; default: return IVL; } })(); return lib.doExcept(a, b); }; return Except; })(Expression); module.exports.Intersect = Intersect = (function(superClass) { extend(Intersect, superClass); function Intersect(json) { Intersect.__super__.constructor.apply(this, arguments); } Intersect.prototype.exec = function(ctx) { var a, b, lib, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[1]; if ((a == null) || (b == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(a): return LIST; default: return IVL; } })(); return lib.doIntersect(a, b); }; return Intersect; })(Expression); module.exports.Indexer = Indexer = (function(superClass) { extend(Indexer, superClass); function Indexer(json) { Indexer.__super__.constructor.apply(this, arguments); } Indexer.prototype.exec = function(ctx) { var index, operand, ref1; ref1 = this.execArgs(ctx), operand = ref1[0], index = ref1[1]; if ((operand == null) || (index == null)) { return null; } if (index < 0 || index >= operand.length) { return null; } return operand[index]; }; return Indexer; })(Expression); module.exports.In = In = (function(superClass) { extend(In, superClass); function In(json) { var ref1; In.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } In.prototype.exec = function(ctx) { var container, item, lib, ref1; ref1 = this.execArgs(ctx), item = ref1[0], container = ref1[1]; if ((container == null) || (item == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(container): return LIST; default: return IVL; } })(); return lib.doContains(container, item, this.precision); }; return In; })(Expression); module.exports.Contains = Contains = (function(superClass) { extend(Contains, superClass); function Contains(json) { var ref1; Contains.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } Contains.prototype.exec = function(ctx) { var container, item, lib, ref1; ref1 = this.execArgs(ctx), container = ref1[0], item = ref1[1]; if ((container == null) || (item == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(container): return LIST; default: return IVL; } })(); return lib.doContains(container, item, this.precision); }; return Contains; })(Expression); module.exports.Includes = Includes = (function(superClass) { extend(Includes, superClass); function Includes(json) { var ref1; Includes.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } Includes.prototype.exec = function(ctx) { var contained, container, lib, ref1; ref1 = this.execArgs(ctx), container = ref1[0], contained = ref1[1]; if ((container == null) || (contained == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(container): return LIST; default: return IVL; } })(); return lib.doIncludes(container, contained, this.precision); }; return Includes; })(Expression); module.exports.IncludedIn = IncludedIn = (function(superClass) { extend(IncludedIn, superClass); function IncludedIn(json) { var ref1; IncludedIn.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } IncludedIn.prototype.exec = function(ctx) { var contained, container, lib, ref1; ref1 = this.execArgs(ctx), contained = ref1[0], container = ref1[1]; if ((container == null) || (contained == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(container): return LIST; default: return IVL; } })(); return lib.doIncludes(container, contained, this.precision); }; return IncludedIn; })(Expression); module.exports.ProperIncludes = ProperIncludes = (function(superClass) { extend(ProperIncludes, superClass); function ProperIncludes(json) { var ref1; ProperIncludes.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } ProperIncludes.prototype.exec = function(ctx) { var contained, container, lib, ref1; ref1 = this.execArgs(ctx), container = ref1[0], contained = ref1[1]; if ((container == null) || (contained == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(container): return LIST; default: return IVL; } })(); return lib.doProperIncludes(container, contained, this.precision); }; return ProperIncludes; })(Expression); module.exports.ProperIncludedIn = ProperIncludedIn = (function(superClass) { extend(ProperIncludedIn, superClass); function ProperIncludedIn(json) { var ref1; ProperIncludedIn.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } ProperIncludedIn.prototype.exec = function(ctx) { var contained, container, lib, ref1; ref1 = this.execArgs(ctx), contained = ref1[0], container = ref1[1]; if ((container == null) || (contained == null)) { return null; } lib = (function() { switch (false) { case !typeIsArray(container): return LIST; default: return IVL; } })(); return lib.doProperIncludes(container, contained, this.precision); }; return ProperIncludedIn; })(Expression); module.exports.Length = Length = (function(superClass) { extend(Length, superClass); function Length(json) { Length.__super__.constructor.apply(this, arguments); } Length.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg != null) { return arg.length; } else { return null; } }; return Length; })(Expression); module.exports.After = After = (function(superClass) { extend(After, superClass); function After(json) { var ref1; After.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } After.prototype.exec = function(ctx) { var a, b, lib, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[1]; if ((a == null) || (b == null)) { return null; } lib = (function() { switch (false) { case !(a instanceof DateTime): return DT; default: return IVL; } })(); return lib.doAfter(a, b, this.precision); }; return After; })(Expression); module.exports.Before = After = (function(superClass) { extend(After, superClass); function After(json) { var ref1; After.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } After.prototype.exec = function(ctx) { var a, b, lib, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[1]; if ((a == null) || (b == null)) { return null; } lib = (function() { switch (false) { case !(a instanceof DateTime): return DT; default: return IVL; } })(); return lib.doBefore(a, b, this.precision); }; return After; })(Expression); module.exports.SameAs = SameAs = (function(superClass) { extend(SameAs, superClass); function SameAs(json) { SameAs.__super__.constructor.apply(this, arguments); this.precision = json.precision; } SameAs.prototype.exec = function(ctx) { var a, b, ref1, ref2; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[1]; if ((a != null) && (b != null)) { return a.sameAs(b, (ref2 = this.precision) != null ? ref2.toLowerCase() : void 0); } else { return null; } }; return SameAs; })(Expression); module.exports.SameOrAfter = SameOrAfter = (function(superClass) { extend(SameOrAfter, superClass); function SameOrAfter(json) { SameOrAfter.__super__.constructor.apply(this, arguments); this.precision = json.precision; } SameOrAfter.prototype.exec = function(ctx) { var d1, d2, ref1, ref2; ref1 = this.execArgs(ctx), d1 = ref1[0], d2 = ref1[1]; if ((d1 != null) && (d2 != null)) { return d1.sameOrAfter(d2, (ref2 = this.precision) != null ? ref2.toLowerCase() : void 0); } else { return null; } }; return SameOrAfter; })(Expression); module.exports.SameOrBefore = SameOrBefore = (function(superClass) { extend(SameOrBefore, superClass); function SameOrBefore(json) { SameOrBefore.__super__.constructor.apply(this, arguments); this.precision = json.precision; } SameOrBefore.prototype.exec = function(ctx) { var d1, d2, ref1, ref2; ref1 = this.execArgs(ctx), d1 = ref1[0], d2 = ref1[1]; if ((d1 != null) && (d2 != null)) { return d1.sameOrBefore(d2, (ref2 = this.precision) != null ? ref2.toLowerCase() : void 0); } else { return null; } }; return SameOrBefore; })(Expression); }).call(this); },{"../datatypes/datetime":122,"../datatypes/exception":123,"../datatypes/logic":125,"../util/comparison":250,"../util/util":252,"./builder":131,"./datetime":135,"./expression":137,"./interval":141,"./list":143,"./string":153}],148:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, ParameterDef, ParameterRef, build, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; build = require('./builder').build; module.exports.ParameterDef = ParameterDef = (function(superClass) { extend(ParameterDef, superClass); function ParameterDef(json) { ParameterDef.__super__.constructor.apply(this, arguments); this.name = json.name; this["default"] = build(json["default"]); this.parameterTypeSpecifier = json.parameterTypeSpecifier; } ParameterDef.prototype.exec = function(ctx) { var ref; if (((ctx != null ? ctx.parameters[this.name] : void 0) != null)) { return ctx.parameters[this.name]; } else if (this["default"] != null) { return (ref = this["default"]) != null ? ref.execute(ctx) : void 0; } else { return ctx.getParentParameter(this.name); } }; return ParameterDef; })(Expression); module.exports.ParameterRef = ParameterRef = (function(superClass) { extend(ParameterRef, superClass); function ParameterRef(json) { ParameterRef.__super__.constructor.apply(this, arguments); this.name = json.name; this.library = json.libraryName; } ParameterRef.prototype.exec = function(ctx) { var ref; ctx = this.library ? ctx.getLibraryContext(this.library) : ctx; return (ref = ctx.getParameter(this.name)) != null ? ref.execute(ctx) : void 0; }; return ParameterRef; })(Expression); }).call(this); },{"./builder":131,"./expression":137}],149:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Code, DT, Exception, Expression, FunctionRef, Quantity, ValueSet, build, ref, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; FunctionRef = require('./reusable').FunctionRef; ref = require('../datatypes/datatypes'), ValueSet = ref.ValueSet, Code = ref.Code; Exception = require('../datatypes/exception').Exception; build = require('./builder').build; DT = require('../datatypes/datatypes'); module.exports.Quantity = Quantity = (function(superClass) { extend(Quantity, superClass); function Quantity(json) { Quantity.__super__.constructor.apply(this, arguments); this.value = parseFloat(json.value); this.unit = json.unit; } Quantity.prototype.exec = function(ctx) { return new DT.Quantity(this.value, this.unit); }; return Quantity; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"../datatypes/exception":123,"./builder":131,"./expression":137,"./reusable":152}],150:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var AliasRef, AliasedQuerySource, ByColumn, ByDirection, ByExpression, Context, Expression, LetClause, MultiSource, Query, QueryLetRef, ReturnClause, Sort, SortClause, UnimplementedExpression, With, Without, allTrue, build, equals, ref, ref1, toDistinctList, typeIsArray, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; Context = require('../runtime/context').Context; build = require('./builder').build; ref1 = require('../util/util'), typeIsArray = ref1.typeIsArray, allTrue = ref1.allTrue; equals = require('../util/comparison').equals; module.exports.AliasedQuerySource = AliasedQuerySource = (function() { function AliasedQuerySource(json) { this.alias = json.alias; this.expression = build(json.expression); } return AliasedQuerySource; })(); module.exports.LetClause = LetClause = (function() { function LetClause(json) { this.identifier = json.identifier; this.expression = build(json.expression); } return LetClause; })(); module.exports.With = With = (function(superClass) { extend(With, superClass); function With(json) { With.__super__.constructor.apply(this, arguments); this.alias = json.alias; this.expression = build(json.expression); this.suchThat = build(json.suchThat); } With.prototype.exec = function(ctx) { var childCtx, rec, records, returns; records = this.expression.execute(ctx); this.isList = typeIsArray(records); records = this.isList ? records : [records]; returns = (function() { var i, len, results; results = []; for (i = 0, len = records.length; i < len; i++) { rec = records[i]; childCtx = ctx.childContext(); childCtx.set(this.alias, rec); results.push(this.suchThat.execute(childCtx)); } return results; }).call(this); return returns.some(function(x) { return x; }); }; return With; })(Expression); module.exports.Without = Without = (function(superClass) { extend(Without, superClass); function Without(json) { Without.__super__.constructor.apply(this, arguments); } Without.prototype.exec = function(ctx) { return !Without.__super__.exec.call(this, ctx); }; return Without; })(With); module.exports.Sort = Sort = (function(superClass) { extend(Sort, superClass); function Sort() { return Sort.__super__.constructor.apply(this, arguments); } return Sort; })(UnimplementedExpression); module.exports.ByDirection = ByDirection = (function(superClass) { extend(ByDirection, superClass); function ByDirection(json) { ByDirection.__super__.constructor.apply(this, arguments); this.direction = json.direction; this.low_order = this.direction === "asc" ? -1 : 1; this.high_order = this.low_order * -1; } ByDirection.prototype.exec = function(ctx, a, b) { if (a === b) { return 0; } else if (a.isQuantity && b.isQuantity) { if (a.before(b)) { return this.low_order; } else { return this.high_order; } } else if (a < b) { return this.low_order; } else { return this.high_order; } }; return ByDirection; })(Expression); module.exports.ByExpression = ByExpression = (function(superClass) { extend(ByExpression, superClass); function ByExpression(json) { ByExpression.__super__.constructor.apply(this, arguments); this.expression = build(json.expression); this.direction = json.direction; this.low_order = this.direction === "asc" ? -1 : 1; this.high_order = this.low_order * -1; } ByExpression.prototype.exec = function(ctx, a, b) { var a_val, b_val, sctx; sctx = ctx.childContext(a); a_val = this.expression.execute(sctx); sctx = ctx.childContext(b); b_val = this.expression.execute(sctx); if (a_val === b_val) { return 0; } else if (a_val.isQuantity && b_val.isQuantity) { if (a_val.before(b_val)) { return this.low_order; } else { return this.high_order; } } else if (a_val < b_val) { return this.low_order; } else { return this.high_order; } }; return ByExpression; })(Expression); module.exports.ByColumn = ByColumn = (function(superClass) { extend(ByColumn, superClass); function ByColumn(json) { ByColumn.__super__.constructor.apply(this, arguments); this.expression = build({ "name": json.path, "type": "IdentifierRef" }); } return ByColumn; })(ByExpression); module.exports.ReturnClause = ReturnClause = ReturnClause = (function() { function ReturnClause(json) { var ref2; this.expression = build(json.expression); this.distinct = (ref2 = json.distinct) != null ? ref2 : true; } return ReturnClause; })(); module.exports.SortClause = SortClause = SortClause = (function() { function SortClause(json) { this.by = build(json != null ? json.by : void 0); } SortClause.prototype.sort = function(ctx, values) { if (this.by) { return values.sort((function(_this) { return function(a, b) { var i, item, len, order, ref2; order = 0; ref2 = _this.by; for (i = 0, len = ref2.length; i < len; i++) { item = ref2[i]; order = item.exec(ctx, a, b); if (order !== 0) { break; } } return order; }; })(this)); } }; return SortClause; })(); toDistinctList = function(xList) { var i, inYList, j, len, len1, x, y, yList; yList = []; for (i = 0, len = xList.length; i < len; i++) { x = xList[i]; inYList = false; for (j = 0, len1 = yList.length; j < len1; j++) { y = yList[j]; if (equals(x, y)) { inYList = true; } } if (!inYList) { yList.push(x); } } return yList; }; module.exports.Query = Query = (function(superClass) { extend(Query, superClass); function Query(json) { var d, s; Query.__super__.constructor.apply(this, arguments); this.sources = new MultiSource((function() { var i, len, ref2, results; ref2 = json.source; results = []; for (i = 0, len = ref2.length; i < len; i++) { s = ref2[i]; results.push(new AliasedQuerySource(s)); } return results; })()); this.letClauses = (function() { var i, len, ref2, ref3, results; ref3 = (ref2 = json["let"]) != null ? ref2 : []; results = []; for (i = 0, len = ref3.length; i < len; i++) { d = ref3[i]; results.push(new LetClause(d)); } return results; })(); this.relationship = json.relationship != null ? build(json.relationship) : []; this.where = build(json.where); this.returnClause = json["return"] != null ? new ReturnClause(json["return"]) : null; this.aliases = this.sources.aliases(); this.sortClause = json.sort != null ? new SortClause(json.sort) : null; } Query.prototype.exec = function(ctx) { var distinct, ref2, returnedValues; returnedValues = []; this.sources.forEach(ctx, (function(_this) { return function(rctx) { var child_ctx, def, i, len, passed, ref2, rel, relations, val; ref2 = _this.letClauses; for (i = 0, len = ref2.length; i < len; i++) { def = ref2[i]; rctx.set(def.identifier, def.expression.execute(rctx)); } relations = (function() { var j, len1, ref3, results; ref3 = this.relationship; results = []; for (j = 0, len1 = ref3.length; j < len1; j++) { rel = ref3[j]; child_ctx = rctx.childContext(); results.push(rel.execute(child_ctx)); } return results; }).call(_this); passed = allTrue(relations); passed = passed && (_this.where ? _this.where.execute(rctx) : passed); if (passed) { if (_this.returnClause != null) { val = _this.returnClause.expression.execute(rctx); return returnedValues.push(val); } else { if (_this.aliases.length === 1) { return returnedValues.push(rctx.get(_this.aliases[0])); } else { return returnedValues.push(rctx.context_values); } } } }; })(this)); distinct = this.returnClause != null ? this.returnClause.distinct : true; if (distinct) { returnedValues = toDistinctList(returnedValues); } if ((ref2 = this.sortClause) != null) { ref2.sort(ctx, returnedValues); } if (this.sources.returnsList()) { return returnedValues; } else { return returnedValues[0]; } }; return Query; })(Expression); module.exports.AliasRef = AliasRef = (function(superClass) { extend(AliasRef, superClass); function AliasRef(json) { AliasRef.__super__.constructor.apply(this, arguments); this.name = json.name; } AliasRef.prototype.exec = function(ctx) { return ctx != null ? ctx.get(this.name) : void 0; }; return AliasRef; })(Expression); module.exports.QueryLetRef = QueryLetRef = (function(superClass) { extend(QueryLetRef, superClass); function QueryLetRef(json) { QueryLetRef.__super__.constructor.apply(this, arguments); } return QueryLetRef; })(AliasRef); MultiSource = (function() { function MultiSource(sources) { this.sources = sources; this.alias = this.sources[0].alias; this.expression = this.sources[0].expression; this.isList = true; if (this.sources.length > 1) { this.rest = new MultiSource(this.sources.slice(1)); } } MultiSource.prototype.aliases = function() { var a; a = [this.alias]; if (this.rest) { a = a.concat(this.rest.aliases()); } return a; }; MultiSource.prototype.returnsList = function() { return this.isList || (this.rest && this.rest.returnsList()); }; MultiSource.prototype.forEach = function(ctx, func) { var i, len, rctx, rec, records, results; records = this.expression.execute(ctx); this.isList = typeIsArray(records); records = this.isList ? records : [records]; results = []; for (i = 0, len = records.length; i < len; i++) { rec = records[i]; rctx = new Context(ctx); rctx.set(this.alias, rec); if (this.rest) { results.push(this.rest.forEach(rctx, func)); } else { results.push(func(rctx)); } } return results; }; return MultiSource; })(); }).call(this); },{"../runtime/context":246,"../util/comparison":250,"../util/util":252,"./builder":131,"./expression":137}],151:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DT, Exception, Expression, Quantity, Ratio, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Exception = require('../datatypes/exception').Exception; Expression = require('./expression').Expression; Quantity = require('../datatypes/quantity').Quantity; DT = require('../datatypes/datatypes'); module.exports.Ratio = Ratio = (function(superClass) { extend(Ratio, superClass); function Ratio(json) { Ratio.__super__.constructor.apply(this, arguments); if (json.numerator == null) { throw new Error("Cannot create a ratio with an undefined numerator value"); } else { this.numerator = new Quantity(json.numerator.value, json.numerator.unit); } if (json.denominator == null) { throw new Error("Cannot create a ratio with an undefined denominator value"); } else { this.denominator = new Quantity(json.denominator.value, json.denominator.unit); } } Ratio.prototype.exec = function(ctx) { return new DT.Ratio(this.numerator, this.denominator); }; return Ratio; })(Expression); }).call(this); },{"../datatypes/datatypes":121,"../datatypes/exception":123,"../datatypes/quantity":126,"./expression":137}],152:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, ExpressionDef, ExpressionRef, FunctionDef, FunctionRef, IdentifierRef, OperandRef, build, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Expression = require('./expression').Expression; build = require('./builder').build; module.exports.ExpressionDef = ExpressionDef = (function(superClass) { extend(ExpressionDef, superClass); function ExpressionDef(json) { ExpressionDef.__super__.constructor.apply(this, arguments); this.name = json.name; this.context = json.context; this.expression = build(json.expression); } ExpressionDef.prototype.exec = function(ctx) { var ref, value; value = (ref = this.expression) != null ? ref.execute(ctx) : void 0; ctx.rootContext().set(this.name, value); return value; }; return ExpressionDef; })(Expression); module.exports.ExpressionRef = ExpressionRef = (function(superClass) { extend(ExpressionRef, superClass); function ExpressionRef(json) { ExpressionRef.__super__.constructor.apply(this, arguments); this.name = json.name; this.library = json.libraryName; } ExpressionRef.prototype.exec = function(ctx) { var value; ctx = this.library ? ctx.getLibraryContext(this.library) : ctx; value = ctx.get(this.name); if (value instanceof Expression) { value = value.execute(ctx); } return value; }; return ExpressionRef; })(Expression); module.exports.FunctionDef = FunctionDef = (function(superClass) { extend(FunctionDef, superClass); function FunctionDef(json) { FunctionDef.__super__.constructor.apply(this, arguments); this.name = json.name; this.expression = build(json.expression); this.parameters = json.operand; } FunctionDef.prototype.exec = function(ctx) { return this; }; return FunctionDef; })(Expression); module.exports.FunctionRef = FunctionRef = (function(superClass) { extend(FunctionRef, superClass); function FunctionRef(json) { FunctionRef.__super__.constructor.apply(this, arguments); this.name = json.name; this.library = json.libraryName; } FunctionRef.prototype.exec = function(ctx) { var args, child_ctx, functionDef, i, j, len, p, ref, ref1, ref2; functionDef = this.library ? (ref = ctx.get(this.library)) != null ? ref.get(this.name) : void 0 : ctx.get(this.name); args = this.execArgs(ctx); child_ctx = this.library ? (ref1 = ctx.getLibraryContext(this.library)) != null ? ref1.childContext() : void 0 : ctx.childContext(); if (args.length !== functionDef.parameters.length) { throw new Error("incorrect number of arguments supplied"); } ref2 = functionDef.parameters; for (i = j = 0, len = ref2.length; j < len; i = ++j) { p = ref2[i]; child_ctx.set(p.name, args[i]); } return functionDef.expression.execute(child_ctx); }; return FunctionRef; })(Expression); module.exports.OperandRef = OperandRef = (function(superClass) { extend(OperandRef, superClass); function OperandRef(json) { this.name = json.name; } OperandRef.prototype.exec = function(ctx) { return ctx.get(this.name); }; return OperandRef; })(Expression); module.exports.IdentifierRef = IdentifierRef = (function(superClass) { extend(IdentifierRef, superClass); function IdentifierRef(json) { IdentifierRef.__super__.constructor.apply(this, arguments); this.name = json.name; this.library = json.libraryName; } IdentifierRef.prototype.exec = function(ctx) { var _obj, curr_obj, curr_val, j, len, part, parts, ref, ref1, ref2, val; val = this.library ? (ref = ctx.get(this.library)) != null ? ref.get(this.name) : void 0 : ctx.get(this.name); if (val == null) { parts = this.name.split("."); val = ctx.get(part); if ((val != null) && parts.length > 1) { curr_obj = val; curr_val = null; ref1 = parts.slice(1); for (j = 0, len = ref1.length; j < len; j++) { part = ref1[j]; _obj = (ref2 = curr_obj != null ? curr_obj[part] : void 0) != null ? ref2 : curr_obj != null ? typeof curr_obj.get === "function" ? curr_obj.get(part) : void 0 : void 0; curr_obj = _obj instanceof Function ? _obj.call(curr_obj) : _obj; } val = curr_obj; } } if (val instanceof Function) { return val.call(ctx.context_values); } else { return val; } }; return IdentifierRef; })(Expression); }).call(this); },{"./builder":131,"./expression":137}],153:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Combine, Concatenate, EndsWith, Expression, Lower, Matches, PositionOf, Split, SplitOnMatches, StartsWith, Substring, UnimplementedExpression, Upper, build, ref, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; build = require('./builder').build; module.exports.Concatenate = Concatenate = (function(superClass) { extend(Concatenate, superClass); function Concatenate(json) { Concatenate.__super__.constructor.apply(this, arguments); } Concatenate.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx); if (args.some(function(x) { return x == null; })) { return null; } else { return args.reduce(function(x, y) { return x + y; }); } }; return Concatenate; })(Expression); module.exports.Combine = Combine = (function(superClass) { extend(Combine, superClass); function Combine(json) { Combine.__super__.constructor.apply(this, arguments); this.source = build(json.source); this.separator = build(json.separator); } Combine.prototype.exec = function(ctx) { var filteredArray, separator, source; source = this.source.execute(ctx); separator = this.separator != null ? this.separator.execute(ctx) : ''; if (source == null) { return null; } else { filteredArray = source.filter(function(x) { return x !== null && x !== void 0; }); if (filteredArray.length < 1) { return null; } else { return filteredArray.join(separator); } } }; return Combine; })(Expression); module.exports.Split = Split = (function(superClass) { extend(Split, superClass); function Split(json) { Split.__super__.constructor.apply(this, arguments); this.stringToSplit = build(json.stringToSplit); this.separator = build(json.separator); } Split.prototype.exec = function(ctx) { var separator, stringToSplit; stringToSplit = this.stringToSplit.execute(ctx); separator = this.separator.execute(ctx); if (!((stringToSplit != null) && (separator != null))) { return null; } else { return stringToSplit.split(separator); } }; return Split; })(Expression); module.exports.SplitOnMatches = SplitOnMatches = (function(superClass) { extend(SplitOnMatches, superClass); function SplitOnMatches(json) { SplitOnMatches.__super__.constructor.apply(this, arguments); this.stringToSplit = build(json.stringToSplit); this.separatorPattern = build(json.separatorPattern); } SplitOnMatches.prototype.exec = function(ctx) { var separatorPattern, stringToSplit; stringToSplit = this.stringToSplit.execute(ctx); separatorPattern = this.separatorPattern.execute(ctx); if (!((stringToSplit != null) && (separatorPattern != null))) { return null; } else { return stringToSplit.split(new RegExp(separatorPattern)); } }; return SplitOnMatches; })(Expression); module.exports.Upper = Upper = (function(superClass) { extend(Upper, superClass); function Upper(json) { Upper.__super__.constructor.apply(this, arguments); } Upper.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg != null) { return arg.toUpperCase(); } else { return null; } }; return Upper; })(Expression); module.exports.Lower = Lower = (function(superClass) { extend(Lower, superClass); function Lower(json) { Lower.__super__.constructor.apply(this, arguments); } Lower.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg != null) { return arg.toLowerCase(); } else { return null; } }; return Lower; })(Expression); module.exports.PositionOf = PositionOf = (function(superClass) { extend(PositionOf, superClass); function PositionOf(json) { PositionOf.__super__.constructor.apply(this, arguments); this.pattern = build(json.pattern); this.string = build(json.string); } PositionOf.prototype.exec = function(ctx) { var pattern, string; pattern = this.pattern.execute(ctx); string = this.string.execute(ctx); if (!((pattern != null) && (string != null))) { return null; } else { return string.indexOf(pattern); } }; return PositionOf; })(Expression); module.exports.Matches = Matches = (function(superClass) { extend(Matches, superClass); function Matches(json) { Matches.__super__.constructor.apply(this, arguments); } Matches.prototype.exec = function(ctx) { var pattern, ref1, string; ref1 = this.execArgs(ctx), string = ref1[0], pattern = ref1[1]; if (!((string != null) && (pattern != null))) { return null; } if (string.match(new RegExp(pattern))) { return true; } else { return false; } }; return Matches; })(Expression); module.exports.Substring = Substring = (function(superClass) { extend(Substring, superClass); function Substring(json) { Substring.__super__.constructor.apply(this, arguments); this.stringToSub = build(json.stringToSub); this.startIndex = build(json.startIndex); this.length = build(json['length']); } Substring.prototype.exec = function(ctx) { var length, startIndex, stringToSub; stringToSub = this.stringToSub.execute(ctx); startIndex = this.startIndex.execute(ctx); length = this.length != null ? this.length.execute(ctx) : null; if ((stringToSub == null) || (startIndex == null) || startIndex < 0 || startIndex >= stringToSub.length) { return null; } else if (length != null) { return stringToSub.substr(startIndex, length); } else { return stringToSub.substr(startIndex); } }; return Substring; })(Expression); module.exports.StartsWith = StartsWith = (function(superClass) { extend(StartsWith, superClass); function StartsWith(json) { StartsWith.__super__.constructor.apply(this, arguments); } StartsWith.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx); if (args.some(function(x) { return x == null; })) { return null; } else { return args[0].slice(0, args[1].length) === args[1]; } }; return StartsWith; })(Expression); module.exports.EndsWith = EndsWith = (function(superClass) { extend(EndsWith, superClass); function EndsWith(json) { EndsWith.__super__.constructor.apply(this, arguments); } EndsWith.prototype.exec = function(ctx) { var args; args = this.execArgs(ctx); if (args.some(function(x) { return x == null; })) { return null; } else { return args[1] === '' || args[0].slice(-args[1].length) === args[1]; } }; return EndsWith; })(Expression); }).call(this); },{"./builder":131,"./expression":137}],154:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, Property, Tuple, TupleElement, TupleElementDefinition, UnimplementedExpression, build, ref, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; build = require('./builder').build; module.exports.Property = Property = (function(superClass) { extend(Property, superClass); function Property(json) { Property.__super__.constructor.apply(this, arguments); this.scope = json.scope; this.source = build(json.source); this.path = json.path; } Property.prototype.exec = function(ctx) { var _obj, curr_obj, curr_val, i, len, obj, part, parts, ref1, ref2, val; obj = this.scope != null ? ctx.get(this.scope) : this.source; if (obj instanceof Expression) { obj = obj.execute(ctx); } val = (ref1 = obj != null ? obj[this.path] : void 0) != null ? ref1 : obj != null ? typeof obj.get === "function" ? obj.get(this.path) : void 0 : void 0; if (!val) { parts = this.path.split("."); curr_obj = obj; curr_val = null; for (i = 0, len = parts.length; i < len; i++) { part = parts[i]; _obj = (ref2 = curr_obj != null ? curr_obj[part] : void 0) != null ? ref2 : curr_obj != null ? typeof curr_obj.get === "function" ? curr_obj.get(part) : void 0 : void 0; curr_obj = _obj instanceof Function ? _obj.call(curr_obj) : _obj; } val = curr_obj != null ? curr_obj : null; } if (val instanceof Function) { return val.call(obj); } else { return val; } }; return Property; })(Expression); module.exports.Tuple = Tuple = (function(superClass) { extend(Tuple, superClass); function Tuple(json) { var el, elements; Tuple.__super__.constructor.apply(this, arguments); elements = json.element != null ? json.element : []; this.elements = (function() { var i, len, results; results = []; for (i = 0, len = elements.length; i < len; i++) { el = elements[i]; results.push({ name: el.name, value: build(el.value) }); } return results; })(); } Object.defineProperties(Tuple.prototype, { isTuple: { get: function() { return true; } } }); Tuple.prototype.exec = function(ctx) { var el, i, len, ref1, ref2, val; val = {}; ref1 = this.elements; for (i = 0, len = ref1.length; i < len; i++) { el = ref1[i]; val[el.name] = (ref2 = el.value) != null ? ref2.execute(ctx) : void 0; } return val; }; return Tuple; })(Expression); module.exports.TupleElement = TupleElement = (function(superClass) { extend(TupleElement, superClass); function TupleElement() { return TupleElement.__super__.constructor.apply(this, arguments); } return TupleElement; })(UnimplementedExpression); module.exports.TupleElementDefinition = TupleElementDefinition = (function(superClass) { extend(TupleElementDefinition, superClass); function TupleElementDefinition() { return TupleElementDefinition.__super__.constructor.apply(this, arguments); } return TupleElementDefinition; })(UnimplementedExpression); }).call(this); },{"./builder":131,"./expression":137}],155:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var As, CanConvertQuantity, Concept, Convert, ConvertQuantity, ConvertsToBoolean, ConvertsToDate, ConvertsToDateTime, ConvertsToDecimal, ConvertsToInteger, ConvertsToQuantity, ConvertsToRatio, ConvertsToString, ConvertsToTime, Date, DateTime, Expression, FunctionRef, IntervalTypeSpecifier, Is, ListTypeSpecifier, NamedTypeSpecifier, Quantity, Ratio, ToBoolean, ToConcept, ToDate, ToDateTime, ToDecimal, ToInteger, ToQuantity, ToRatio, ToString, ToTime, TupleTypeSpecifier, UnimplementedExpression, canConvertToType, isValidDecimal, isValidInteger, limitDecimalPrecision, normalizeMillisecondsField, parseQuantity, ref, ref1, ref2, ref3, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; FunctionRef = require('./reusable').FunctionRef; ref1 = require('../datatypes/datetime'), DateTime = ref1.DateTime, Date = ref1.Date; Concept = require('../datatypes/clinical').Concept; ref2 = require('../datatypes/quantity'), parseQuantity = ref2.parseQuantity, Quantity = ref2.Quantity; ref3 = require('../util/math'), isValidDecimal = ref3.isValidDecimal, isValidInteger = ref3.isValidInteger, limitDecimalPrecision = ref3.limitDecimalPrecision; normalizeMillisecondsField = require('../util/util').normalizeMillisecondsField; Ratio = require('../datatypes/ratio').Ratio; module.exports.As = As = (function(superClass) { extend(As, superClass); function As(json) { var ref4; As.__super__.constructor.apply(this, arguments); this.asType = json.asType; this.asTypeSpecifier = json.asTypeSpecifier; this.strict = (ref4 = json.strict) != null ? ref4 : false; } As.prototype.exec = function(ctx) { return this.execArgs(ctx); }; return As; })(Expression); module.exports.ToBoolean = ToBoolean = (function(superClass) { extend(ToBoolean, superClass); function ToBoolean(json) { ToBoolean.__super__.constructor.apply(this, arguments); } ToBoolean.prototype.exec = function(ctx) { var arg, strArg; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { strArg = arg.toString().toLowerCase(); if (strArg === "true" || strArg === "t" || strArg === "yes" || strArg === "y" || strArg === "1") { return true; } else if (strArg === "false" || strArg === "f" || strArg === "no" || strArg === "n" || strArg === "0") { return false; } else { return null; } } else { return null; } }; return ToBoolean; })(Expression); module.exports.ToConcept = ToConcept = (function(superClass) { extend(ToConcept, superClass); function ToConcept(json) { ToConcept.__super__.constructor.apply(this, arguments); } ToConcept.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { return new Concept([arg], arg.display); } else { return null; } }; return ToConcept; })(Expression); module.exports.ToDate = ToDate = (function(superClass) { extend(ToDate, superClass); function ToDate(json) { ToDate.__super__.constructor.apply(this, arguments); } ToDate.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isDateTime) { return arg.getDate(); } else { return Date.parse(arg.toString()); } }; return ToDate; })(Expression); module.exports.ToDateTime = ToDateTime = (function(superClass) { extend(ToDateTime, superClass); function ToDateTime(json) { ToDateTime.__super__.constructor.apply(this, arguments); } ToDateTime.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else if (arg.isDate) { return arg.getDateTime(); } else { return DateTime.parse(arg.toString()); } }; return ToDateTime; })(Expression); module.exports.ToDecimal = ToDecimal = (function(superClass) { extend(ToDecimal, superClass); function ToDecimal(json) { ToDecimal.__super__.constructor.apply(this, arguments); } ToDecimal.prototype.exec = function(ctx) { var arg, decimal; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { decimal = parseFloat(arg.toString()); decimal = limitDecimalPrecision(decimal); if (isValidDecimal(decimal)) { return decimal; } } return null; }; return ToDecimal; })(Expression); module.exports.ToInteger = ToInteger = (function(superClass) { extend(ToInteger, superClass); function ToInteger(json) { ToInteger.__super__.constructor.apply(this, arguments); } ToInteger.prototype.exec = function(ctx) { var arg, integer; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { integer = parseInt(arg.toString()); if (isValidInteger(integer)) { return integer; } } return null; }; return ToInteger; })(Expression); module.exports.ToQuantity = ToQuantity = (function(superClass) { extend(ToQuantity, superClass); function ToQuantity(json) { ToQuantity.__super__.constructor.apply(this, arguments); } ToQuantity.prototype.exec = function(ctx) { var arg, quantity; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { quantity = parseQuantity(arg.toString()); return quantity; } else { return null; } }; return ToQuantity; })(Expression); module.exports.ToRatio = ToRatio = (function(superClass) { extend(ToRatio, superClass); function ToRatio(json) { ToRatio.__super__.constructor.apply(this, arguments); } ToRatio.prototype.exec = function(ctx) { var arg, denominator, numerator, splitRatioString; arg = this.execArgs(ctx); if (arg != null) { try { splitRatioString = arg.toString().match(/^(\d+(\.\d+)?\s*('.+')?)\s*:\s*(\d+(\.\d+)?\s*('.+')?)$/); if (splitRatioString == null) { return null; } numerator = parseQuantity(splitRatioString[1]); denominator = parseQuantity(splitRatioString[4]); } catch (error) { return null; } if (!((numerator != null) && (denominator != null))) { return null; } return new Ratio(numerator, denominator); } else { return null; } }; return ToRatio; })(Expression); module.exports.ToString = ToString = (function(superClass) { extend(ToString, superClass); function ToString(json) { ToString.__super__.constructor.apply(this, arguments); } ToString.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { return arg.toString(); } else { return null; } }; return ToString; })(Expression); module.exports.ToTime = ToTime = (function(superClass) { extend(ToTime, superClass); function ToTime(json) { ToTime.__super__.constructor.apply(this, arguments); } ToTime.prototype.exec = function(ctx) { var arg, hours, matches, milliseconds, minutes, seconds, timeString; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { timeString = arg.toString(); matches = /^((\d{2})(\:(\d{2})(\:(\d{2})(\.(\d+))?)?)?)?$/.exec(timeString); if (matches == null) { return null; } hours = matches[2]; minutes = matches[4]; seconds = matches[6]; if (hours != null) { if (!(hours >= 0 && hours <= 23)) { return null; } hours = parseInt(hours, 10); } if (minutes != null) { if (!(minutes >= 0 && minutes <= 59)) { return null; } minutes = parseInt(minutes, 10); } if (seconds != null) { if (!(seconds >= 0 && seconds <= 59)) { return null; } seconds = parseInt(seconds, 10); } milliseconds = matches[8]; if (milliseconds != null) { milliseconds = parseInt(normalizeMillisecondsField(milliseconds)); } return new DateTime(0, 1, 1, hours, minutes, seconds, milliseconds, null); } else { return null; } }; return ToTime; })(Expression); module.exports.Convert = Convert = (function(superClass) { extend(Convert, superClass); function Convert(json) { Convert.__super__.constructor.apply(this, arguments); this.operand = json.operand; this.toType = json.toType; } Convert.prototype.exec = function(ctx) { switch (this.toType) { case "{urn:hl7-org:elm-types:r1}Boolean": return new ToBoolean({ "type": "ToBoolean", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}Concept": return new ToConcept({ "type": "ToConcept", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}Decimal": return new ToDecimal({ "type": "ToDecimal", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}Integer": return new ToInteger({ "type": "ToInteger", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}String": return new ToString({ "type": "ToString", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}Quantity": return new ToQuantity({ "type": "ToQuantity", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}DateTime": return new ToDateTime({ "type": "ToDateTime", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}Date": return new ToDate({ "type": "ToDate", "operand": this.operand }).execute(ctx); case "{urn:hl7-org:elm-types:r1}Time": return new ToTime({ "type": "ToTime", "operand": this.operand }).execute(ctx); default: return this.execArgs(ctx); } }; return Convert; })(Expression); module.exports.ConvertsToBoolean = ConvertsToBoolean = (function(superClass) { extend(ConvertsToBoolean, superClass); function ConvertsToBoolean(json) { ConvertsToBoolean.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToBoolean.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToBoolean, this.operand, ctx); } }; return ConvertsToBoolean; })(Expression); module.exports.ConvertsToDate = ConvertsToDate = (function(superClass) { extend(ConvertsToDate, superClass); function ConvertsToDate(json) { ConvertsToDate.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToDate.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToDate, this.operand, ctx); } }; return ConvertsToDate; })(Expression); module.exports.ConvertsToDateTime = ConvertsToDateTime = (function(superClass) { extend(ConvertsToDateTime, superClass); function ConvertsToDateTime(json) { ConvertsToDateTime.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToDateTime.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToDateTime, this.operand, ctx); } }; return ConvertsToDateTime; })(Expression); module.exports.ConvertsToDecimal = ConvertsToDecimal = (function(superClass) { extend(ConvertsToDecimal, superClass); function ConvertsToDecimal(json) { ConvertsToDecimal.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToDecimal.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToDecimal, this.operand, ctx); } }; return ConvertsToDecimal; })(Expression); module.exports.ConvertsToInteger = ConvertsToInteger = (function(superClass) { extend(ConvertsToInteger, superClass); function ConvertsToInteger(json) { ConvertsToInteger.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToInteger.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToInteger, this.operand, ctx); } }; return ConvertsToInteger; })(Expression); module.exports.ConvertsToQuantity = ConvertsToQuantity = (function(superClass) { extend(ConvertsToQuantity, superClass); function ConvertsToQuantity(json) { ConvertsToQuantity.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToQuantity.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToQuantity, this.operand, ctx); } }; return ConvertsToQuantity; })(Expression); module.exports.ConvertsToRatio = ConvertsToRatio = (function(superClass) { extend(ConvertsToRatio, superClass); function ConvertsToRatio(json) { ConvertsToRatio.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToRatio.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToRatio, this.operand, ctx); } }; return ConvertsToRatio; })(Expression); module.exports.ConvertsToString = ConvertsToString = (function(superClass) { extend(ConvertsToString, superClass); function ConvertsToString(json) { ConvertsToString.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToString.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToString, this.operand, ctx); } }; return ConvertsToString; })(Expression); module.exports.ConvertsToTime = ConvertsToTime = (function(superClass) { extend(ConvertsToTime, superClass); function ConvertsToTime(json) { ConvertsToTime.__super__.constructor.apply(this, arguments); this.operand = json.operand; } ConvertsToTime.prototype.exec = function(ctx) { var operatorValue; operatorValue = this.execArgs(ctx); if (operatorValue === null) { return null; } else { return canConvertToType(ToTime, this.operand, ctx); } }; return ConvertsToTime; })(Expression); canConvertToType = function(toFunction, operand, ctx) { var value; try { value = new toFunction({ "type": toFunction.name, "operand": operand }).execute(ctx); if (value != null) { return true; } else { return false; } } catch (error) { return false; } }; module.exports.ConvertQuantity = ConvertQuantity = (function(superClass) { extend(ConvertQuantity, superClass); function ConvertQuantity(json) { ConvertQuantity.__super__.constructor.apply(this, arguments); } ConvertQuantity.prototype.exec = function(ctx) { var newUnit, quantity, ref4; ref4 = this.execArgs(ctx), quantity = ref4[0], newUnit = ref4[1]; if ((quantity != null) && (newUnit != null)) { try { return quantity.convertUnit(newUnit); } catch (error) { return null; } } }; return ConvertQuantity; })(Expression); module.exports.CanConvertQuantity = CanConvertQuantity = (function(superClass) { extend(CanConvertQuantity, superClass); function CanConvertQuantity(json) { CanConvertQuantity.__super__.constructor.apply(this, arguments); } CanConvertQuantity.prototype.exec = function(ctx) { var newUnit, quantity, ref4; ref4 = this.execArgs(ctx), quantity = ref4[0], newUnit = ref4[1]; if ((quantity != null) && (newUnit != null)) { try { quantity.convertUnit(newUnit); return true; } catch (error) { return false; } } return null; }; return CanConvertQuantity; })(Expression); module.exports.Is = Is = (function(superClass) { extend(Is, superClass); function Is() { return Is.__super__.constructor.apply(this, arguments); } return Is; })(UnimplementedExpression); module.exports.IntervalTypeSpecifier = IntervalTypeSpecifier = (function(superClass) { extend(IntervalTypeSpecifier, superClass); function IntervalTypeSpecifier() { return IntervalTypeSpecifier.__super__.constructor.apply(this, arguments); } return IntervalTypeSpecifier; })(UnimplementedExpression); module.exports.ListTypeSpecifier = ListTypeSpecifier = (function(superClass) { extend(ListTypeSpecifier, superClass); function ListTypeSpecifier() { return ListTypeSpecifier.__super__.constructor.apply(this, arguments); } return ListTypeSpecifier; })(UnimplementedExpression); module.exports.NamedTypeSpecifier = NamedTypeSpecifier = (function(superClass) { extend(NamedTypeSpecifier, superClass); function NamedTypeSpecifier() { return NamedTypeSpecifier.__super__.constructor.apply(this, arguments); } return NamedTypeSpecifier; })(UnimplementedExpression); module.exports.TupleTypeSpecifier = TupleTypeSpecifier = (function(superClass) { extend(TupleTypeSpecifier, superClass); function TupleTypeSpecifier() { return TupleTypeSpecifier.__super__.constructor.apply(this, arguments); } return TupleTypeSpecifier; })(UnimplementedExpression); }).call(this); },{"../datatypes/clinical":120,"../datatypes/datetime":122,"../datatypes/quantity":126,"../datatypes/ratio":127,"../util/math":251,"../util/util":252,"./expression":137,"./reusable":152}],156:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Alert, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Prospective warnings of potential issues when providing care to the patient. @class Alert @exports Alert as Alert */ Alert = (function(superClass) { extend(Alert, superClass); function Alert(json) { this.json = json; Alert.__super__.constructor.call(this, this.json); } /** Identifier assigned to the alert for external use (outside the FHIR environment). @returns {Array} an array of {@link Identifier} objects */ Alert.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Allows an alert to be divided into different categories like clinical, administrative etc. @returns {CodeableConcept} */ Alert.prototype.category = function() { if (this.json['category']) { return new CodeableConcept(this.json['category']); } }; /** Supports basic workflow. @returns {Array} an array of {@link String} objects */ Alert.prototype.status = function() { return this.json['status']; }; /** The person who this alert concerns. @returns {Reference} */ Alert.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The person or device that created the alert. @returns {Reference} */ Alert.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** The textual component of the alert to display to the user. @returns {Array} an array of {@link String} objects */ Alert.prototype.note = function() { return this.json['note']; }; return Alert; })(DomainResource); module.exports.Alert = Alert; }).call(this); },{"../cql-datatypes":117,"./core":173}],157:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, AllergyIntolerance, AllergyIntoleranceEventComponent, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class AllergyIntoleranceEventComponent @exports AllergyIntoleranceEventComponent as AllergyIntoleranceEventComponent */ AllergyIntoleranceEventComponent = (function(superClass) { extend(AllergyIntoleranceEventComponent, superClass); function AllergyIntoleranceEventComponent(json) { this.json = json; AllergyIntoleranceEventComponent.__super__.constructor.call(this, this.json); } /** Identification of the specific substance considered to be responsible for the Adverse Reaction event. Note: the substance for a specific reaction may be different to the substance identified as the cause of the risk, but must be consistent with it. For instance, it may be a more specific substance (e.g. a brand medication) or a composite substance that includes the identified substance. It must be clinically safe to only process the AllergyIntolerance.substance and ignore the AllergyIntolerance.event.substance. @returns {CodeableConcept} */ AllergyIntoleranceEventComponent.prototype.substance = function() { if (this.json['substance']) { return new CodeableConcept(this.json['substance']); } }; /** Statement about the degree of clinical certainty that the Specific Substance was the cause of the Manifestation in this reaction event. @returns {Array} an array of {@link String} objects */ AllergyIntoleranceEventComponent.prototype.certainty = function() { return this.json['certainty']; }; /** Clinical symptoms and/or signs that are observed or associated with the Adverse Reaction Event. @returns {Array} an array of {@link CodeableConcept} objects */ AllergyIntoleranceEventComponent.prototype.manifestation = function() { var i, item, len, ref, results; if (this.json['manifestation']) { ref = this.json['manifestation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Text description about the Reaction as a whole, including details of the manifestation if required. @returns {Array} an array of {@link String} objects */ AllergyIntoleranceEventComponent.prototype.description = function() { return this.json['description']; }; /** Record of the date and/or time of the onset of the Reaction. @returns {Array} an array of {@link Date} objects */ AllergyIntoleranceEventComponent.prototype.onset = function() { if (this.json['onset']) { return DT.DateTime.parse(this.json['onset']); } }; /** The amount of time that the Adverse Reaction persisted. @returns {Duration} */ AllergyIntoleranceEventComponent.prototype.duration = function() { if (this.json['duration']) { return new Duration(this.json['duration']); } }; /** Clinical assessment of the severity of the reaction event as a whole, potentially considering multiple different manifestations. @returns {Array} an array of {@link String} objects */ AllergyIntoleranceEventComponent.prototype.severity = function() { return this.json['severity']; }; /** Identification of the route by which the subject was exposed to the substance. @returns {CodeableConcept} */ AllergyIntoleranceEventComponent.prototype.exposureRoute = function() { if (this.json['exposureRoute']) { return new CodeableConcept(this.json['exposureRoute']); } }; /** Additional text about the Adverse Reaction event not captured in other fields. @returns {Array} an array of {@link String} objects */ AllergyIntoleranceEventComponent.prototype.comment = function() { return this.json['comment']; }; return AllergyIntoleranceEventComponent; })(BackboneElement); /** Risk of harmful or undesirable, physiological response which is unique to an individual and associated with exposure to a substance. @class AllergyIntolerance @exports AllergyIntolerance as AllergyIntolerance */ AllergyIntolerance = (function(superClass) { extend(AllergyIntolerance, superClass); function AllergyIntolerance(json) { this.json = json; AllergyIntolerance.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this allergy/intolerance concern that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ AllergyIntolerance.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Date when the sensitivity was recorded. @returns {Array} an array of {@link Date} objects */ AllergyIntolerance.prototype.recordedDate = function() { if (this.json['recordedDate']) { return DT.DateTime.parse(this.json['recordedDate']); } }; /** Indicates who has responsibility for the record. @returns {Reference} */ AllergyIntolerance.prototype.recorder = function() { if (this.json['recorder']) { return new Reference(this.json['recorder']); } }; /** The patient who has the allergy or intolerance. @returns {Reference} */ AllergyIntolerance.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Identification of a substance, or a class of substances, that is considered to be responsible for the Adverse reaction risk. @returns {CodeableConcept} */ AllergyIntolerance.prototype.substance = function() { if (this.json['substance']) { return new CodeableConcept(this.json['substance']); } }; /** Assertion about certainty associated with the propensity, or potential risk, of a reaction to the identified Substance. @returns {Array} an array of {@link String} objects */ AllergyIntolerance.prototype.status = function() { return this.json['status']; }; /** Estimate of the potential clinical harm, or seriousness, of the reaction to the identified Substance. @returns {Array} an array of {@link String} objects */ AllergyIntolerance.prototype.criticality = function() { return this.json['criticality']; }; /** Identification of the underlying physiological mechanism for the Reaction Risk. @returns {Array} an array of {@link String} objects */ AllergyIntolerance.prototype.type = function() { return this.json['type']; }; /** Category of the identified Substance. @returns {Array} an array of {@link String} objects */ AllergyIntolerance.prototype.category = function() { return this.json['category']; }; /** Represents the date and/or time of the last known occurence of a reaction event. @returns {Array} an array of {@link Date} objects */ AllergyIntolerance.prototype.lastOccurence = function() { if (this.json['lastOccurence']) { return DT.DateTime.parse(this.json['lastOccurence']); } }; /** Additional narrative about the propensity for the Adverse Reaction, not captured in other fields. @returns {Array} an array of {@link String} objects */ AllergyIntolerance.prototype.comment = function() { return this.json['comment']; }; /** Details about each Adverse Reaction Event linked to exposure to the identified Substance. @returns {Array} an array of {@link AllergyIntoleranceEventComponent} objects */ AllergyIntolerance.prototype.event = function() { var i, item, len, ref, results; if (this.json['event']) { ref = this.json['event']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new AllergyIntoleranceEventComponent(item)); } return results; } }; return AllergyIntolerance; })(DomainResource); module.exports.AllergyIntolerance = AllergyIntolerance; }).call(this); },{"../cql-datatypes":117,"./core":173}],158:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Appointment, AppointmentParticipantComponent, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class AppointmentParticipantComponent @exports AppointmentParticipantComponent as AppointmentParticipantComponent */ AppointmentParticipantComponent = (function(superClass) { extend(AppointmentParticipantComponent, superClass); function AppointmentParticipantComponent(json) { this.json = json; AppointmentParticipantComponent.__super__.constructor.call(this, this.json); } /** Role of participant in the appointment. @returns {Array} an array of {@link CodeableConcept} objects */ AppointmentParticipantComponent.prototype.type = function() { var i, item, len, ref, results; if (this.json['type']) { ref = this.json['type']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** A Person of device that is participating in the appointment, usually Practitioner, Patient, RelatedPerson or Device. @returns {Reference} */ AppointmentParticipantComponent.prototype.actor = function() { if (this.json['actor']) { return new Reference(this.json['actor']); } }; /** Is this participant required to be present at the meeting. This covers a use-case where 2 doctors need to meet to discuss the results for a specific patient, and the patient is not required to be present. @returns {Array} an array of {@link String} objects */ AppointmentParticipantComponent.prototype.required = function() { return this.json['required']; }; /** Participation status of the Patient. @returns {Array} an array of {@link String} objects */ AppointmentParticipantComponent.prototype.status = function() { return this.json['status']; }; return AppointmentParticipantComponent; })(BackboneElement); /** A scheduled healthcare event for a patient and/or practitioner(s) where a service may take place at a specific date/time. @class Appointment @exports Appointment as Appointment */ Appointment = (function(superClass) { extend(Appointment, superClass); function Appointment(json) { this.json = json; Appointment.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this appointment concern that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ Appointment.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The priority of the appointment. Can be used to make informed decisions if needing to re-prioritize appointments. (The iCal Standard specifies 0 as undefined, 1 as highest, 9 as lowest priority) (Need to change back to CodeableConcept). @returns {Array} an array of {@link Number} objects */ Appointment.prototype.priority = function() { return this.json['priority']; }; /** Each of the participants has their own participation status which indicates their involvement in the process, however this status indicates the shared status. @returns {Array} an array of {@link String} objects */ Appointment.prototype.status = function() { return this.json['status']; }; /** The type of appointments that is being booked (ideally this would be an identifiable service - which is at a location, rather than the location itself). @returns {CodeableConcept} */ Appointment.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The reason that this appointment is being scheduled, this is more clinical than administrative. @returns {CodeableConcept} */ Appointment.prototype.reason = function() { if (this.json['reason']) { return new CodeableConcept(this.json['reason']); } }; /** The brief description of the appointment as would be shown on a subject line in a meeting request, or appointment list. Detailed or expanded information should be put in the comment field. @returns {Array} an array of {@link String} objects */ Appointment.prototype.description = function() { return this.json['description']; }; /** Date/Time that the appointment is to take place. @returns {Array} an array of {@link Date} objects */ Appointment.prototype.start = function() { if (this.json['start']) { return DT.DateTime.parse(this.json['start']); } }; /** Date/Time that the appointment is to conclude. @returns {Array} an array of {@link Date} objects */ Appointment.prototype.end = function() { if (this.json['end']) { return DT.DateTime.parse(this.json['end']); } }; /** The slot that this appointment is filling. If provided then the schedule will not be provided as slots are not recursive, and the start/end values MUST be the same as from the slot. @returns {Array} an array of {@link Reference} objects */ Appointment.prototype.slot = function() { var i, item, len, ref, results; if (this.json['slot']) { ref = this.json['slot']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The primary location that this appointment is to take place. @returns {Reference} */ Appointment.prototype.location = function() { if (this.json['location']) { return new Reference(this.json['location']); } }; /** Additional comments about the appointment. @returns {Array} an array of {@link String} objects */ Appointment.prototype.comment = function() { return this.json['comment']; }; /** An Order that lead to the creation of this appointment. @returns {Reference} */ Appointment.prototype.order = function() { if (this.json['order']) { return new Reference(this.json['order']); } }; /** List of participants involved in the appointment. @returns {Array} an array of {@link AppointmentParticipantComponent} objects */ Appointment.prototype.participant = function() { var i, item, len, ref, results; if (this.json['participant']) { ref = this.json['participant']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new AppointmentParticipantComponent(item)); } return results; } }; /** Who recorded the appointment. @returns {Reference} */ Appointment.prototype.lastModifiedBy = function() { if (this.json['lastModifiedBy']) { return new Reference(this.json['lastModifiedBy']); } }; /** Date when the appointment was recorded. @returns {Array} an array of {@link Date} objects */ Appointment.prototype.lastModified = function() { if (this.json['lastModified']) { return DT.DateTime.parse(this.json['lastModified']); } }; return Appointment; })(DomainResource); module.exports.Appointment = Appointment; }).call(this); },{"../cql-datatypes":117,"./core":173}],159:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, AppointmentResponse, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A reply to an appointment request for a patient and/or practitioner(s), such as a confirmation or rejection. @class AppointmentResponse @exports AppointmentResponse as AppointmentResponse */ AppointmentResponse = (function(superClass) { extend(AppointmentResponse, superClass); function AppointmentResponse(json) { this.json = json; AppointmentResponse.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this appointment concern that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ AppointmentResponse.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Parent appointment that this response is replying to. @returns {Reference} */ AppointmentResponse.prototype.appointment = function() { if (this.json['appointment']) { return new Reference(this.json['appointment']); } }; /** Role of participant in the appointment. @returns {Array} an array of {@link CodeableConcept} objects */ AppointmentResponse.prototype.participantType = function() { var i, item, len, ref, results; if (this.json['participantType']) { ref = this.json['participantType']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** A Person of device that is participating in the appointment, usually Practitioner, Patient, RelatedPerson or Device. @returns {Array} an array of {@link Reference} objects */ AppointmentResponse.prototype.individual = function() { var i, item, len, ref, results; if (this.json['individual']) { ref = this.json['individual']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Participation status of the Patient. @returns {Array} an array of {@link String} objects */ AppointmentResponse.prototype.participantStatus = function() { return this.json['participantStatus']; }; /** Additional comments about the appointment. @returns {Array} an array of {@link String} objects */ AppointmentResponse.prototype.comment = function() { return this.json['comment']; }; /** Date/Time that the appointment is to take place. @returns {Array} an array of {@link Date} objects */ AppointmentResponse.prototype.start = function() { if (this.json['start']) { return DT.DateTime.parse(this.json['start']); } }; /** Date/Time that the appointment is to conclude. @returns {Array} an array of {@link Date} objects */ AppointmentResponse.prototype.end = function() { if (this.json['end']) { return DT.DateTime.parse(this.json['end']); } }; /** Who recorded the appointment response. @returns {Reference} */ AppointmentResponse.prototype.lastModifiedBy = function() { if (this.json['lastModifiedBy']) { return new Reference(this.json['lastModifiedBy']); } }; /** Date when the response was recorded or last updated. @returns {Array} an array of {@link Date} objects */ AppointmentResponse.prototype.lastModified = function() { if (this.json['lastModified']) { return DT.DateTime.parse(this.json['lastModified']); } }; return AppointmentResponse; })(DomainResource); module.exports.AppointmentResponse = AppointmentResponse; }).call(this); },{"../cql-datatypes":117,"./core":173}],160:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, Availability, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** (informative) A container for slot(s) of time that may be available for booking appointments. @class Availability @exports Availability as Availability */ Availability = (function(superClass) { extend(Availability, superClass); function Availability(json) { this.json = json; Availability.__super__.constructor.call(this, this.json); } /** External Ids for this item. @returns {Array} an array of {@link Identifier} objects */ Availability.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The schedule type can be used for the categorization of healthcare services or other appointment types. @returns {Array} an array of {@link CodeableConcept} objects */ Availability.prototype.type = function() { var i, item, len, ref, results; if (this.json['type']) { ref = this.json['type']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The resource this availability resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson. @returns {Reference} */ Availability.prototype.actor = function() { if (this.json['actor']) { return new Reference(this.json['actor']); } }; /** The period of time that the slots that are attached to this availability resource cover (even if none exist). These cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a "template" for planning outside these dates. @returns {Period} */ Availability.prototype.planningHorizon = function() { if (this.json['planningHorizon']) { return new Period(this.json['planningHorizon']); } }; /** Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated. @returns {Array} an array of {@link String} objects */ Availability.prototype.comment = function() { return this.json['comment']; }; /** When this availability was created, or last revised. @returns {Array} an array of {@link Date} objects */ Availability.prototype.lastModified = function() { if (this.json['lastModified']) { return DT.DateTime.parse(this.json['lastModified']); } }; return Availability; })(DomainResource); module.exports.Availability = Availability; }).call(this); },{"../cql-datatypes":117,"./core":173}],161:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, Basic, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Basic is used for handling concepts not yet defined in FHIR, narrative-only resources that don't map to an existing resource, and custom resources not appropriate for inclusion in the FHIR specification. @class Basic @exports Basic as Basic */ Basic = (function(superClass) { extend(Basic, superClass); function Basic(json) { this.json = json; Basic.__super__.constructor.call(this, this.json); } /** Identifier assigned to the resource for business purposes, outside the context of FHIR. @returns {Array} an array of {@link Identifier} objects */ Basic.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Identifies the 'type' of resource - equivalent to the resource name for other resources. @returns {CodeableConcept} */ Basic.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** Identifies the patient, practitioner, device or any other resource that is the "focus" of this resoruce. @returns {Reference} */ Basic.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Indicates who was responsible for creating the resource instance. @returns {Reference} */ Basic.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** Identifies when the resource was first created. @returns {Array} an array of {@link Date} objects */ Basic.prototype.created = function() { if (this.json['created']) { return DT.DateTime.parse(this.json['created']); } }; return Basic; })(DomainResource); module.exports.Basic = Basic; }).call(this); },{"../cql-datatypes":117,"./core":173}],162:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, Binary, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A binary resource can contain any content, whether text, image, pdf, zip archive, etc. @class Binary @exports Binary as Binary */ Binary = (function(superClass) { extend(Binary, superClass); function Binary(json) { this.json = json; Binary.__super__.constructor.call(this, this.json); } /** MimeType of the binary content represented as a standard MimeType (BCP 13). @returns {Array} an array of {@link String} objects */ Binary.prototype.contentType = function() { return this.json['contentType']; }; /** The actual content, base64 encoded. @returns {Array} an array of {@link } objects */ Binary.prototype.content = function() { return this.json['content']; }; return Binary; })(Resource); module.exports.Binary = Binary; }).call(this); },{"../cql-datatypes":117,"./core":173}],163:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, Bundle, BundleEntryComponent, BundleEntryDeletedComponent, BundleLinkComponent, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class BundleLinkComponent @exports BundleLinkComponent as BundleLinkComponent */ BundleLinkComponent = (function(superClass) { extend(BundleLinkComponent, superClass); function BundleLinkComponent(json) { this.json = json; BundleLinkComponent.__super__.constructor.call(this, this.json); } /** A name which details the functional use for this link - see [[http://www.iana.org/assignments/link-relations/link-relations.xhtml]]. @returns {Array} an array of {@link String} objects */ BundleLinkComponent.prototype.relation = function() { return this.json['relation']; }; /** The reference details for the link. @returns {Array} an array of {@link String} objects */ BundleLinkComponent.prototype.url = function() { return this.json['url']; }; return BundleLinkComponent; })(BackboneElement); /** Embedded class @class BundleEntryDeletedComponent @exports BundleEntryDeletedComponent as BundleEntryDeletedComponent */ BundleEntryDeletedComponent = (function(superClass) { extend(BundleEntryDeletedComponent, superClass); function BundleEntryDeletedComponent(json) { this.json = json; BundleEntryDeletedComponent.__super__.constructor.call(this, this.json); } /** The type of resource that was deleted (required to construct the identity). @returns {Array} an array of {@link String} objects */ BundleEntryDeletedComponent.prototype.type = function() { return this.json['type']; }; /** The id of the resource that was deleted. @returns {Array} an array of {@link String} objects */ BundleEntryDeletedComponent.prototype.id = function() { return this.json['id']; }; /** Version id for releted resource. @returns {Array} an array of {@link String} objects */ BundleEntryDeletedComponent.prototype.versionId = function() { return this.json['versionId']; }; /** The date/time that the resource was deleted. @returns {Array} an array of {@link Date} objects */ BundleEntryDeletedComponent.prototype.instant = function() { if (this.json['instant']) { return DT.DateTime.parse(this.json['instant']); } }; return BundleEntryDeletedComponent; })(BackboneElement); /** Embedded class @class BundleEntryComponent @exports BundleEntryComponent as BundleEntryComponent */ BundleEntryComponent = (function(superClass) { extend(BundleEntryComponent, superClass); function BundleEntryComponent(json) { this.json = json; BundleEntryComponent.__super__.constructor.call(this, this.json); } /** The Base URL for the resource, if different to the base URL specified for the bundle as a whole. @returns {Array} an array of {@link String} objects */ BundleEntryComponent.prototype.base = function() { return this.json['base']; }; /** The status of a resource in the bundle. Used for search (to differentiate between resources included as a match, and resources included as an _include), for history (deleted resources), and for transactions (create/update/delete). @returns {Array} an array of {@link String} objects */ BundleEntryComponent.prototype.status = function() { return this.json['status']; }; /** Search URL for this resource when processing a transaction (see transaction documentation). @returns {Array} an array of {@link String} objects */ BundleEntryComponent.prototype.search = function() { return this.json['search']; }; /** When searching, the server's search ranking score for the entry. @returns {Array} an array of {@link Number} objects */ BundleEntryComponent.prototype.score = function() { return this.json['score']; }; /** If this is an entry that represents a deleted resource. Only used when the bundle is a transaction or a history type. See RESTful API documentation for further informatino. @returns {BundleEntryDeletedComponent} */ BundleEntryComponent.prototype.deleted = function() { if (this.json['deleted']) { return new BundleEntryDeletedComponent(this.json['deleted']); } }; /** The Resources for the entry. @returns {Resource} */ BundleEntryComponent.prototype.resource = function() { var req, typeName; if (this.json['resource']) { typeName = this.json['resource'].resourceType; req = require('./' + typeName.toLowerCase())[typeName]; return new req(this.json['resource']); } }; return BundleEntryComponent; })(BackboneElement); /** A container for a group of resources. @class Bundle @exports Bundle as Bundle */ Bundle = (function(superClass) { extend(Bundle, superClass); function Bundle(json) { this.json = json; Bundle.__super__.constructor.call(this, this.json); } /** Indicates the purpose of this bundle- how it was intended to be used. @returns {Array} an array of {@link String} objects */ Bundle.prototype.type = function() { return this.json['type']; }; /** The base URL for the service that provided these resources. All relative URLs are relative to this one (equivalent to xml:base). @returns {Array} an array of {@link String} objects */ Bundle.prototype.base = function() { return this.json['base']; }; /** If a set of search matches, this is the total number of matches for the search (as opposed to the number of results in this bundle). @returns {Array} an array of {@link Number} objects */ Bundle.prototype.total = function() { return this.json['total']; }; /** A series of links that provide context to this bundle. @returns {Array} an array of {@link BundleLinkComponent} objects */ Bundle.prototype.link = function() { var i, item, len, ref, results; if (this.json['link']) { ref = this.json['link']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new BundleLinkComponent(item)); } return results; } }; /** An entry in a bundle resource - will either contain a resource, or a deleted entry (transaction and history bundles only). @returns {Array} an array of {@link BundleEntryComponent} objects */ Bundle.prototype.entry = function() { var i, item, len, ref, results; if (this.json['entry']) { ref = this.json['entry']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new BundleEntryComponent(item)); } return results; } }; /** XML Digital Signature - base64 encoded. @returns {Array} an array of {@link } objects */ Bundle.prototype.signature = function() { return this.json['signature']; }; return Bundle; })(Resource); module.exports.Bundle = Bundle; }).call(this); },{"../cql-datatypes":117,"./core":173}],164:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CarePlan, CarePlanActivityComponent, CarePlanActivitySimpleComponent, CarePlanGoalComponent, CarePlanParticipantComponent, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class CarePlanParticipantComponent @exports CarePlanParticipantComponent as CarePlanParticipantComponent */ CarePlanParticipantComponent = (function(superClass) { extend(CarePlanParticipantComponent, superClass); function CarePlanParticipantComponent(json) { this.json = json; CarePlanParticipantComponent.__super__.constructor.call(this, this.json); } /** Indicates specific responsibility of an individual within the care plan. E.g. "Primary physician", "Team coordinator", "Caregiver", etc. @returns {CodeableConcept} */ CarePlanParticipantComponent.prototype.role = function() { if (this.json['role']) { return new CodeableConcept(this.json['role']); } }; /** The specific person or organization who is participating/expected to participate in the care plan. @returns {Reference} */ CarePlanParticipantComponent.prototype.member = function() { if (this.json['member']) { return new Reference(this.json['member']); } }; return CarePlanParticipantComponent; })(BackboneElement); /** Embedded class @class CarePlanGoalComponent @exports CarePlanGoalComponent as CarePlanGoalComponent */ CarePlanGoalComponent = (function(superClass) { extend(CarePlanGoalComponent, superClass); function CarePlanGoalComponent(json) { this.json = json; CarePlanGoalComponent.__super__.constructor.call(this, this.json); } /** Human-readable description of a specific desired objective of the care plan. @returns {Array} an array of {@link String} objects */ CarePlanGoalComponent.prototype.description = function() { return this.json['description']; }; /** Indicates whether the goal has been reached and is still considered relevant. @returns {Array} an array of {@link String} objects */ CarePlanGoalComponent.prototype.status = function() { return this.json['status']; }; /** Any comments related to the goal. @returns {Array} an array of {@link String} objects */ CarePlanGoalComponent.prototype.notes = function() { return this.json['notes']; }; /** The identified conditions that this goal relates to - the condition that caused it to be created, or that it is intended to address. @returns {Array} an array of {@link Reference} objects */ CarePlanGoalComponent.prototype.concern = function() { var i, item, len, ref, results; if (this.json['concern']) { ref = this.json['concern']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return CarePlanGoalComponent; })(BackboneElement); /** Embedded class @class CarePlanActivitySimpleComponent @exports CarePlanActivitySimpleComponent as CarePlanActivitySimpleComponent */ CarePlanActivitySimpleComponent = (function(superClass) { extend(CarePlanActivitySimpleComponent, superClass); function CarePlanActivitySimpleComponent(json) { this.json = json; CarePlanActivitySimpleComponent.__super__.constructor.call(this, this.json); } /** High-level categorization of the type of activity in a care plan. @returns {Array} an array of {@link String} objects */ CarePlanActivitySimpleComponent.prototype.category = function() { return this.json['category']; }; /** Detailed description of the type of activity. E.g. What lab test, what procedure, what kind of encounter. @returns {CodeableConcept} */ CarePlanActivitySimpleComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** The period, timing or frequency upon which the described activity is to occur. @returns {Timing} */ CarePlanActivitySimpleComponent.prototype.scheduledTiming = function() { if (this.json['scheduledTiming']) { return new Timing(this.json['scheduledTiming']); } }; /** The period, timing or frequency upon which the described activity is to occur. @returns {Period} */ CarePlanActivitySimpleComponent.prototype.scheduledPeriod = function() { if (this.json['scheduledPeriod']) { return new Period(this.json['scheduledPeriod']); } }; /** The period, timing or frequency upon which the described activity is to occur. @returns {Array} an array of {@link String} objects */ CarePlanActivitySimpleComponent.prototype.scheduledString = function() { return this.json['scheduledString']; }; /** Identifies the facility where the activity will occur. E.g. home, hospital, specific clinic, etc. @returns {Reference} */ CarePlanActivitySimpleComponent.prototype.location = function() { if (this.json['location']) { return new Reference(this.json['location']); } }; /** Identifies who's expected to be involved in the activity. @returns {Array} an array of {@link Reference} objects */ CarePlanActivitySimpleComponent.prototype.performer = function() { var i, item, len, ref, results; if (this.json['performer']) { ref = this.json['performer']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Identifies the food, drug or other product being consumed or supplied in the activity. @returns {Reference} */ CarePlanActivitySimpleComponent.prototype.product = function() { if (this.json['product']) { return new Reference(this.json['product']); } }; /** Identifies the quantity expected to be consumed in a given day. @returns {Quantity} */ CarePlanActivitySimpleComponent.prototype.dailyAmount = function() { if (this.json['dailyAmount']) { return new Quantity(this.json['dailyAmount']); } }; /** Identifies the quantity expected to be supplied. @returns {Quantity} */ CarePlanActivitySimpleComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** This provides a textual description of constraints on the activity occurrence, including relation to other activities. It may also include objectives, pre-conditions and end-conditions. Finally, it may convey specifics about the activity such as body site, method, route, etc. @returns {Array} an array of {@link String} objects */ CarePlanActivitySimpleComponent.prototype.details = function() { return this.json['details']; }; return CarePlanActivitySimpleComponent; })(BackboneElement); /** Embedded class @class CarePlanActivityComponent @exports CarePlanActivityComponent as CarePlanActivityComponent */ CarePlanActivityComponent = (function(superClass) { extend(CarePlanActivityComponent, superClass); function CarePlanActivityComponent(json) { this.json = json; CarePlanActivityComponent.__super__.constructor.call(this, this.json); } /** Internal reference that identifies the goals that this activity is intended to contribute towards meeting. @returns {Array} an array of {@link String} objects */ CarePlanActivityComponent.prototype.goal = function() { return this.json['goal']; }; /** Identifies what progress is being made for the specific activity. @returns {Array} an array of {@link String} objects */ CarePlanActivityComponent.prototype.status = function() { return this.json['status']; }; /** If true, indicates that the described activity is one that must NOT be engaged in when following the plan. @returns {Array} an array of {@link boolean} objects */ CarePlanActivityComponent.prototype.prohibited = function() { return this.json['prohibited']; }; /** Resources that describe follow-on actions resulting from the plan, such as drug prescriptions, encounter records, appointments, etc. @returns {Array} an array of {@link Reference} objects */ CarePlanActivityComponent.prototype.actionResulting = function() { var i, item, len, ref, results; if (this.json['actionResulting']) { ref = this.json['actionResulting']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Notes about the execution of the activity. @returns {Array} an array of {@link String} objects */ CarePlanActivityComponent.prototype.notes = function() { return this.json['notes']; }; /** The details of the proposed activity represented in a specific resource. @returns {Reference} */ CarePlanActivityComponent.prototype.detail = function() { if (this.json['detail']) { return new Reference(this.json['detail']); } }; /** A simple summary of details suitable for a general care plan system (e.g. form driven) that doesn't know about specific resources such as procedure etc. @returns {CarePlanActivitySimpleComponent} */ CarePlanActivityComponent.prototype.simple = function() { if (this.json['simple']) { return new CarePlanActivitySimpleComponent(this.json['simple']); } }; return CarePlanActivityComponent; })(BackboneElement); /** Describes the intention of how one or more practitioners intend to deliver care for a particular patient for a period of time, possibly limited to care for a specific condition or set of conditions. @class CarePlan @exports CarePlan as CarePlan */ CarePlan = (function(superClass) { extend(CarePlan, superClass); function CarePlan(json) { this.json = json; CarePlan.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this care plan that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ CarePlan.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Identifies the patient/subject whose intended care is described by the plan. @returns {Reference} */ CarePlan.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** Indicates whether the plan is currently being acted upon, represents future intentions or is now just historical record. @returns {Array} an array of {@link String} objects */ CarePlan.prototype.status = function() { return this.json['status']; }; /** Indicates when the plan did (or is intended to) come into effect and end. @returns {Period} */ CarePlan.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** Identifies the most recent date on which the plan has been revised. @returns {Array} an array of {@link Date} objects */ CarePlan.prototype.modified = function() { if (this.json['modified']) { return DT.DateTime.parse(this.json['modified']); } }; /** Identifies the conditions/problems/concerns/diagnoses/etc. whose management and/or mitigation are handled by this plan. @returns {Array} an array of {@link Reference} objects */ CarePlan.prototype.concern = function() { var i, item, len, ref, results; if (this.json['concern']) { ref = this.json['concern']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Identifies all people and organizations who are expected to be involved in the care envisioned by this plan. @returns {Array} an array of {@link CarePlanParticipantComponent} objects */ CarePlan.prototype.participant = function() { var i, item, len, ref, results; if (this.json['participant']) { ref = this.json['participant']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CarePlanParticipantComponent(item)); } return results; } }; /** Describes the intended objective(s) of carrying out the Care Plan. @returns {Array} an array of {@link CarePlanGoalComponent} objects */ CarePlan.prototype.goal = function() { var i, item, len, ref, results; if (this.json['goal']) { ref = this.json['goal']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CarePlanGoalComponent(item)); } return results; } }; /** Identifies a planned action to occur as part of the plan. For example, a medication to be used, lab tests to perform, self-monitoring, education, etc. @returns {Array} an array of {@link CarePlanActivityComponent} objects */ CarePlan.prototype.activity = function() { var i, item, len, ref, results; if (this.json['activity']) { ref = this.json['activity']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CarePlanActivityComponent(item)); } return results; } }; /** General notes about the care plan not covered elsewhere. @returns {Array} an array of {@link String} objects */ CarePlan.prototype.notes = function() { return this.json['notes']; }; return CarePlan; })(DomainResource); module.exports.CarePlan = CarePlan; }).call(this); },{"../cql-datatypes":117,"./core":173}],165:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var AddedItemAdjudicationComponent, AddedItemComponent, AddedItemDetailAdjudicationComponent, AddedItemsDetailComponent, Address, Attachment, BackboneElement, CORE, ClaimResponse, CodeableConcept, Coding, ContactPoint, DT, DetailAdjudicationComponent, DomainResource, Element, ElementDefinition, ErrorsComponent, Extension, HumanName, Identifier, ItemAdjudicationComponent, ItemDetailComponent, ItemSubdetailComponent, ItemsComponent, Narrative, NotesComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, SubdetailAdjudicationComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ItemAdjudicationComponent @exports ItemAdjudicationComponent as ItemAdjudicationComponent */ ItemAdjudicationComponent = (function(superClass) { extend(ItemAdjudicationComponent, superClass); function ItemAdjudicationComponent(json) { this.json = json; ItemAdjudicationComponent.__super__.constructor.call(this, this.json); } /** Code indicating: Co-Pay, deductable, elegible, benefit, tax, etc. @returns {Coding} */ ItemAdjudicationComponent.prototype.code = function() { if (this.json['code']) { return new Coding(this.json['code']); } }; /** Monitory amount associated with the code. @returns {Money} */ ItemAdjudicationComponent.prototype.amount = function() { if (this.json['amount']) { return new Money(this.json['amount']); } }; /** A non-monitary value for example a percentage. Mutually exclusive to the amount element above. @returns {Array} an array of {@link Number} objects */ ItemAdjudicationComponent.prototype.value = function() { return this.json['value']; }; return ItemAdjudicationComponent; })(BackboneElement); /** Embedded class @class DetailAdjudicationComponent @exports DetailAdjudicationComponent as DetailAdjudicationComponent */ DetailAdjudicationComponent = (function(superClass) { extend(DetailAdjudicationComponent, superClass); function DetailAdjudicationComponent(json) { this.json = json; DetailAdjudicationComponent.__super__.constructor.call(this, this.json); } /** Code indicating: Co-Pay, deductable, elegible, benefit, tax, etc. @returns {Coding} */ DetailAdjudicationComponent.prototype.code = function() { if (this.json['code']) { return new Coding(this.json['code']); } }; /** Monitory amount associated with the code. @returns {Money} */ DetailAdjudicationComponent.prototype.amount = function() { if (this.json['amount']) { return new Money(this.json['amount']); } }; /** A non-monitary value for example a percentage. Mutually exclusive to the amount element above. @returns {Array} an array of {@link Number} objects */ DetailAdjudicationComponent.prototype.value = function() { return this.json['value']; }; return DetailAdjudicationComponent; })(BackboneElement); /** Embedded class @class SubdetailAdjudicationComponent @exports SubdetailAdjudicationComponent as SubdetailAdjudicationComponent */ SubdetailAdjudicationComponent = (function(superClass) { extend(SubdetailAdjudicationComponent, superClass); function SubdetailAdjudicationComponent(json) { this.json = json; SubdetailAdjudicationComponent.__super__.constructor.call(this, this.json); } /** Code indicating: Co-Pay, deductable, elegible, benefit, tax, etc. @returns {Coding} */ SubdetailAdjudicationComponent.prototype.code = function() { if (this.json['code']) { return new Coding(this.json['code']); } }; /** Monitory amount associated with the code. @returns {Money} */ SubdetailAdjudicationComponent.prototype.amount = function() { if (this.json['amount']) { return new Money(this.json['amount']); } }; /** A non-monitary value for example a percentage. Mutually exclusive to the amount element above. @returns {Array} an array of {@link Number} objects */ SubdetailAdjudicationComponent.prototype.value = function() { return this.json['value']; }; return SubdetailAdjudicationComponent; })(BackboneElement); /** Embedded class @class ItemSubdetailComponent @exports ItemSubdetailComponent as ItemSubdetailComponent */ ItemSubdetailComponent = (function(superClass) { extend(ItemSubdetailComponent, superClass); function ItemSubdetailComponent(json) { this.json = json; ItemSubdetailComponent.__super__.constructor.call(this, this.json); } /** A service line number. @returns {Array} an array of {@link Number} objects */ ItemSubdetailComponent.prototype.sequenceLinkId = function() { return this.json['sequenceLinkId']; }; /** The adjudications results. @returns {Array} an array of {@link SubdetailAdjudicationComponent} objects */ ItemSubdetailComponent.prototype.adjudication = function() { var i, item, len, ref, results; if (this.json['adjudication']) { ref = this.json['adjudication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SubdetailAdjudicationComponent(item)); } return results; } }; return ItemSubdetailComponent; })(BackboneElement); /** Embedded class @class ItemDetailComponent @exports ItemDetailComponent as ItemDetailComponent */ ItemDetailComponent = (function(superClass) { extend(ItemDetailComponent, superClass); function ItemDetailComponent(json) { this.json = json; ItemDetailComponent.__super__.constructor.call(this, this.json); } /** A service line number. @returns {Array} an array of {@link Number} objects */ ItemDetailComponent.prototype.sequenceLinkId = function() { return this.json['sequenceLinkId']; }; /** The adjudications results. @returns {Array} an array of {@link DetailAdjudicationComponent} objects */ ItemDetailComponent.prototype.adjudication = function() { var i, item, len, ref, results; if (this.json['adjudication']) { ref = this.json['adjudication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DetailAdjudicationComponent(item)); } return results; } }; /** The third tier service adjudications for submitted services. @returns {Array} an array of {@link ItemSubdetailComponent} objects */ ItemDetailComponent.prototype.subdetail = function() { var i, item, len, ref, results; if (this.json['subdetail']) { ref = this.json['subdetail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ItemSubdetailComponent(item)); } return results; } }; return ItemDetailComponent; })(BackboneElement); /** Embedded class @class ItemsComponent @exports ItemsComponent as ItemsComponent */ ItemsComponent = (function(superClass) { extend(ItemsComponent, superClass); function ItemsComponent(json) { this.json = json; ItemsComponent.__super__.constructor.call(this, this.json); } /** A service line number. @returns {Array} an array of {@link Number} objects */ ItemsComponent.prototype.sequenceLinkId = function() { return this.json['sequenceLinkId']; }; /** A list of note references to the notes provided below. @returns {Array} an array of {@link Number} objects */ ItemsComponent.prototype.noteNumber = function() { return this.json['noteNumber']; }; /** The adjudications results. @returns {Array} an array of {@link ItemAdjudicationComponent} objects */ ItemsComponent.prototype.adjudication = function() { var i, item, len, ref, results; if (this.json['adjudication']) { ref = this.json['adjudication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ItemAdjudicationComponent(item)); } return results; } }; /** The second tier service adjudications for submitted services. @returns {Array} an array of {@link ItemDetailComponent} objects */ ItemsComponent.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ItemDetailComponent(item)); } return results; } }; return ItemsComponent; })(BackboneElement); /** Embedded class @class AddedItemAdjudicationComponent @exports AddedItemAdjudicationComponent as AddedItemAdjudicationComponent */ AddedItemAdjudicationComponent = (function(superClass) { extend(AddedItemAdjudicationComponent, superClass); function AddedItemAdjudicationComponent(json) { this.json = json; AddedItemAdjudicationComponent.__super__.constructor.call(this, this.json); } /** Code indicating: Co-Pay, deductable, elegible, benefit, tax, etc. @returns {Coding} */ AddedItemAdjudicationComponent.prototype.code = function() { if (this.json['code']) { return new Coding(this.json['code']); } }; /** Monitory amount associated with the code. @returns {Money} */ AddedItemAdjudicationComponent.prototype.amount = function() { if (this.json['amount']) { return new Money(this.json['amount']); } }; /** A non-monitary value for example a percentage. Mutually exclusive to the amount element above. @returns {Array} an array of {@link Number} objects */ AddedItemAdjudicationComponent.prototype.value = function() { return this.json['value']; }; return AddedItemAdjudicationComponent; })(BackboneElement); /** Embedded class @class AddedItemDetailAdjudicationComponent @exports AddedItemDetailAdjudicationComponent as AddedItemDetailAdjudicationComponent */ AddedItemDetailAdjudicationComponent = (function(superClass) { extend(AddedItemDetailAdjudicationComponent, superClass); function AddedItemDetailAdjudicationComponent(json) { this.json = json; AddedItemDetailAdjudicationComponent.__super__.constructor.call(this, this.json); } /** Code indicating: Co-Pay, deductable, elegible, benefit, tax, etc. @returns {Coding} */ AddedItemDetailAdjudicationComponent.prototype.code = function() { if (this.json['code']) { return new Coding(this.json['code']); } }; /** Monitory amount associated with the code. @returns {Money} */ AddedItemDetailAdjudicationComponent.prototype.amount = function() { if (this.json['amount']) { return new Money(this.json['amount']); } }; /** A non-monitary value for example a percentage. Mutually exclusive to the amount element above. @returns {Array} an array of {@link Number} objects */ AddedItemDetailAdjudicationComponent.prototype.value = function() { return this.json['value']; }; return AddedItemDetailAdjudicationComponent; })(BackboneElement); /** Embedded class @class AddedItemsDetailComponent @exports AddedItemsDetailComponent as AddedItemsDetailComponent */ AddedItemsDetailComponent = (function(superClass) { extend(AddedItemsDetailComponent, superClass); function AddedItemsDetailComponent(json) { this.json = json; AddedItemsDetailComponent.__super__.constructor.call(this, this.json); } /** A code to indicate the Professional Service or Product supplied. @returns {Coding} */ AddedItemsDetailComponent.prototype.service = function() { if (this.json['service']) { return new Coding(this.json['service']); } }; /** The fee charged for the professional service or product.. @returns {Money} */ AddedItemsDetailComponent.prototype.fee = function() { if (this.json['fee']) { return new Money(this.json['fee']); } }; /** The adjudications results. @returns {Array} an array of {@link AddedItemDetailAdjudicationComponent} objects */ AddedItemsDetailComponent.prototype.adjudication = function() { var i, item, len, ref, results; if (this.json['adjudication']) { ref = this.json['adjudication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new AddedItemDetailAdjudicationComponent(item)); } return results; } }; return AddedItemsDetailComponent; })(BackboneElement); /** Embedded class @class AddedItemComponent @exports AddedItemComponent as AddedItemComponent */ AddedItemComponent = (function(superClass) { extend(AddedItemComponent, superClass); function AddedItemComponent(json) { this.json = json; AddedItemComponent.__super__.constructor.call(this, this.json); } /** List of input service items which this service line is intended to replace. @returns {Array} an array of {@link Number} objects */ AddedItemComponent.prototype.sequenceLinkId = function() { return this.json['sequenceLinkId']; }; /** A code to indicate the Professional Service or Product supplied. @returns {Coding} */ AddedItemComponent.prototype.service = function() { if (this.json['service']) { return new Coding(this.json['service']); } }; /** The fee charged for the professional service or product.. @returns {Money} */ AddedItemComponent.prototype.fee = function() { if (this.json['fee']) { return new Money(this.json['fee']); } }; /** A list of note references to the notes provided below. @returns {Array} an array of {@link Number} objects */ AddedItemComponent.prototype.noteNumberLinkId = function() { return this.json['noteNumberLinkId']; }; /** The adjudications results. @returns {Array} an array of {@link AddedItemAdjudicationComponent} objects */ AddedItemComponent.prototype.adjudication = function() { var i, item, len, ref, results; if (this.json['adjudication']) { ref = this.json['adjudication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new AddedItemAdjudicationComponent(item)); } return results; } }; /** The second tier service adjudications for payor added services. @returns {Array} an array of {@link AddedItemsDetailComponent} objects */ AddedItemComponent.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new AddedItemsDetailComponent(item)); } return results; } }; return AddedItemComponent; })(BackboneElement); /** Embedded class @class ErrorsComponent @exports ErrorsComponent as ErrorsComponent */ ErrorsComponent = (function(superClass) { extend(ErrorsComponent, superClass); function ErrorsComponent(json) { this.json = json; ErrorsComponent.__super__.constructor.call(this, this.json); } /** The sequence number of the line item submitted which contains the error. This value is ommitted when the error is elsewhere. @returns {Array} an array of {@link Number} objects */ ErrorsComponent.prototype.sequenceLinkId = function() { return this.json['sequenceLinkId']; }; /** The sequence number of the addition within the line item submitted which contains the error. This value is ommitted when the error is not related to an Addition. @returns {Array} an array of {@link Number} objects */ ErrorsComponent.prototype.detailSequenceLinkId = function() { return this.json['detailSequenceLinkId']; }; /** The sequence number of the addition within the line item submitted which contains the error. This value is ommitted when the error is not related to an Addition. @returns {Array} an array of {@link Number} objects */ ErrorsComponent.prototype.subdetailSequenceLinkId = function() { return this.json['subdetailSequenceLinkId']; }; /** An error code,froma specified code system, which details why the claim could not be adjudicated. @returns {Coding} */ ErrorsComponent.prototype.code = function() { if (this.json['code']) { return new Coding(this.json['code']); } }; return ErrorsComponent; })(BackboneElement); /** Embedded class @class NotesComponent @exports NotesComponent as NotesComponent */ NotesComponent = (function(superClass) { extend(NotesComponent, superClass); function NotesComponent(json) { this.json = json; NotesComponent.__super__.constructor.call(this, this.json); } /** An integer associated with each note which may be referred to from each service line item. @returns {Array} an array of {@link Number} objects */ NotesComponent.prototype.number = function() { return this.json['number']; }; /** The note purpose: Print/Display. @returns {Coding} */ NotesComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The note text. @returns {Array} an array of {@link String} objects */ NotesComponent.prototype.text = function() { return this.json['text']; }; return NotesComponent; })(BackboneElement); /** This resource provides the adjudication details from the processing of a Claim resource. @class ClaimResponse @exports ClaimResponse as ClaimResponse */ ClaimResponse = (function(superClass) { extend(ClaimResponse, superClass); function ClaimResponse(json) { this.json = json; ClaimResponse.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ ClaimResponse.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Original request resource referrence. @returns {Reference} */ ClaimResponse.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ ClaimResponse.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ ClaimResponse.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ ClaimResponse.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who produced this adjudicated response. @returns {Reference} */ ClaimResponse.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ ClaimResponse.prototype.requestProvider = function() { if (this.json['requestProvider']) { return new Reference(this.json['requestProvider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ ClaimResponse.prototype.requestOrganization = function() { if (this.json['requestOrganization']) { return new Reference(this.json['requestOrganization']); } }; /** Transaction status: error, complete. @returns {Array} an array of {@link String} objects */ ClaimResponse.prototype.outcome = function() { return this.json['outcome']; }; /** A description of the status of the adjudication. @returns {Array} an array of {@link String} objects */ ClaimResponse.prototype.disposition = function() { return this.json['disposition']; }; /** Party to be reimbursed: Subscriber, provider, other. @returns {Coding} */ ClaimResponse.prototype.payeeType = function() { if (this.json['payeeType']) { return new Coding(this.json['payeeType']); } }; /** The first tier service adjudications for submitted services. @returns {Array} an array of {@link ItemsComponent} objects */ ClaimResponse.prototype.item = function() { var i, item, len, ref, results; if (this.json['item']) { ref = this.json['item']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ItemsComponent(item)); } return results; } }; /** The first tier service adjudications for payor added services. @returns {Array} an array of {@link AddedItemComponent} objects */ ClaimResponse.prototype.additem = function() { var i, item, len, ref, results; if (this.json['additem']) { ref = this.json['additem']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new AddedItemComponent(item)); } return results; } }; /** Mutually exclusive with Services Provided (Item). @returns {Array} an array of {@link ErrorsComponent} objects */ ClaimResponse.prototype.error = function() { var i, item, len, ref, results; if (this.json['error']) { ref = this.json['error']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ErrorsComponent(item)); } return results; } }; /** The total cost of the services reported. @returns {Money} */ ClaimResponse.prototype.totalCost = function() { if (this.json['totalCost']) { return new Money(this.json['totalCost']); } }; /** The amount of deductable applied which was not allocated to any particular service line. @returns {Money} */ ClaimResponse.prototype.unallocDeductable = function() { if (this.json['unallocDeductable']) { return new Money(this.json['unallocDeductable']); } }; /** Total amount of benefit payable (Equal to sum of the Benefit amounts from all detail lines and additions less the Unallocated Deductable). @returns {Money} */ ClaimResponse.prototype.totalBenefit = function() { if (this.json['totalBenefit']) { return new Money(this.json['totalBenefit']); } }; /** Adjustment to the payment of this transaction which is not related to adjudication of this transaction. @returns {Money} */ ClaimResponse.prototype.paymentAdjustment = function() { if (this.json['paymentAdjustment']) { return new Money(this.json['paymentAdjustment']); } }; /** Reason for the payment adjustment. @returns {Coding} */ ClaimResponse.prototype.paymentAdjustmentReason = function() { if (this.json['paymentAdjustmentReason']) { return new Coding(this.json['paymentAdjustmentReason']); } }; /** Estimated payment data. @returns {Array} an array of {@link Date} objects */ ClaimResponse.prototype.paymentDate = function() { if (this.json['paymentDate']) { return DT.DateTime.parse(this.json['paymentDate']); } }; /** Payable less any payment adjustment. @returns {Money} */ ClaimResponse.prototype.paymentAmount = function() { if (this.json['paymentAmount']) { return new Money(this.json['paymentAmount']); } }; /** Payment identifer. @returns {Identifier} */ ClaimResponse.prototype.paymentRef = function() { if (this.json['paymentRef']) { return new Identifier(this.json['paymentRef']); } }; /** Status of funds reservation (For provider, for Patient, None). @returns {Coding} */ ClaimResponse.prototype.reserved = function() { if (this.json['reserved']) { return new Coding(this.json['reserved']); } }; /** The form to be used for printing the content. @returns {Coding} */ ClaimResponse.prototype.form = function() { if (this.json['form']) { return new Coding(this.json['form']); } }; /** Note text. @returns {Array} an array of {@link NotesComponent} objects */ ClaimResponse.prototype.note = function() { var i, item, len, ref, results; if (this.json['note']) { ref = this.json['note']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new NotesComponent(item)); } return results; } }; return ClaimResponse; })(DomainResource); module.exports.ClaimResponse = ClaimResponse; }).call(this); },{"../cql-datatypes":117,"./core":173}],166:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, CommunicationRequest, CommunicationRequestMessagePartComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class CommunicationRequestMessagePartComponent @exports CommunicationRequestMessagePartComponent as CommunicationRequestMessagePartComponent */ CommunicationRequestMessagePartComponent = (function(superClass) { extend(CommunicationRequestMessagePartComponent, superClass); function CommunicationRequestMessagePartComponent(json) { this.json = json; CommunicationRequestMessagePartComponent.__super__.constructor.call(this, this.json); } /** An individual message part for multi-part messages. @returns {Array} an array of {@link String} objects */ CommunicationRequestMessagePartComponent.prototype.contentString = function() { return this.json['contentString']; }; /** An individual message part for multi-part messages. @returns {Attachment} */ CommunicationRequestMessagePartComponent.prototype.contentAttachment = function() { if (this.json['contentAttachment']) { return new Attachment(this.json['contentAttachment']); } }; /** An individual message part for multi-part messages. @returns {Reference} */ CommunicationRequestMessagePartComponent.prototype.contentReference = function() { if (this.json['contentReference']) { return new Reference(this.json['contentReference']); } }; return CommunicationRequestMessagePartComponent; })(BackboneElement); /** A request to convey information. E.g., the CDS system proposes that an alert be sent to a responsible provider, the CDS system proposes that the public health agency be notified about a reportable condition. @class CommunicationRequest @exports CommunicationRequest as CommunicationRequest */ CommunicationRequest = (function(superClass) { extend(CommunicationRequest, superClass); function CommunicationRequest(json) { this.json = json; CommunicationRequest.__super__.constructor.call(this, this.json); } /** A unique ID of this request for reference purposes. It must be provided if user wants it returned as part of any output, otherwise it will be auto-generated, if needed, by CDS system. Does not need to be the actual ID of the source system. @returns {Array} an array of {@link Identifier} objects */ CommunicationRequest.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The type of message such as alert, notification, reminder, instruction, etc. @returns {CodeableConcept} */ CommunicationRequest.prototype.category = function() { if (this.json['category']) { return new CodeableConcept(this.json['category']); } }; /** The entity (e.g., person, organization, clinical information system, or device) which is the source of the communication. @returns {Reference} */ CommunicationRequest.prototype.sender = function() { if (this.json['sender']) { return new Reference(this.json['sender']); } }; /** The entity (e.g., person, organization, clinical information system, or device) which is the intended target of the communication. @returns {Array} an array of {@link Reference} objects */ CommunicationRequest.prototype.recipient = function() { var i, item, len, ref, results; if (this.json['recipient']) { ref = this.json['recipient']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Text, attachment(s), or resource(s) to be communicated to the recipient. @returns {Array} an array of {@link CommunicationRequestMessagePartComponent} objects */ CommunicationRequest.prototype.messagePart = function() { var i, item, len, ref, results; if (this.json['messagePart']) { ref = this.json['messagePart']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CommunicationRequestMessagePartComponent(item)); } return results; } }; /** The communication medium, e.g., email, fax. @returns {Array} an array of {@link CodeableConcept} objects */ CommunicationRequest.prototype.medium = function() { var i, item, len, ref, results; if (this.json['medium']) { ref = this.json['medium']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The responsible person who authorizes this order, e.g., physician. This may be different than the author of the order statement, e.g., clerk, who may have entered the statement into the order entry application. @returns {Reference} */ CommunicationRequest.prototype.requester = function() { if (this.json['requester']) { return new Reference(this.json['requester']); } }; /** The status of the proposal or order. @returns {Array} an array of {@link String} objects */ CommunicationRequest.prototype.status = function() { return this.json['status']; }; /** Whether the communication is proposed, ordered, or planned. @returns {Array} an array of {@link String} objects */ CommunicationRequest.prototype.mode = function() { return this.json['mode']; }; /** The encounter within which the communication request was created. @returns {Reference} */ CommunicationRequest.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** The time when this communication is to occur. @returns {Array} an array of {@link Date} objects */ CommunicationRequest.prototype.scheduledTime = function() { if (this.json['scheduledTime']) { return DT.DateTime.parse(this.json['scheduledTime']); } }; /** The reason or justification for the communication request. @returns {Array} an array of {@link CodeableConcept} objects */ CommunicationRequest.prototype.indication = function() { var i, item, len, ref, results; if (this.json['indication']) { ref = this.json['indication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The time when the request was made. @returns {Array} an array of {@link Date} objects */ CommunicationRequest.prototype.orderedOn = function() { if (this.json['orderedOn']) { return DT.DateTime.parse(this.json['orderedOn']); } }; /** The patient who is the focus of this communication request. @returns {Reference} */ CommunicationRequest.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Characterizes how quickly the proposed act must be initiated. Includes concepts such as stat, urgent, routine. @returns {CodeableConcept} */ CommunicationRequest.prototype.priority = function() { if (this.json['priority']) { return new CodeableConcept(this.json['priority']); } }; return CommunicationRequest; })(DomainResource); module.exports.CommunicationRequest = CommunicationRequest; }).call(this); },{"../cql-datatypes":117,"./core":173}],167:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, Composition, CompositionAttesterComponent, CompositionEventComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, SectionComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class CompositionAttesterComponent @exports CompositionAttesterComponent as CompositionAttesterComponent */ CompositionAttesterComponent = (function(superClass) { extend(CompositionAttesterComponent, superClass); function CompositionAttesterComponent(json) { this.json = json; CompositionAttesterComponent.__super__.constructor.call(this, this.json); } /** The type of attestation the authenticator offers. @returns {Array} an array of {@link String} objects */ CompositionAttesterComponent.prototype.mode = function() { return this.json['mode']; }; /** When composition was attested by the party. @returns {Array} an array of {@link Date} objects */ CompositionAttesterComponent.prototype.time = function() { if (this.json['time']) { return DT.DateTime.parse(this.json['time']); } }; /** Who attested the composition in the specified way. @returns {Reference} */ CompositionAttesterComponent.prototype.party = function() { if (this.json['party']) { return new Reference(this.json['party']); } }; return CompositionAttesterComponent; })(BackboneElement); /** Embedded class @class CompositionEventComponent @exports CompositionEventComponent as CompositionEventComponent */ CompositionEventComponent = (function(superClass) { extend(CompositionEventComponent, superClass); function CompositionEventComponent(json) { this.json = json; CompositionEventComponent.__super__.constructor.call(this, this.json); } /** This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a "History and Physical Report" in which the procedure being documented is necessarily a "History and Physical" act. @returns {Array} an array of {@link CodeableConcept} objects */ CompositionEventComponent.prototype.code = function() { var i, item, len, ref, results; if (this.json['code']) { ref = this.json['code']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The period of time covered by the documentation. There is no assertion that the documentation is a complete representation for this period, only that it documents events during this time. @returns {Period} */ CompositionEventComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** Full details for the event(s) the composition/documentation consents. @returns {Array} an array of {@link Reference} objects */ CompositionEventComponent.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return CompositionEventComponent; })(BackboneElement); /** Embedded class @class SectionComponent @exports SectionComponent as SectionComponent */ SectionComponent = (function(superClass) { extend(SectionComponent, superClass); function SectionComponent(json) { this.json = json; SectionComponent.__super__.constructor.call(this, this.json); } /** The label for this particular section. This will be part of the rendered content for the document, and is often used to build a table of contents. @returns {Array} an array of {@link String} objects */ SectionComponent.prototype.title = function() { return this.json['title']; }; /** A code identifying the kind of content contained within the section. This must be consistent with the section title. @returns {CodeableConcept} */ SectionComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** A nested sub-section within this section. @returns {Array} an array of {@link SectionComponent} objects */ SectionComponent.prototype.section = function() { var i, item, len, ref, results; if (this.json['section']) { ref = this.json['section']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SectionComponent(item)); } return results; } }; /** The content (narrative and data) associated with the section. @returns {Reference} */ SectionComponent.prototype.content = function() { if (this.json['content']) { return new Reference(this.json['content']); } }; return SectionComponent; })(BackboneElement); /** A set of healthcare-related information that is assembled together into a single logical document that provides a single coherent statement of meaning, establishes its own context and that has clinical attestation with regard to who is making the statement. @class Composition @exports Composition as Composition */ Composition = (function(superClass) { extend(Composition, superClass); function Composition(json) { this.json = json; Composition.__super__.constructor.call(this, this.json); } /** Logical Identifier for the composition, assigned when created. This identifier stays constant as the composition is changed over time. @returns {Identifier} */ Composition.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** The composition editing time, when the composition was last logically changed by the author. @returns {Array} an array of {@link Date} objects */ Composition.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Specifies the particular kind of composition (e.g. History and Physical, Discharge Summary, Progress Note). This usually equates to the purpose of making the composition. @returns {CodeableConcept} */ Composition.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** A categorization for the type of the composition. This may be implied by or derived from the code specified in the Composition Type. @returns {CodeableConcept} */ Composition.prototype["class"] = function() { if (this.json['class']) { return new CodeableConcept(this.json['class']); } }; /** Official human-readable label for the composition. @returns {Array} an array of {@link String} objects */ Composition.prototype.title = function() { return this.json['title']; }; /** The workflow/clinical status of this composition. The status is a marker for the clinical standing of the document. @returns {Array} an array of {@link String} objects */ Composition.prototype.status = function() { return this.json['status']; }; /** The code specifying the level of confidentiality of the Composition. @returns {Coding} */ Composition.prototype.confidentiality = function() { if (this.json['confidentiality']) { return new Coding(this.json['confidentiality']); } }; /** Who or what the composition is about. The composition can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of livestock, or a set of patients that share a common exposure). @returns {Reference} */ Composition.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Identifies who is responsible for the information in the composition. (Not necessarily who typed it in.). @returns {Array} an array of {@link Reference} objects */ Composition.prototype.author = function() { var i, item, len, ref, results; if (this.json['author']) { ref = this.json['author']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** A participant who has attested to the accuracy of the composition/document. @returns {Array} an array of {@link CompositionAttesterComponent} objects */ Composition.prototype.attester = function() { var i, item, len, ref, results; if (this.json['attester']) { ref = this.json['attester']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CompositionAttesterComponent(item)); } return results; } }; /** Identifies the organization or group who is responsible for ongoing maintenance of and access to the composition/document information. @returns {Reference} */ Composition.prototype.custodian = function() { if (this.json['custodian']) { return new Reference(this.json['custodian']); } }; /** The clinical service, such as a colonoscopy or an appendectomy, being documented. @returns {Array} an array of {@link CompositionEventComponent} objects */ Composition.prototype.event = function() { var i, item, len, ref, results; if (this.json['event']) { ref = this.json['event']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CompositionEventComponent(item)); } return results; } }; /** Describes the clinical encounter or type of care this documentation is associated with. @returns {Reference} */ Composition.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** The root of the sections that make up the composition. @returns {Array} an array of {@link SectionComponent} objects */ Composition.prototype.section = function() { var i, item, len, ref, results; if (this.json['section']) { ref = this.json['section']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SectionComponent(item)); } return results; } }; return Composition; })(DomainResource); module.exports.Composition = Composition; }).call(this); },{"../cql-datatypes":117,"./core":173}],168:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ConceptMap, ConceptMapElementComponent, ConceptMapElementMapComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, OtherElementComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class OtherElementComponent @exports OtherElementComponent as OtherElementComponent */ OtherElementComponent = (function(superClass) { extend(OtherElementComponent, superClass); function OtherElementComponent(json) { this.json = json; OtherElementComponent.__super__.constructor.call(this, this.json); } /** A reference to a specific concept that holds a coded value. This can be an element in a FHIR resource, or a specific reference to a data element in a different specification (e.g. v2) or a general reference to a kind of data field, or a reference to a value set with an appropriately narrow definition. @returns {Array} an array of {@link String} objects */ OtherElementComponent.prototype.element = function() { return this.json['element']; }; /** The code system of the dependency code (if the source/dependency is a value set that cross code systems). @returns {Array} an array of {@link String} objects */ OtherElementComponent.prototype.codeSystem = function() { return this.json['codeSystem']; }; /** Identity (code or path) or the element/item that the map depends on / refers to. @returns {Array} an array of {@link String} objects */ OtherElementComponent.prototype.code = function() { return this.json['code']; }; return OtherElementComponent; })(BackboneElement); /** Embedded class @class ConceptMapElementMapComponent @exports ConceptMapElementMapComponent as ConceptMapElementMapComponent */ ConceptMapElementMapComponent = (function(superClass) { extend(ConceptMapElementMapComponent, superClass); function ConceptMapElementMapComponent(json) { this.json = json; ConceptMapElementMapComponent.__super__.constructor.call(this, this.json); } /** The code system of the target code (if the target is a value set that cross code systems). @returns {Array} an array of {@link String} objects */ ConceptMapElementMapComponent.prototype.codeSystem = function() { return this.json['codeSystem']; }; /** Identity (code or path) or the element/item that the map refers to. @returns {Array} an array of {@link String} objects */ ConceptMapElementMapComponent.prototype.code = function() { return this.json['code']; }; /** The equivalence between the source and target concepts (counting for the dependencies and products). The equivalence is read from source to target (e.g. the source is 'wider' than the target. @returns {Array} an array of {@link String} objects */ ConceptMapElementMapComponent.prototype.equivalence = function() { return this.json['equivalence']; }; /** A description of status/issues in mapping that conveys additional information not represented in the structured data. @returns {Array} an array of {@link String} objects */ ConceptMapElementMapComponent.prototype.comments = function() { return this.json['comments']; }; /** A set of additional outcomes from this mapping to other elements. To properly execute this mapping, the specified element must be mapped to some data element or source that is in context. The mapping may still be useful without a place for the additional data elements, but the equivalence cannot be relied on. @returns {Array} an array of {@link OtherElementComponent} objects */ ConceptMapElementMapComponent.prototype.product = function() { var i, item, len, ref, results; if (this.json['product']) { ref = this.json['product']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new OtherElementComponent(item)); } return results; } }; return ConceptMapElementMapComponent; })(BackboneElement); /** Embedded class @class ConceptMapElementComponent @exports ConceptMapElementComponent as ConceptMapElementComponent */ ConceptMapElementComponent = (function(superClass) { extend(ConceptMapElementComponent, superClass); function ConceptMapElementComponent(json) { this.json = json; ConceptMapElementComponent.__super__.constructor.call(this, this.json); } /** Code System (if the source is a value value set that crosses more than one code system). @returns {Array} an array of {@link String} objects */ ConceptMapElementComponent.prototype.codeSystem = function() { return this.json['codeSystem']; }; /** Identity (code or path) or the element/item being mapped. @returns {Array} an array of {@link String} objects */ ConceptMapElementComponent.prototype.code = function() { return this.json['code']; }; /** A set of additional dependencies for this mapping to hold. This mapping is only applicable if the specified element can be resolved, and it has the specified value. @returns {Array} an array of {@link OtherElementComponent} objects */ ConceptMapElementComponent.prototype.dependsOn = function() { var i, item, len, ref, results; if (this.json['dependsOn']) { ref = this.json['dependsOn']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new OtherElementComponent(item)); } return results; } }; /** A concept from the target value set that this concept maps to. @returns {Array} an array of {@link ConceptMapElementMapComponent} objects */ ConceptMapElementComponent.prototype.map = function() { var i, item, len, ref, results; if (this.json['map']) { ref = this.json['map']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptMapElementMapComponent(item)); } return results; } }; return ConceptMapElementComponent; })(BackboneElement); /** A statement of relationships from one set of concepts to one or more other concepts - either code systems or data elements, or classes in class models. @class ConceptMap @exports ConceptMap as ConceptMap */ ConceptMap = (function(superClass) { extend(ConceptMap, superClass); function ConceptMap(json) { this.json = json; ConceptMap.__super__.constructor.call(this, this.json); } /** The identifier that is used to identify this concept map when it is referenced in a specification, model, design or an instance (should be globally unique OID, UUID, or URI). @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.identifier = function() { return this.json['identifier']; }; /** The identifier that is used to identify this version of the concept map when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the profile author manually and the value should be a timestamp. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.version = function() { return this.json['version']; }; /** A free text natural language name describing the concept map. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.name = function() { return this.json['name']; }; /** The name of the individual or organization that published the concept map. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.publisher = function() { return this.json['publisher']; }; /** Contacts of the publisher to assist a user in finding and communicating with the publisher. @returns {Array} an array of {@link ContactPoint} objects */ ConceptMap.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** A free text natural language description of the use of the concept map - reason for definition, conditions of use, etc. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.description = function() { return this.json['description']; }; /** A copyright statement relating to the concept map and/or its contents. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.copyright = function() { return this.json['copyright']; }; /** The status of the concept map. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.status = function() { return this.json['status']; }; /** This ConceptMap was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. @returns {Array} an array of {@link boolean} objects */ ConceptMap.prototype.experimental = function() { return this.json['experimental']; }; /** The date that the concept map status was last changed. @returns {Array} an array of {@link Date} objects */ ConceptMap.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The source value set that specifies the concepts that are being mapped. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.sourceUri = function() { return this.json['sourceUri']; }; /** The source value set that specifies the concepts that are being mapped. @returns {Reference} */ ConceptMap.prototype.sourceReference = function() { if (this.json['sourceReference']) { return new Reference(this.json['sourceReference']); } }; /** The target value set provides context to the mappings. Note that the mapping is made between concepts, not between value sets, but the value set provides important context about how the concept mapping choices are made. @returns {Array} an array of {@link String} objects */ ConceptMap.prototype.targetUri = function() { return this.json['targetUri']; }; /** The target value set provides context to the mappings. Note that the mapping is made between concepts, not between value sets, but the value set provides important context about how the concept mapping choices are made. @returns {Reference} */ ConceptMap.prototype.targetReference = function() { if (this.json['targetReference']) { return new Reference(this.json['targetReference']); } }; /** Mappings for an individual concept in the source to one or more concepts in the target. @returns {Array} an array of {@link ConceptMapElementComponent} objects */ ConceptMap.prototype.element = function() { var i, item, len, ref, results; if (this.json['element']) { ref = this.json['element']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptMapElementComponent(item)); } return results; } }; return ConceptMap; })(DomainResource); module.exports.ConceptMap = ConceptMap; }).call(this); },{"../cql-datatypes":117,"./core":173}],169:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, Condition, ConditionDueToComponent, ConditionEvidenceComponent, ConditionLocationComponent, ConditionOccurredFollowingComponent, ConditionStageComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ConditionStageComponent @exports ConditionStageComponent as ConditionStageComponent */ ConditionStageComponent = (function(superClass) { extend(ConditionStageComponent, superClass); function ConditionStageComponent(json) { this.json = json; ConditionStageComponent.__super__.constructor.call(this, this.json); } /** A simple summary of the stage such as "Stage 3". The determination of the stage is disease-specific. @returns {CodeableConcept} */ ConditionStageComponent.prototype.summary = function() { if (this.json['summary']) { return new CodeableConcept(this.json['summary']); } }; /** Reference to a formal record of the evidence on which the staging assessment is based. @returns {Array} an array of {@link Reference} objects */ ConditionStageComponent.prototype.assessment = function() { var i, item, len, ref, results; if (this.json['assessment']) { ref = this.json['assessment']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return ConditionStageComponent; })(BackboneElement); /** Embedded class @class ConditionEvidenceComponent @exports ConditionEvidenceComponent as ConditionEvidenceComponent */ ConditionEvidenceComponent = (function(superClass) { extend(ConditionEvidenceComponent, superClass); function ConditionEvidenceComponent(json) { this.json = json; ConditionEvidenceComponent.__super__.constructor.call(this, this.json); } /** A manifestation or symptom that led to the recording of this condition. @returns {CodeableConcept} */ ConditionEvidenceComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** Links to other relevant information, including pathology reports. @returns {Array} an array of {@link Reference} objects */ ConditionEvidenceComponent.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return ConditionEvidenceComponent; })(BackboneElement); /** Embedded class @class ConditionLocationComponent @exports ConditionLocationComponent as ConditionLocationComponent */ ConditionLocationComponent = (function(superClass) { extend(ConditionLocationComponent, superClass); function ConditionLocationComponent(json) { this.json = json; ConditionLocationComponent.__super__.constructor.call(this, this.json); } /** Code that identifies the structural location. @returns {CodeableConcept} */ ConditionLocationComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** Detailed anatomical location information. @returns {Array} an array of {@link String} objects */ ConditionLocationComponent.prototype.detail = function() { return this.json['detail']; }; return ConditionLocationComponent; })(BackboneElement); /** Embedded class @class ConditionDueToComponent @exports ConditionDueToComponent as ConditionDueToComponent */ ConditionDueToComponent = (function(superClass) { extend(ConditionDueToComponent, superClass); function ConditionDueToComponent(json) { this.json = json; ConditionDueToComponent.__super__.constructor.call(this, this.json); } /** Code that identifies the target of this relationship. The code takes the place of a detailed instance target. @returns {CodeableConcept} */ ConditionDueToComponent.prototype.codeableConcept = function() { if (this.json['codeableConcept']) { return new CodeableConcept(this.json['codeableConcept']); } }; /** Target of the relationship. @returns {Reference} */ ConditionDueToComponent.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; return ConditionDueToComponent; })(BackboneElement); /** Embedded class @class ConditionOccurredFollowingComponent @exports ConditionOccurredFollowingComponent as ConditionOccurredFollowingComponent */ ConditionOccurredFollowingComponent = (function(superClass) { extend(ConditionOccurredFollowingComponent, superClass); function ConditionOccurredFollowingComponent(json) { this.json = json; ConditionOccurredFollowingComponent.__super__.constructor.call(this, this.json); } /** Code that identifies the target of this relationship. The code takes the place of a detailed instance target. @returns {CodeableConcept} */ ConditionOccurredFollowingComponent.prototype.codeableConcept = function() { if (this.json['codeableConcept']) { return new CodeableConcept(this.json['codeableConcept']); } }; /** Target of the relationship. @returns {Reference} */ ConditionOccurredFollowingComponent.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; return ConditionOccurredFollowingComponent; })(BackboneElement); /** Use to record detailed information about conditions, problems or diagnoses recognized by a clinician. There are many uses including: recording a Diagnosis during an Encounter; populating a problem List or a Summary Statement, such as a Discharge Summary. @class Condition @exports Condition as Condition */ Condition = (function(superClass) { extend(Condition, superClass); function Condition(json) { this.json = json; Condition.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this condition that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ Condition.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Indicates the patient who the condition record is associated with. @returns {Reference} */ Condition.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Encounter during which the condition was first asserted. @returns {Reference} */ Condition.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** Person who takes responsibility for asserting the existence of the condition as part of the electronic record. @returns {Reference} */ Condition.prototype.asserter = function() { if (this.json['asserter']) { return new Reference(this.json['asserter']); } }; /** Estimated or actual date the condition/problem/diagnosis was first detected/suspected. @returns {Array} an array of {@link Date} objects */ Condition.prototype.dateAsserted = function() { if (this.json['dateAsserted']) { return DT.DateTime.parse(this.json['dateAsserted']); } }; /** Identification of the condition, problem or diagnosis. @returns {CodeableConcept} */ Condition.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** A category assigned to the condition. E.g. complaint | symptom | finding | diagnosis. @returns {CodeableConcept} */ Condition.prototype.category = function() { if (this.json['category']) { return new CodeableConcept(this.json['category']); } }; /** The clinical status of the condition. @returns {Array} an array of {@link String} objects */ Condition.prototype.status = function() { return this.json['status']; }; /** The degree of confidence that this condition is correct. @returns {CodeableConcept} */ Condition.prototype.certainty = function() { if (this.json['certainty']) { return new CodeableConcept(this.json['certainty']); } }; /** A subjective assessment of the severity of the condition as evaluated by the clinician. @returns {CodeableConcept} */ Condition.prototype.severity = function() { if (this.json['severity']) { return new CodeableConcept(this.json['severity']); } }; /** Estimated or actual date or date-time the condition began, in the opinion of the clinician. @returns {Array} an array of {@link Date} objects */ Condition.prototype.onsetDateTime = function() { if (this.json['onsetDateTime']) { return DT.DateTime.parse(this.json['onsetDateTime']); } }; Condition.prototype.onsetAge = function() { return new Quantity(this.json['onsetAge']); }; /** The date or estimated date that the condition resolved or went into remission. This is called "abatement" because of the many overloaded connotations associated with "remission" or "resolution" - Conditions are never really resolved, but they can abate. @returns {Array} an array of {@link Date} objects */ Condition.prototype.abatementDate = function() { if (this.json['abatementDate']) { return DT.DateTime.parse(this.json['abatementDate']); } }; Condition.prototype.abatementAge = function() { return new Quantity(this.json['abatementAge']); }; /** The date or estimated date that the condition resolved or went into remission. This is called "abatement" because of the many overloaded connotations associated with "remission" or "resolution" - Conditions are never really resolved, but they can abate. @returns {Array} an array of {@link boolean} objects */ Condition.prototype.abatementBoolean = function() { return this.json['abatementBoolean']; }; /** Clinical stage or grade of a condition. May include formal severity assessments. @returns {ConditionStageComponent} */ Condition.prototype.stage = function() { if (this.json['stage']) { return new ConditionStageComponent(this.json['stage']); } }; /** Supporting Evidence / manifestations that are the basis on which this condition is suspected or confirmed. @returns {Array} an array of {@link ConditionEvidenceComponent} objects */ Condition.prototype.evidence = function() { var i, item, len, ref, results; if (this.json['evidence']) { ref = this.json['evidence']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConditionEvidenceComponent(item)); } return results; } }; /** The anatomical location where this condition manifests itself. @returns {Array} an array of {@link ConditionLocationComponent} objects */ Condition.prototype.location = function() { var i, item, len, ref, results; if (this.json['location']) { ref = this.json['location']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConditionLocationComponent(item)); } return results; } }; /** Further conditions, problems, diagnoses, procedures or events or the substance that caused/triggered this Condition. @returns {Array} an array of {@link ConditionDueToComponent} objects */ Condition.prototype.dueTo = function() { var i, item, len, ref, results; if (this.json['dueTo']) { ref = this.json['dueTo']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConditionDueToComponent(item)); } return results; } }; /** Further conditions, problems, diagnoses, procedures or events or the substance that preceded this Condition. @returns {Array} an array of {@link ConditionOccurredFollowingComponent} objects */ Condition.prototype.occurredFollowing = function() { var i, item, len, ref, results; if (this.json['occurredFollowing']) { ref = this.json['occurredFollowing']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConditionOccurredFollowingComponent(item)); } return results; } }; /** Additional information about the Condition. This is a general notes/comments entry for description of the Condition, its diagnosis and prognosis. @returns {Array} an array of {@link String} objects */ Condition.prototype.notes = function() { return this.json['notes']; }; return Condition; })(DomainResource); module.exports.Condition = Condition; }).call(this); },{"../cql-datatypes":117,"./core":173}],170:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, Conformance, ConformanceDocumentComponent, ConformanceImplementationComponent, ConformanceMessagingComponent, ConformanceMessagingEventComponent, ConformanceRestComponent, ConformanceRestOperationComponent, ConformanceRestResourceComponent, ConformanceRestResourceSearchParamComponent, ConformanceRestSecurityCertificateComponent, ConformanceRestSecurityComponent, ConformanceSoftwareComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, ResourceInteractionComponent, SampledData, SystemInteractionComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ConformanceSoftwareComponent @exports ConformanceSoftwareComponent as ConformanceSoftwareComponent */ ConformanceSoftwareComponent = (function(superClass) { extend(ConformanceSoftwareComponent, superClass); function ConformanceSoftwareComponent(json) { this.json = json; ConformanceSoftwareComponent.__super__.constructor.call(this, this.json); } /** Name software is known by. @returns {Array} an array of {@link String} objects */ ConformanceSoftwareComponent.prototype.name = function() { return this.json['name']; }; /** The version identifier for the software covered by this statement. @returns {Array} an array of {@link String} objects */ ConformanceSoftwareComponent.prototype.version = function() { return this.json['version']; }; /** Date this version of the software released. @returns {Array} an array of {@link Date} objects */ ConformanceSoftwareComponent.prototype.releaseDate = function() { if (this.json['releaseDate']) { return DT.DateTime.parse(this.json['releaseDate']); } }; return ConformanceSoftwareComponent; })(BackboneElement); /** Embedded class @class ConformanceImplementationComponent @exports ConformanceImplementationComponent as ConformanceImplementationComponent */ ConformanceImplementationComponent = (function(superClass) { extend(ConformanceImplementationComponent, superClass); function ConformanceImplementationComponent(json) { this.json = json; ConformanceImplementationComponent.__super__.constructor.call(this, this.json); } /** Information about the specific installation that this conformance statement relates to. @returns {Array} an array of {@link String} objects */ ConformanceImplementationComponent.prototype.description = function() { return this.json['description']; }; /** A base URL for the implementation. This forms the base for REST interfaces as well as the mailbox and document interfaces. @returns {Array} an array of {@link String} objects */ ConformanceImplementationComponent.prototype.url = function() { return this.json['url']; }; return ConformanceImplementationComponent; })(BackboneElement); /** Embedded class @class ConformanceRestSecurityCertificateComponent @exports ConformanceRestSecurityCertificateComponent as ConformanceRestSecurityCertificateComponent */ ConformanceRestSecurityCertificateComponent = (function(superClass) { extend(ConformanceRestSecurityCertificateComponent, superClass); function ConformanceRestSecurityCertificateComponent(json) { this.json = json; ConformanceRestSecurityCertificateComponent.__super__.constructor.call(this, this.json); } /** Mime type for certificate. @returns {Array} an array of {@link String} objects */ ConformanceRestSecurityCertificateComponent.prototype.type = function() { return this.json['type']; }; /** Actual certificate. @returns {Array} an array of {@link } objects */ ConformanceRestSecurityCertificateComponent.prototype.blob = function() { return this.json['blob']; }; return ConformanceRestSecurityCertificateComponent; })(BackboneElement); /** Embedded class @class ConformanceRestSecurityComponent @exports ConformanceRestSecurityComponent as ConformanceRestSecurityComponent */ ConformanceRestSecurityComponent = (function(superClass) { extend(ConformanceRestSecurityComponent, superClass); function ConformanceRestSecurityComponent(json) { this.json = json; ConformanceRestSecurityComponent.__super__.constructor.call(this, this.json); } /** Server adds CORS headers when responding to requests - this enables javascript applications to use the server. @returns {Array} an array of {@link boolean} objects */ ConformanceRestSecurityComponent.prototype.cors = function() { return this.json['cors']; }; /** Types of security services are supported/required by the system. @returns {Array} an array of {@link CodeableConcept} objects */ ConformanceRestSecurityComponent.prototype.service = function() { var i, item, len, ref, results; if (this.json['service']) { ref = this.json['service']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** General description of how security works. @returns {Array} an array of {@link String} objects */ ConformanceRestSecurityComponent.prototype.description = function() { return this.json['description']; }; /** Certificates associated with security profiles. @returns {Array} an array of {@link ConformanceRestSecurityCertificateComponent} objects */ ConformanceRestSecurityComponent.prototype.certificate = function() { var i, item, len, ref, results; if (this.json['certificate']) { ref = this.json['certificate']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceRestSecurityCertificateComponent(item)); } return results; } }; return ConformanceRestSecurityComponent; })(BackboneElement); /** Embedded class @class ResourceInteractionComponent @exports ResourceInteractionComponent as ResourceInteractionComponent */ ResourceInteractionComponent = (function(superClass) { extend(ResourceInteractionComponent, superClass); function ResourceInteractionComponent(json) { this.json = json; ResourceInteractionComponent.__super__.constructor.call(this, this.json); } /** Coded identifier of the operation, supported by the system resource. @returns {Array} an array of {@link String} objects */ ResourceInteractionComponent.prototype.code = function() { return this.json['code']; }; /** Guidance specific to the implementation of this operation, such as 'delete is a logical delete' or 'updates are only allowed with version id' or 'creates permitted from pre-authorized certificates only'. @returns {Array} an array of {@link String} objects */ ResourceInteractionComponent.prototype.documentation = function() { return this.json['documentation']; }; return ResourceInteractionComponent; })(BackboneElement); /** Embedded class @class ConformanceRestResourceSearchParamComponent @exports ConformanceRestResourceSearchParamComponent as ConformanceRestResourceSearchParamComponent */ ConformanceRestResourceSearchParamComponent = (function(superClass) { extend(ConformanceRestResourceSearchParamComponent, superClass); function ConformanceRestResourceSearchParamComponent(json) { this.json = json; ConformanceRestResourceSearchParamComponent.__super__.constructor.call(this, this.json); } /** The name of the search parameter used in the interface. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceSearchParamComponent.prototype.name = function() { return this.json['name']; }; /** A formal reference to where this parameter was first defined, so that a client can be confident of the meaning of the search parameter. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceSearchParamComponent.prototype.definition = function() { return this.json['definition']; }; /** The type of value a search parameter refers to, and how the content is interpreted. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceSearchParamComponent.prototype.type = function() { return this.json['type']; }; /** This allows documentation of any distinct behaviors about how the search parameter is used. For example, text matching algorithms. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceSearchParamComponent.prototype.documentation = function() { return this.json['documentation']; }; /** Types of resource (if a resource is referenced). @returns {Array} an array of {@link String} objects */ ConformanceRestResourceSearchParamComponent.prototype.target = function() { return this.json['target']; }; /** Chained names supported. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceSearchParamComponent.prototype.chain = function() { return this.json['chain']; }; return ConformanceRestResourceSearchParamComponent; })(BackboneElement); /** Embedded class @class ConformanceRestResourceComponent @exports ConformanceRestResourceComponent as ConformanceRestResourceComponent */ ConformanceRestResourceComponent = (function(superClass) { extend(ConformanceRestResourceComponent, superClass); function ConformanceRestResourceComponent(json) { this.json = json; ConformanceRestResourceComponent.__super__.constructor.call(this, this.json); } /** A type of resource exposed via the restful interface. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceComponent.prototype.type = function() { return this.json['type']; }; /** A specification of the profile that describes the solution's support for the resource, including any constraints on cardinality, bindings, lengths or other limitations. @returns {Reference} */ ConformanceRestResourceComponent.prototype.profile = function() { if (this.json['profile']) { return new Reference(this.json['profile']); } }; /** Identifies a restful operation supported by the solution. @returns {Array} an array of {@link ResourceInteractionComponent} objects */ ConformanceRestResourceComponent.prototype.interaction = function() { var i, item, len, ref, results; if (this.json['interaction']) { ref = this.json['interaction']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ResourceInteractionComponent(item)); } return results; } }; /** Thi field is set to true to specify that the system does not support (server) or use (client) versioning for this resource type. If this is not set to true, the server must at least correctly track and populate the versionId meta-property on resources. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceComponent.prototype.versioning = function() { return this.json['versioning']; }; /** A flag for whether the server is able to return past versions as part of the vRead operation. @returns {Array} an array of {@link boolean} objects */ ConformanceRestResourceComponent.prototype.readHistory = function() { return this.json['readHistory']; }; /** A flag to indicate that the server allows the client to create new identities on the server. If the update operation is used (client) or allowed (server) to a new location where a resource doesn't already exist. This means that the server allows the client to create new identities on the server. @returns {Array} an array of {@link boolean} objects */ ConformanceRestResourceComponent.prototype.updateCreate = function() { return this.json['updateCreate']; }; /** A list of _include values supported by the server. @returns {Array} an array of {@link String} objects */ ConformanceRestResourceComponent.prototype.searchInclude = function() { return this.json['searchInclude']; }; /** Additional search parameters for implementations to support and/or make use of. @returns {Array} an array of {@link ConformanceRestResourceSearchParamComponent} objects */ ConformanceRestResourceComponent.prototype.searchParam = function() { var i, item, len, ref, results; if (this.json['searchParam']) { ref = this.json['searchParam']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceRestResourceSearchParamComponent(item)); } return results; } }; return ConformanceRestResourceComponent; })(BackboneElement); /** Embedded class @class SystemInteractionComponent @exports SystemInteractionComponent as SystemInteractionComponent */ SystemInteractionComponent = (function(superClass) { extend(SystemInteractionComponent, superClass); function SystemInteractionComponent(json) { this.json = json; SystemInteractionComponent.__super__.constructor.call(this, this.json); } /** A coded identifier of the operation, supported by the system. @returns {Array} an array of {@link String} objects */ SystemInteractionComponent.prototype.code = function() { return this.json['code']; }; /** Guidance specific to the implementation of this operation, such as limitations on the kind of transactions allowed, or information about system wide search is implemented. @returns {Array} an array of {@link String} objects */ SystemInteractionComponent.prototype.documentation = function() { return this.json['documentation']; }; return SystemInteractionComponent; })(BackboneElement); /** Embedded class @class ConformanceRestOperationComponent @exports ConformanceRestOperationComponent as ConformanceRestOperationComponent */ ConformanceRestOperationComponent = (function(superClass) { extend(ConformanceRestOperationComponent, superClass); function ConformanceRestOperationComponent(json) { this.json = json; ConformanceRestOperationComponent.__super__.constructor.call(this, this.json); } /** The name of a query, which is used in the _query parameter when the query is called. @returns {Array} an array of {@link String} objects */ ConformanceRestOperationComponent.prototype.name = function() { return this.json['name']; }; /** Where the formal definition can be found. @returns {Reference} */ ConformanceRestOperationComponent.prototype.definition = function() { if (this.json['definition']) { return new Reference(this.json['definition']); } }; return ConformanceRestOperationComponent; })(BackboneElement); /** Embedded class @class ConformanceRestComponent @exports ConformanceRestComponent as ConformanceRestComponent */ ConformanceRestComponent = (function(superClass) { extend(ConformanceRestComponent, superClass); function ConformanceRestComponent(json) { this.json = json; ConformanceRestComponent.__super__.constructor.call(this, this.json); } /** Identifies whether this portion of the statement is describing ability to initiate or receive restful operations. @returns {Array} an array of {@link String} objects */ ConformanceRestComponent.prototype.mode = function() { return this.json['mode']; }; /** Information about the system's restful capabilities that apply across all applications, such as security. @returns {Array} an array of {@link String} objects */ ConformanceRestComponent.prototype.documentation = function() { return this.json['documentation']; }; /** Information about security of implementation. @returns {ConformanceRestSecurityComponent} */ ConformanceRestComponent.prototype.security = function() { if (this.json['security']) { return new ConformanceRestSecurityComponent(this.json['security']); } }; /** A specification of the restful capabilities of the solution for a specific resource type. @returns {Array} an array of {@link ConformanceRestResourceComponent} objects */ ConformanceRestComponent.prototype.resource = function() { var i, item, len, ref, results; if (this.json['resource']) { ref = this.json['resource']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceRestResourceComponent(item)); } return results; } }; /** A specification of restful operations supported by the system. @returns {Array} an array of {@link SystemInteractionComponent} objects */ ConformanceRestComponent.prototype.interaction = function() { var i, item, len, ref, results; if (this.json['interaction']) { ref = this.json['interaction']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SystemInteractionComponent(item)); } return results; } }; /** Definition of an operation or a named query and with its parameters and their meaning and type. @returns {Array} an array of {@link ConformanceRestOperationComponent} objects */ ConformanceRestComponent.prototype.operation = function() { var i, item, len, ref, results; if (this.json['operation']) { ref = this.json['operation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceRestOperationComponent(item)); } return results; } }; /** A list of profiles that this server implements for accepting documents in the mailbox. If this list is empty, then documents are not accepted. The base specification has the profile identifier "http://hl7.org/fhir/documents/mailbox". Other specifications can declare their own identifier for this purpose. @returns {Array} an array of {@link String} objects */ ConformanceRestComponent.prototype.documentMailbox = function() { return this.json['documentMailbox']; }; return ConformanceRestComponent; })(BackboneElement); /** Embedded class @class ConformanceMessagingEventComponent @exports ConformanceMessagingEventComponent as ConformanceMessagingEventComponent */ ConformanceMessagingEventComponent = (function(superClass) { extend(ConformanceMessagingEventComponent, superClass); function ConformanceMessagingEventComponent(json) { this.json = json; ConformanceMessagingEventComponent.__super__.constructor.call(this, this.json); } /** A coded identifier of a supported messaging event. @returns {Coding} */ ConformanceMessagingEventComponent.prototype.code = function() { if (this.json['code']) { return new Coding(this.json['code']); } }; /** The impact of the content of the message. @returns {Array} an array of {@link String} objects */ ConformanceMessagingEventComponent.prototype.category = function() { return this.json['category']; }; /** The mode of this event declaration - whether application is sender or receiver. @returns {Array} an array of {@link String} objects */ ConformanceMessagingEventComponent.prototype.mode = function() { return this.json['mode']; }; /** A list of the messaging transport protocol(s) identifiers, supported by this endpoint. @returns {Array} an array of {@link Coding} objects */ ConformanceMessagingEventComponent.prototype.protocol = function() { var i, item, len, ref, results; if (this.json['protocol']) { ref = this.json['protocol']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** A resource associated with the event. This is the resource that defines the event. @returns {Array} an array of {@link String} objects */ ConformanceMessagingEventComponent.prototype.focus = function() { return this.json['focus']; }; /** Information about the request for this event. @returns {Reference} */ ConformanceMessagingEventComponent.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Information about the response for this event. @returns {Reference} */ ConformanceMessagingEventComponent.prototype.response = function() { if (this.json['response']) { return new Reference(this.json['response']); } }; /** Guidance on how this event is handled, such as internal system trigger points, business rules, etc. @returns {Array} an array of {@link String} objects */ ConformanceMessagingEventComponent.prototype.documentation = function() { return this.json['documentation']; }; return ConformanceMessagingEventComponent; })(BackboneElement); /** Embedded class @class ConformanceMessagingComponent @exports ConformanceMessagingComponent as ConformanceMessagingComponent */ ConformanceMessagingComponent = (function(superClass) { extend(ConformanceMessagingComponent, superClass); function ConformanceMessagingComponent(json) { this.json = json; ConformanceMessagingComponent.__super__.constructor.call(this, this.json); } /** An address to which messages and/or replies are to be sent. @returns {Array} an array of {@link String} objects */ ConformanceMessagingComponent.prototype.endpoint = function() { return this.json['endpoint']; }; /** Length if the receiver's reliable messaging cache in minutes (if a receiver) or how long the cache length on the receiver should be (if a sender). @returns {Array} an array of {@link Number} objects */ ConformanceMessagingComponent.prototype.reliableCache = function() { return this.json['reliableCache']; }; /** Documentation about the system's messaging capabilities for this endpoint not otherwise documented by the conformance statement. For example, process for becoming an authorized messaging exchange partner. @returns {Array} an array of {@link String} objects */ ConformanceMessagingComponent.prototype.documentation = function() { return this.json['documentation']; }; /** A description of the solution's support for an event at this end point. @returns {Array} an array of {@link ConformanceMessagingEventComponent} objects */ ConformanceMessagingComponent.prototype.event = function() { var i, item, len, ref, results; if (this.json['event']) { ref = this.json['event']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceMessagingEventComponent(item)); } return results; } }; return ConformanceMessagingComponent; })(BackboneElement); /** Embedded class @class ConformanceDocumentComponent @exports ConformanceDocumentComponent as ConformanceDocumentComponent */ ConformanceDocumentComponent = (function(superClass) { extend(ConformanceDocumentComponent, superClass); function ConformanceDocumentComponent(json) { this.json = json; ConformanceDocumentComponent.__super__.constructor.call(this, this.json); } /** Mode of this document declaration - whether application is producer or consumer. @returns {Array} an array of {@link String} objects */ ConformanceDocumentComponent.prototype.mode = function() { return this.json['mode']; }; /** A description of how the application supports or uses the specified document profile. For example, when are documents created, what action is taken with consumed documents, etc. @returns {Array} an array of {@link String} objects */ ConformanceDocumentComponent.prototype.documentation = function() { return this.json['documentation']; }; /** A constraint on a resource used in the document. @returns {Reference} */ ConformanceDocumentComponent.prototype.profile = function() { if (this.json['profile']) { return new Reference(this.json['profile']); } }; return ConformanceDocumentComponent; })(BackboneElement); /** A conformance statement is a set of requirements for a desired implementation or a description of how a target application fulfills those requirements in a particular implementation. @class Conformance @exports Conformance as Conformance */ Conformance = (function(superClass) { extend(Conformance, superClass); function Conformance(json) { this.json = json; Conformance.__super__.constructor.call(this, this.json); } /** The identifier that is used to identify this conformance statement when it is referenced in a specification, model, design or an instance (should be globally unique OID, UUID, or URI). @returns {Array} an array of {@link String} objects */ Conformance.prototype.identifier = function() { return this.json['identifier']; }; /** The identifier that is used to identify this version of the conformance statement when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the profile author manually and the value should be a timestamp. @returns {Array} an array of {@link String} objects */ Conformance.prototype.version = function() { return this.json['version']; }; /** A free text natural language name identifying the conformance statement. @returns {Array} an array of {@link String} objects */ Conformance.prototype.name = function() { return this.json['name']; }; /** Name of Organization publishing this conformance statement. @returns {Array} an array of {@link String} objects */ Conformance.prototype.publisher = function() { return this.json['publisher']; }; /** Contacts for Organization relevant to this conformance statement. The contacts may be a website, email, phone numbers, etc. @returns {Array} an array of {@link ContactPoint} objects */ Conformance.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** A free text natural language description of the conformance statement and its use. Typically, this is used when the profile describes a desired rather than an actual solution, for example as a formal expression of requirements as part of an RFP. @returns {Array} an array of {@link String} objects */ Conformance.prototype.description = function() { return this.json['description']; }; /** The status of this conformance statement. @returns {Array} an array of {@link String} objects */ Conformance.prototype.status = function() { return this.json['status']; }; /** A flag to indicate that this conformance statement is authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. @returns {Array} an array of {@link boolean} objects */ Conformance.prototype.experimental = function() { return this.json['experimental']; }; /** The date (and optionally time) when the conformance statement was published. @returns {Array} an array of {@link Date} objects */ Conformance.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Software that is covered by this conformance statement. It is used when the profile describes the capabilities of a particular software version, independent of an installation. @returns {ConformanceSoftwareComponent} */ Conformance.prototype.software = function() { if (this.json['software']) { return new ConformanceSoftwareComponent(this.json['software']); } }; /** Identifies a specific implementation instance that is described by the conformance statement - i.e. a particular installation, rather than the capabilities of a software program. @returns {ConformanceImplementationComponent} */ Conformance.prototype.implementation = function() { if (this.json['implementation']) { return new ConformanceImplementationComponent(this.json['implementation']); } }; /** The version of the FHIR specification on which this conformance statement is based. @returns {Array} an array of {@link String} objects */ Conformance.prototype.fhirVersion = function() { return this.json['fhirVersion']; }; /** A flag that indicates whether the application accepts unknown elements as part of a resource. @returns {Array} an array of {@link boolean} objects */ Conformance.prototype.acceptUnknown = function() { return this.json['acceptUnknown']; }; /** A list of the formats supported by this implementation. @returns {Array} an array of {@link String} objects */ Conformance.prototype.format = function() { return this.json['format']; }; /** A list of profiles supported by the system. For a server, "supported by the system" means the system hosts/produces a set of resources, conformant to a particular profile, and allows its clients to search using this profile and to find appropriate data. For a client, it means the system will search by this profile and process data according to the guidance implicit in the profile. @returns {Array} an array of {@link Reference} objects */ Conformance.prototype.profile = function() { var i, item, len, ref, results; if (this.json['profile']) { ref = this.json['profile']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** A definition of the restful capabilities of the solution, if any. @returns {Array} an array of {@link ConformanceRestComponent} objects */ Conformance.prototype.rest = function() { var i, item, len, ref, results; if (this.json['rest']) { ref = this.json['rest']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceRestComponent(item)); } return results; } }; /** A description of the messaging capabilities of the solution. @returns {Array} an array of {@link ConformanceMessagingComponent} objects */ Conformance.prototype.messaging = function() { var i, item, len, ref, results; if (this.json['messaging']) { ref = this.json['messaging']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceMessagingComponent(item)); } return results; } }; /** A document definition. @returns {Array} an array of {@link ConformanceDocumentComponent} objects */ Conformance.prototype.document = function() { var i, item, len, ref, results; if (this.json['document']) { ref = this.json['document']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConformanceDocumentComponent(item)); } return results; } }; return Conformance; })(DomainResource); module.exports.Conformance = Conformance; }).call(this); },{"../cql-datatypes":117,"./core":173}],171:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, Contract, ContractSignerComponent, ContractTermComponent, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ContractSignerComponent @exports ContractSignerComponent as ContractSignerComponent */ ContractSignerComponent = (function(superClass) { extend(ContractSignerComponent, superClass); function ContractSignerComponent(json) { this.json = json; ContractSignerComponent.__super__.constructor.call(this, this.json); } /** Party or role who is signing. @returns {Coding} */ ContractSignerComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The DSIG signature contents in Base64. @returns {Array} an array of {@link String} objects */ ContractSignerComponent.prototype.singnature = function() { return this.json['singnature']; }; return ContractSignerComponent; })(BackboneElement); /** Embedded class @class ContractTermComponent @exports ContractTermComponent as ContractTermComponent */ ContractTermComponent = (function(superClass) { extend(ContractTermComponent, superClass); function ContractTermComponent(json) { this.json = json; ContractTermComponent.__super__.constructor.call(this, this.json); } /** Unique Id for this particular term. @returns {Identifier} */ ContractTermComponent.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** The type of the term. @returns {CodeableConcept} */ ContractTermComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The subttype of the term which is appropriate to the term type. @returns {CodeableConcept} */ ContractTermComponent.prototype.subtype = function() { if (this.json['subtype']) { return new CodeableConcept(this.json['subtype']); } }; /** Who or what the contract term is about. @returns {Reference} */ ContractTermComponent.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Human readable form of the term of the contract. @returns {Array} an array of {@link String} objects */ ContractTermComponent.prototype.text = function() { return this.json['text']; }; return ContractTermComponent; })(BackboneElement); /** A formal agreement between parties regarding the conduct of business, exchange of information or other matters. @class Contract @exports Contract as Contract */ Contract = (function(superClass) { extend(Contract, superClass); function Contract(json) { this.json = json; Contract.__super__.constructor.call(this, this.json); } /** Unique Id for this contract. @returns {Array} an array of {@link Identifier} objects */ Contract.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Who and/or what this is about: typically Patient, Organization, property. @returns {Array} an array of {@link Reference} objects */ Contract.prototype.subject = function() { var i, item, len, ref, results; if (this.json['subject']) { ref = this.json['subject']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Type of contract (Privacy-Security, Agreement, Insurance). @returns {CodeableConcept} */ Contract.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** More specific type of contract (Privacy, Disclosure-Authorization, Advanced-Directive, DNR, Authorization-to-Treat). @returns {Array} an array of {@link CodeableConcept} objects */ Contract.prototype.subtype = function() { var i, item, len, ref, results; if (this.json['subtype']) { ref = this.json['subtype']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** When this was issued. @returns {Array} an array of {@link Date} objects */ Contract.prototype.issued = function() { if (this.json['issued']) { return DT.DateTime.parse(this.json['issued']); } }; /** Relevant time/time-period when applicable. @returns {Period} */ Contract.prototype.applies = function() { if (this.json['applies']) { return new Period(this.json['applies']); } }; /** The number of repetitions of a service or product. @returns {Quantity} */ Contract.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** The unit price product. @returns {Money} */ Contract.prototype.unitPrice = function() { if (this.json['unitPrice']) { return new Money(this.json['unitPrice']); } }; /** A real number that represents a multiplier used in determining the overall value of services delivered and/or goods received. The concept of a Factor allows for a discount or surcharge multiplier to be applied to a monetary amount. @returns {Array} an array of {@link Number} objects */ Contract.prototype.factor = function() { return this.json['factor']; }; /** An amount that expresses the weighting (based on difficulty, cost and/or resource intensiveness) associated with the good or service delivered. The concept of Points allows for assignment of point values for services and/or goods, such that a monetary amount can be assigned to each point. @returns {Array} an array of {@link Number} objects */ Contract.prototype.points = function() { return this.json['points']; }; /** The quantity times the unit price for an addtional service or product or charge. For example, the formula: unit Quantity * unit Price (Cost per Point) * factor Number * points = net Amount. Quantity, factor and points are assumed to be 1 if not supplied. @returns {Money} */ Contract.prototype.net = function() { if (this.json['net']) { return new Money(this.json['net']); } }; /** Contract author or responsible party. @returns {Array} an array of {@link Reference} objects */ Contract.prototype.author = function() { var i, item, len, ref, results; if (this.json['author']) { ref = this.json['author']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** First Party to the contract, may be the party who confers or delegates the rights defined in the contract. @returns {Array} an array of {@link Reference} objects */ Contract.prototype.grantor = function() { var i, item, len, ref, results; if (this.json['grantor']) { ref = this.json['grantor']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The Second party to the contract, may be the party who accepts obligations or be that to which rights are delegated. @returns {Array} an array of {@link Reference} objects */ Contract.prototype.grantee = function() { var i, item, len, ref, results; if (this.json['grantee']) { ref = this.json['grantee']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Who witnesses the contract. @returns {Array} an array of {@link Reference} objects */ Contract.prototype.witness = function() { var i, item, len, ref, results; if (this.json['witness']) { ref = this.json['witness']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** First Party to the contract, may be the party who confers or delegates the rights defined in the contract. @returns {Array} an array of {@link Reference} objects */ Contract.prototype.executor = function() { var i, item, len, ref, results; if (this.json['executor']) { ref = this.json['executor']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** First Party to the contract, may be the party who confers or delegates the rights defined in the contract. @returns {Array} an array of {@link Reference} objects */ Contract.prototype.notary = function() { var i, item, len, ref, results; if (this.json['notary']) { ref = this.json['notary']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** List or contract signatures. @returns {Array} an array of {@link ContractSignerComponent} objects */ Contract.prototype.signer = function() { var i, item, len, ref, results; if (this.json['signer']) { ref = this.json['signer']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContractSignerComponent(item)); } return results; } }; /** A contract provision. @returns {Array} an array of {@link ContractTermComponent} objects */ Contract.prototype.term = function() { var i, item, len, ref, results; if (this.json['term']) { ref = this.json['term']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContractTermComponent(item)); } return results; } }; /** Friendly Human readable form (might be a reference to the UI used to capture the contract). @returns {Attachment} */ Contract.prototype.friendly = function() { if (this.json['friendly']) { return new Attachment(this.json['friendly']); } }; /** Legal text in Human readable form. @returns {Attachment} */ Contract.prototype.legal = function() { if (this.json['legal']) { return new Attachment(this.json['legal']); } }; /** Computable Policy rules (e.g. XACML, DKAL, SecPal). @returns {Attachment} */ Contract.prototype.rule = function() { if (this.json['rule']) { return new Attachment(this.json['rule']); } }; return Contract; })(DomainResource); module.exports.Contract = Contract; }).call(this); },{"../cql-datatypes":117,"./core":173}],172:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, Contraindication, ContraindicationMitigationComponent, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ContraindicationMitigationComponent @exports ContraindicationMitigationComponent as ContraindicationMitigationComponent */ ContraindicationMitigationComponent = (function(superClass) { extend(ContraindicationMitigationComponent, superClass); function ContraindicationMitigationComponent(json) { this.json = json; ContraindicationMitigationComponent.__super__.constructor.call(this, this.json); } /** Describes the action that was taken or the observation that was made that reduces/eliminates the risk associated with the identified contraindication. @returns {CodeableConcept} */ ContraindicationMitigationComponent.prototype.action = function() { if (this.json['action']) { return new CodeableConcept(this.json['action']); } }; /** Indicates when the mitigating action was documented. @returns {Array} an array of {@link Date} objects */ ContraindicationMitigationComponent.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Identifies the practitioner who determined the mitigation and takes responsibility for the mitigation step occurring. @returns {Reference} */ ContraindicationMitigationComponent.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; return ContraindicationMitigationComponent; })(BackboneElement); /** Indicates an actual or potential clinical issue with or between one or more active or proposed clinical actions for a patient. E.g. Drug-drug interaction, Ineffective treatment frequency, Procedure-condition conflict, etc. @class Contraindication @exports Contraindication as Contraindication */ Contraindication = (function(superClass) { extend(Contraindication, superClass); function Contraindication(json) { this.json = json; Contraindication.__super__.constructor.call(this, this.json); } /** Indicates the patient whose record the contraindication is associated with. @returns {Reference} */ Contraindication.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** Identifies the general type of issue identified. @returns {CodeableConcept} */ Contraindication.prototype.category = function() { if (this.json['category']) { return new CodeableConcept(this.json['category']); } }; /** Indicates the degree of importance associated with the identified issue based on the potential impact on the patient. @returns {Array} an array of {@link String} objects */ Contraindication.prototype.severity = function() { return this.json['severity']; }; /** Indicates the resource representing the current activity or proposed activity that. @returns {Array} an array of {@link Reference} objects */ Contraindication.prototype.implicated = function() { var i, item, len, ref, results; if (this.json['implicated']) { ref = this.json['implicated']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** A textual explanation of the contraindication. @returns {Array} an array of {@link String} objects */ Contraindication.prototype.detail = function() { return this.json['detail']; }; /** The date or date-time when the contraindication was initially identified. @returns {Array} an array of {@link Date} objects */ Contraindication.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Identifies the provider or software that identified the. @returns {Reference} */ Contraindication.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** Business identifier associated with the contraindication record. @returns {Identifier} */ Contraindication.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** The literature, knowledge-base or similar reference that describes the propensity for the contraindication identified. @returns {Array} an array of {@link String} objects */ Contraindication.prototype.reference = function() { return this.json['reference']; }; /** Indicates an action that has been taken or is committed to to reduce or eliminate the likelihood of the risk identified by the contraindicaiton from manifesting. Can also reflect an observation of known mitigating factors that may reduce/eliminate the need for any action. @returns {Array} an array of {@link ContraindicationMitigationComponent} objects */ Contraindication.prototype.mitigation = function() { var i, item, len, ref, results; if (this.json['mitigation']) { ref = this.json['mitigation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContraindicationMitigationComponent(item)); } return results; } }; return Contraindication; })(DomainResource); module.exports.Contraindication = Contraindication; }).call(this); },{"../cql-datatypes":117,"./core":173}],173:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, Base, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, ElementDefinitionBindingComponent, ElementDefinitionConstraintComponent, ElementDefinitionMappingComponent, ElementDefinitionSlicingComponent, Extension, HumanName, Identifier, Narrative, Parameters, ParametersParameterComponent, Period, Quantity, Range, Ratio, Reference, Resource, ResourceMetaComponent, SampledData, Timing, TimingRepeatComponent, TypeRefComponent, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Base = (function() { function Base(json) { this.json = json; } return Base; })(); module.exports.Base = Base; DT = require('../cql-datatypes'); /** Base definition for all elements in a resource. @class Element @exports Element as Element */ Element = (function(superClass) { extend(Element, superClass); function Element(json) { this.json = json; Element.__super__.constructor.call(this, this.json); } /** unique id for the element within a resource (for internal references). @returns {Array} an array of {@link String} objects */ Element.prototype.id = function() { return this.json['id']; }; /** May be used to represent additional information that is not part of the basic definition of the element. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. @returns {Array} an array of {@link Extension} objects */ Element.prototype.extension = function() { var i, item, len, ref, results; if (this.json['extension']) { ref = this.json['extension']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; return Element; })(Base); module.exports.Element = Element; /** Base definition for all elements that are defined inside a resource - but not those in a data type. @class BackboneElement @exports BackboneElement as BackboneElement */ BackboneElement = (function(superClass) { extend(BackboneElement, superClass); function BackboneElement(json) { this.json = json; BackboneElement.__super__.constructor.call(this, this.json); } /** May be used to represent additional information that is not part of the basic definition of the element, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions. @returns {Array} an array of {@link Extension} objects */ BackboneElement.prototype.modifierExtension = function() { var i, item, len, ref, results; if (this.json['modifierExtension']) { ref = this.json['modifierExtension']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; return BackboneElement; })(Element); module.exports.BackboneElement = BackboneElement; /** Optional Extensions Element - found in all resources. @class Extension @exports Extension as Extension */ Extension = (function(superClass) { extend(Extension, superClass); function Extension(json) { this.json = json; Extension.__super__.constructor.call(this, this.json); } /** Source of the definition for the extension code - a logical name or a URL. @returns {Array} an array of {@link String} objects */ Extension.prototype.url = function() { return this.json['url']; }; /** Value of extension - may be a resource or one of a constrained set of the data types (see Extensibility in the spec for list). @returns {Array} an array of {@link } objects */ Extension.prototype.value = function() { return this.json['value']; }; return Extension; })(Element); module.exports.Extension = Extension; /** A human-readable formatted text, including images. @class Narrative @exports Narrative as Narrative */ Narrative = (function(superClass) { extend(Narrative, superClass); function Narrative(json) { this.json = json; Narrative.__super__.constructor.call(this, this.json); } /** The status of the narrative - whether it's entirely generated (from just the defined data or the extensions too), or whether a human authored it and it may contain additional data. @returns {Array} an array of {@link String} objects */ Narrative.prototype.status = function() { return this.json['status']; }; /** The actual narrative content, a stripped down version of XHTML. @returns {xhtml} */ Narrative.prototype.div = function() { if (this.json['div']) { return new xhtml(this.json['div']); } }; return Narrative; })(Element); module.exports.Narrative = Narrative; /** A time period defined by a start and end date and optionally time. @class Period @exports Period as Period */ Period = (function(superClass) { extend(Period, superClass); function Period(json) { this.json = json; Period.__super__.constructor.call(this, this.json); } /** The start of the period. The boundary is inclusive. @returns {Array} an array of {@link Date} objects */ Period.prototype.start = function() { if (this.json['start']) { return DT.DateTime.parse(this.json['start']); } }; /** The end of the period. If the end of the period is missing, it means that the period is ongoing. @returns {Array} an array of {@link Date} objects */ Period.prototype.end = function() { if (this.json['end']) { return DT.DateTime.parse(this.json['end']); } }; return Period; })(Element); module.exports.Period = Period; /** A reference to a code defined by a terminology system. @class Coding @exports Coding as Coding */ Coding = (function(superClass) { extend(Coding, superClass); function Coding(json) { this.json = json; Coding.__super__.constructor.call(this, this.json); } /** The identification of the code system that defines the meaning of the symbol in the code. @returns {Array} an array of {@link String} objects */ Coding.prototype.system = function() { return this.json['system']; }; /** The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged. @returns {Array} an array of {@link String} objects */ Coding.prototype.version = function() { return this.json['version']; }; /** A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination). @returns {Array} an array of {@link String} objects */ Coding.prototype.code = function() { return this.json['code']; }; /** A representation of the meaning of the code in the system, following the rules of the system. @returns {Array} an array of {@link String} objects */ Coding.prototype.display = function() { return this.json['display']; }; /** Indicates that this code was chosen by a user directly - i.e. off a pick list of available items (codes or displays). @returns {Array} an array of {@link boolean} objects */ Coding.prototype.primary = function() { return this.json['primary']; }; /** The set of possible coded values this coding was chosen from or constrained by. @returns {Reference} */ Coding.prototype.valueSet = function() { if (this.json['valueSet']) { return new Reference(this.json['valueSet']); } }; return Coding; })(Element); module.exports.Coding = Coding; /** A set of ordered Quantities defined by a low and high limit. @class Range @exports Range as Range */ Range = (function(superClass) { extend(Range, superClass); function Range(json) { this.json = json; Range.__super__.constructor.call(this, this.json); } /** The low limit. The boundary is inclusive. @returns {Quantity} */ Range.prototype.low = function() { if (this.json['low']) { return new Quantity(this.json['low']); } }; /** The high limit. The boundary is inclusive. @returns {Quantity} */ Range.prototype.high = function() { if (this.json['high']) { return new Quantity(this.json['high']); } }; return Range; })(Element); module.exports.Range = Range; /** A measured amount (or an amount that can potentially be measured). Note that measured amounts include amounts that are not precisely quantified, including amounts involving arbitrary units and floating currencies. @class Quantity @exports Quantity as Quantity */ Quantity = (function(superClass) { extend(Quantity, superClass); function Quantity(json) { this.json = json; Quantity.__super__.constructor.call(this, this.json); } /** The value of the measured amount. The value includes an implicit precision in the presentation of the value. @returns {Array} an array of {@link Number} objects */ Quantity.prototype.value = function() { return this.json['value']; }; /** How the value should be understood and represented - whether the actual value is greater or less than the stated value due to measurement issues. E.g. if the comparator is "<" , then the real value is < stated value. @returns {Array} an array of {@link String} objects */ Quantity.prototype.comparator = function() { return this.json['comparator']; }; /** A human-readable form of the units. @returns {Array} an array of {@link String} objects */ Quantity.prototype.units = function() { return this.json['units']; }; /** The identification of the system that provides the coded form of the unit. @returns {Array} an array of {@link String} objects */ Quantity.prototype.system = function() { return this.json['system']; }; /** A computer processable form of the units in some unit representation system. @returns {Array} an array of {@link String} objects */ Quantity.prototype.code = function() { return this.json['code']; }; return Quantity; })(Element); module.exports.Quantity = Quantity; /** For referring to data content defined in other formats. @class Attachment @exports Attachment as Attachment */ Attachment = (function(superClass) { extend(Attachment, superClass); function Attachment(json) { this.json = json; Attachment.__super__.constructor.call(this, this.json); } /** Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate. @returns {Array} an array of {@link String} objects */ Attachment.prototype.contentType = function() { return this.json['contentType']; }; /** The human language of the content. The value can be any valid value according to BCP 47. @returns {Array} an array of {@link String} objects */ Attachment.prototype.language = function() { return this.json['language']; }; /** The actual data of the attachment - a sequence of bytes. In XML, represented using base64. @returns {Array} an array of {@link } objects */ Attachment.prototype.data = function() { return this.json['data']; }; /** An alternative location where the data can be accessed. @returns {Array} an array of {@link String} objects */ Attachment.prototype.url = function() { return this.json['url']; }; /** The number of bytes of data that make up this attachment. @returns {Array} an array of {@link Number} objects */ Attachment.prototype.size = function() { return this.json['size']; }; /** The calculated hash of the data using SHA-1. Represented using base64. @returns {Array} an array of {@link } objects */ Attachment.prototype.hash = function() { return this.json['hash']; }; /** A label or set of text to display in place of the data. @returns {Array} an array of {@link String} objects */ Attachment.prototype.title = function() { return this.json['title']; }; return Attachment; })(Element); module.exports.Attachment = Attachment; /** A relationship of two Quantity values - expressed as a numerator and a denominator. @class Ratio @exports Ratio as Ratio */ Ratio = (function(superClass) { extend(Ratio, superClass); function Ratio(json) { this.json = json; Ratio.__super__.constructor.call(this, this.json); } /** The value of the numerator. @returns {Quantity} */ Ratio.prototype.numerator = function() { if (this.json['numerator']) { return new Quantity(this.json['numerator']); } }; /** The value of the denominator. @returns {Quantity} */ Ratio.prototype.denominator = function() { if (this.json['denominator']) { return new Quantity(this.json['denominator']); } }; return Ratio; })(Element); module.exports.Ratio = Ratio; /** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. @class SampledData @exports SampledData as SampledData */ SampledData = (function(superClass) { extend(SampledData, superClass); function SampledData(json) { this.json = json; SampledData.__super__.constructor.call(this, this.json); } /** The base quantity that a measured value of zero represents. In addition, this provides the units of the entire measurement series. @returns {Quantity} */ SampledData.prototype.origin = function() { if (this.json['origin']) { return new Quantity(this.json['origin']); } }; /** The length of time between sampling times, measured in milliseconds. @returns {Array} an array of {@link Number} objects */ SampledData.prototype.period = function() { return this.json['period']; }; /** A correction factor that is applied to the sampled data points before they are added to the origin. @returns {Array} an array of {@link Number} objects */ SampledData.prototype.factor = function() { return this.json['factor']; }; /** The lower limit of detection of the measured points. This is needed if any of the data points have the value "L" (lower than detection limit). @returns {Array} an array of {@link Number} objects */ SampledData.prototype.lowerLimit = function() { return this.json['lowerLimit']; }; /** The upper limit of detection of the measured points. This is needed if any of the data points have the value "U" (higher than detection limit). @returns {Array} an array of {@link Number} objects */ SampledData.prototype.upperLimit = function() { return this.json['upperLimit']; }; /** The number of sample points at each time point. If this value is greater than one, then the dimensions will be interlaced - all the sample points for a point in time will be recorded at once. @returns {Array} an array of {@link Number} objects */ SampledData.prototype.dimensions = function() { return this.json['dimensions']; }; /** A series of data points which are decimal values separated by a single space (character u20). The special values "E" (error), "L" (below detection limit) and "U" (above detection limit) can also be used in place of a decimal value. @returns {Array} an array of {@link String} objects */ SampledData.prototype.data = function() { return this.json['data']; }; return SampledData; })(Element); module.exports.SampledData = SampledData; /** A reference from one resource to another. @class Reference @exports Reference as Reference */ Reference = (function(superClass) { extend(Reference, superClass); function Reference(json) { this.json = json; Reference.__super__.constructor.call(this, this.json); } /** A reference to a location at which the other resource is found. The reference may a relative reference, in which case it is relative to the service base URL, or an absolute URL that resolves to the location where the resource is found. The reference may be version specific or not. If the reference is not to a FHIR RESTful server, then it should be assumed to be version specific. Internal fragment references (start with '#') refer to contained resources. @returns {Array} an array of {@link String} objects */ Reference.prototype.reference = function() { return this.json['reference']; }; /** Plain text narrative that identifies the resource in addition to the resource reference. @returns {Array} an array of {@link String} objects */ Reference.prototype.display = function() { return this.json['display']; }; return Reference; })(Element); module.exports.Reference = Reference; /** A concept that may be defined by a formal reference to a terminology or ontology or may be provided by text. @class CodeableConcept @exports CodeableConcept as CodeableConcept */ CodeableConcept = (function(superClass) { extend(CodeableConcept, superClass); function CodeableConcept(json) { this.json = json; CodeableConcept.__super__.constructor.call(this, this.json); } /** A reference to a code defined by a terminology system. @returns {Array} an array of {@link Coding} objects */ CodeableConcept.prototype.coding = function() { var i, item, len, ref, results; if (this.json['coding']) { ref = this.json['coding']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user. @returns {Array} an array of {@link String} objects */ CodeableConcept.prototype.text = function() { return this.json['text']; }; return CodeableConcept; })(Element); module.exports.CodeableConcept = CodeableConcept; /** A technical identifier - identifies some entity uniquely and unambiguously. @class Identifier @exports Identifier as Identifier */ Identifier = (function(superClass) { extend(Identifier, superClass); function Identifier(json) { this.json = json; Identifier.__super__.constructor.call(this, this.json); } /** The purpose of this identifier. @returns {Array} an array of {@link String} objects */ Identifier.prototype.use = function() { return this.json['use']; }; /** A text string for the identifier that can be displayed to a human so they can recognize the identifier. @returns {Array} an array of {@link String} objects */ Identifier.prototype.label = function() { return this.json['label']; }; /** Establishes the namespace in which set of possible id values is unique. @returns {Array} an array of {@link String} objects */ Identifier.prototype.system = function() { return this.json['system']; }; /** The portion of the identifier typically displayed to the user and which is unique within the context of the system. @returns {Array} an array of {@link String} objects */ Identifier.prototype.value = function() { return this.json['value']; }; /** Time period during which identifier is/was valid for use. @returns {Period} */ Identifier.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** Organization that issued/manages the identifier. @returns {Reference} */ Identifier.prototype.assigner = function() { if (this.json['assigner']) { return new Reference(this.json['assigner']); } }; return Identifier; })(Element); module.exports.Identifier = Identifier; /** Embedded class @class ElementDefinitionSlicingComponent @exports ElementDefinitionSlicingComponent as ElementDefinitionSlicingComponent */ ElementDefinitionSlicingComponent = (function(superClass) { extend(ElementDefinitionSlicingComponent, superClass); function ElementDefinitionSlicingComponent(json) { this.json = json; ElementDefinitionSlicingComponent.__super__.constructor.call(this, this.json); } /** Designates which child elements are used to discriminate between the slices when processing an instance. If one or more discriminators are provided, the value of the child elements in the instance data SHALL completely distinguish which slice the element in the resource matches based on the allowed values for those elements in each of the slices. @returns {Array} an array of {@link String} objects */ ElementDefinitionSlicingComponent.prototype.discriminator = function() { return this.json['discriminator']; }; /** A humane readable text description of how the slicing works. If there is no discriminator, this is required to be present to provide whatever information is possible about how the slices can be differentiated. @returns {Array} an array of {@link String} objects */ ElementDefinitionSlicingComponent.prototype.description = function() { return this.json['description']; }; /** If the matching elements have to occur in the same order as defined in the profile. @returns {Array} an array of {@link boolean} objects */ ElementDefinitionSlicingComponent.prototype.ordered = function() { return this.json['ordered']; }; /** Whether additional slices are allowed or not. When the slices are ordered, profile authors can also say that additional slices are only allowed at the end. @returns {Array} an array of {@link String} objects */ ElementDefinitionSlicingComponent.prototype.rules = function() { return this.json['rules']; }; return ElementDefinitionSlicingComponent; })(Element); /** Embedded class @class TypeRefComponent @exports TypeRefComponent as TypeRefComponent */ TypeRefComponent = (function(superClass) { extend(TypeRefComponent, superClass); function TypeRefComponent(json) { this.json = json; TypeRefComponent.__super__.constructor.call(this, this.json); } /** Name of Data type or Resource that is a(or the) type used for this element. @returns {Array} an array of {@link String} objects */ TypeRefComponent.prototype.code = function() { return this.json['code']; }; /** Identifies a profile structure that SHALL hold for resources or datatypes referenced as the type of this element. Can be a local reference - to another structure in this profile, or a reference to a structure in another profile. @returns {Array} an array of {@link String} objects */ TypeRefComponent.prototype.profile = function() { return this.json['profile']; }; /** If the type is a reference to another resource, how the resource is or can be aggreated - is it a contained resource, or a reference, and if the context is a bundle, is it included in the bundle. @returns {Array} an array of {@link String} objects */ TypeRefComponent.prototype.aggregation = function() { return this.json['aggregation']; }; return TypeRefComponent; })(Element); /** Embedded class @class ElementDefinitionConstraintComponent @exports ElementDefinitionConstraintComponent as ElementDefinitionConstraintComponent */ ElementDefinitionConstraintComponent = (function(superClass) { extend(ElementDefinitionConstraintComponent, superClass); function ElementDefinitionConstraintComponent(json) { this.json = json; ElementDefinitionConstraintComponent.__super__.constructor.call(this, this.json); } /** Allows identification of which elements have their cardinalities impacted by the constraint. Will not be referenced for constraints that do not affect cardinality. @returns {Array} an array of {@link String} objects */ ElementDefinitionConstraintComponent.prototype.key = function() { return this.json['key']; }; /** Used to label the constraint in OCL or in short displays incapable of displaying the full human description. @returns {Array} an array of {@link String} objects */ ElementDefinitionConstraintComponent.prototype.name = function() { return this.json['name']; }; /** Identifies the impact constraint violation has on the conformance of the instance. @returns {Array} an array of {@link String} objects */ ElementDefinitionConstraintComponent.prototype.severity = function() { return this.json['severity']; }; /** Text that can be used to describe the constraint in messages identifying that the constraint has been violated. @returns {Array} an array of {@link String} objects */ ElementDefinitionConstraintComponent.prototype.human = function() { return this.json['human']; }; /** An XPath expression of constraint that can be executed to see if this constraint is met. @returns {Array} an array of {@link String} objects */ ElementDefinitionConstraintComponent.prototype.xpath = function() { return this.json['xpath']; }; return ElementDefinitionConstraintComponent; })(Element); /** Embedded class @class ElementDefinitionBindingComponent @exports ElementDefinitionBindingComponent as ElementDefinitionBindingComponent */ ElementDefinitionBindingComponent = (function(superClass) { extend(ElementDefinitionBindingComponent, superClass); function ElementDefinitionBindingComponent(json) { this.json = json; ElementDefinitionBindingComponent.__super__.constructor.call(this, this.json); } /** A descriptive name for this - can be useful for generating implementation artifacts. @returns {Array} an array of {@link String} objects */ ElementDefinitionBindingComponent.prototype.name = function() { return this.json['name']; }; /** If true, then conformant systems may use additional codes or (where the data type permits) text alone to convey concepts not covered by the set of codes identified in the binding. If false, then conformant systems are constrained to the provided codes alone. @returns {Array} an array of {@link boolean} objects */ ElementDefinitionBindingComponent.prototype.isExtensible = function() { return this.json['isExtensible']; }; /** Indicates the degree of conformance expectations associated with this binding. @returns {Array} an array of {@link String} objects */ ElementDefinitionBindingComponent.prototype.conformance = function() { return this.json['conformance']; }; /** Describes the intended use of this particular set of codes. @returns {Array} an array of {@link String} objects */ ElementDefinitionBindingComponent.prototype.description = function() { return this.json['description']; }; /** Points to the value set or external definition that identifies the set of codes to be used. @returns {Array} an array of {@link String} objects */ ElementDefinitionBindingComponent.prototype.referenceUri = function() { return this.json['referenceUri']; }; /** Points to the value set or external definition that identifies the set of codes to be used. @returns {Reference} */ ElementDefinitionBindingComponent.prototype.referenceReference = function() { if (this.json['referenceReference']) { return new Reference(this.json['referenceReference']); } }; return ElementDefinitionBindingComponent; })(Element); /** Embedded class @class ElementDefinitionMappingComponent @exports ElementDefinitionMappingComponent as ElementDefinitionMappingComponent */ ElementDefinitionMappingComponent = (function(superClass) { extend(ElementDefinitionMappingComponent, superClass); function ElementDefinitionMappingComponent(json) { this.json = json; ElementDefinitionMappingComponent.__super__.constructor.call(this, this.json); } /** An internal reference to the definition of a mapping. @returns {Array} an array of {@link String} objects */ ElementDefinitionMappingComponent.prototype.identity = function() { return this.json['identity']; }; /** Expresses what part of the target specification corresponds to this element. @returns {Array} an array of {@link String} objects */ ElementDefinitionMappingComponent.prototype.map = function() { return this.json['map']; }; return ElementDefinitionMappingComponent; })(Element); /** Captures constraints on each element within the resource, profile, or extension. @class ElementDefinition @exports ElementDefinition as ElementDefinition */ ElementDefinition = (function(superClass) { extend(ElementDefinition, superClass); function ElementDefinition(json) { this.json = json; ElementDefinition.__super__.constructor.call(this, this.json); } /** The path identifies the element and is expressed as a "."-separated list of ancestor elements, beginning with the name of the resource or extension. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.path = function() { return this.json['path']; }; /** Codes that define how this element is represented in instances, when the deviation varies from the normal case. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.representation = function() { return this.json['representation']; }; /** The name of this element definition (to refer to it from other element definitions using ElementDefinition.nameReference). This is a unique name referring to a specific set of constraints applied to this element. One use of this is to provide a name to different slices of the same element. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.name = function() { return this.json['name']; }; /** Indicates that the element is sliced into a set of alternative definitions (there are multiple definitions on a single element in the base resource). The set of slices is any elements that come after this in the element sequence that have the same path, until a shorter path occurs (the shorter path terminates the set). @returns {ElementDefinitionSlicingComponent} */ ElementDefinition.prototype.slicing = function() { if (this.json['slicing']) { return new ElementDefinitionSlicingComponent(this.json['slicing']); } }; /** A concise definition that is shown in the generated XML format that summarizes profiles (used throughout the specification). @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.short = function() { return this.json['short']; }; /** The definition SHALL be consistent with the base definition, but convey the meaning of the element in the particular context of use of the resource. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.formal = function() { return this.json['formal']; }; /** Comments about the use of the element, including notes about how to use the data properly, exceptions to proper use, etc. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.comments = function() { return this.json['comments']; }; /** Explains why this element is needed and why it's been constrained as it has. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.requirements = function() { return this.json['requirements']; }; /** Identifies additional names by which this element might also be known. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.synonym = function() { return this.json['synonym']; }; /** The minimum number of times this element SHALL appear in the instance. @returns {Array} an array of {@link Number} objects */ ElementDefinition.prototype.min = function() { return this.json['min']; }; /** The maximum number of times this element is permitted to appear in the instance. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.max = function() { return this.json['max']; }; /** The data type or resource that the value of this element is permitted to be. @returns {Array} an array of {@link TypeRefComponent} objects */ ElementDefinition.prototype.type = function() { var i, item, len, ref, results; if (this.json['type']) { ref = this.json['type']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new TypeRefComponent(item)); } return results; } }; /** Identifies the name of a slice defined elsewhere in the profile whose constraints should be applied to the current element. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.nameReference = function() { return this.json['nameReference']; }; /** The value that should be used if there is no value stated in the instance. @returns {Array} an array of {@link } objects */ ElementDefinition.prototype.defaultValue = function() { return this.json['defaultValue']; }; /** The Implicit meaning that is to be understood when this element is missing. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.meaningWhenMissing = function() { return this.json['meaningWhenMissing']; }; /** Specifies a value that SHALL be exactly the value for this element in the instance. For purposes of comparison, non-signficant whitespace is ignored, and all values must be an exact match (case and accent sensitive). Missing elements/attributes must also be missing. @returns {Array} an array of {@link } objects */ ElementDefinition.prototype.fixed = function() { return this.json['fixed']; }; /** Specifies a value that the value in the instance SHALL follow - that is, any value in the pattern must be found in the instance. Other additional values may be found too. This is effectively constraint by example. The values of elements present in the pattern must match exactly (case-senstive, accent-sensitive, etc.). @returns {Array} an array of {@link } objects */ ElementDefinition.prototype.pattern = function() { return this.json['pattern']; }; /** An example value for this element. @returns {Array} an array of {@link } objects */ ElementDefinition.prototype.example = function() { return this.json['example']; }; /** Indicates the maximum length in characters that is permitted to be present in conformant instances and which is expected to be supported by conformant consumers that support the element. @returns {Array} an array of {@link Number} objects */ ElementDefinition.prototype.maxLength = function() { return this.json['maxLength']; }; /** A reference to an invariant that may make additional statements about the cardinality or value in the instance. @returns {Array} an array of {@link String} objects */ ElementDefinition.prototype.condition = function() { return this.json['condition']; }; /** Formal constraints such as co-occurrence and other constraints that can be computationally evaluated within the context of the instance. @returns {Array} an array of {@link ElementDefinitionConstraintComponent} objects */ ElementDefinition.prototype.constraint = function() { var i, item, len, ref, results; if (this.json['constraint']) { ref = this.json['constraint']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ElementDefinitionConstraintComponent(item)); } return results; } }; /** If true, conformant resource authors SHALL be capable of providing a value for the element and resource consumers SHALL be capable of extracting and doing something useful with the data element. If false, the element may be ignored and not supported. @returns {Array} an array of {@link boolean} objects */ ElementDefinition.prototype.mustSupport = function() { return this.json['mustSupport']; }; /** If true, the value of this element affects the interpretation of the element or resource that contains it, and the value of the element cannot be ignored. Typically, this is used for status, negation and qualification codes. The effect of this is that the element cannot be ignored by systems: they SHALL either recognize the element and process it, and/or a pre-determination has been made that it is not relevant to their particular system. @returns {Array} an array of {@link boolean} objects */ ElementDefinition.prototype.isModifier = function() { return this.json['isModifier']; }; /** Whether the element should be included if a client requests a search with the parameter _summary=true. @returns {Array} an array of {@link boolean} objects */ ElementDefinition.prototype.isSummary = function() { return this.json['isSummary']; }; /** Binds to a value set if this element is coded (code, Coding, CodeableConcept). @returns {ElementDefinitionBindingComponent} */ ElementDefinition.prototype.binding = function() { if (this.json['binding']) { return new ElementDefinitionBindingComponent(this.json['binding']); } }; /** Identifies a concept from an external specification that roughly corresponds to this element. @returns {Array} an array of {@link ElementDefinitionMappingComponent} objects */ ElementDefinition.prototype.mapping = function() { var i, item, len, ref, results; if (this.json['mapping']) { ref = this.json['mapping']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ElementDefinitionMappingComponent(item)); } return results; } }; return ElementDefinition; })(Element); module.exports.ElementDefinition = ElementDefinition; /** Embedded class @class TimingRepeatComponent @exports TimingRepeatComponent as TimingRepeatComponent */ TimingRepeatComponent = (function(superClass) { extend(TimingRepeatComponent, superClass); function TimingRepeatComponent(json) { this.json = json; TimingRepeatComponent.__super__.constructor.call(this, this.json); } /** Indicates how often the event should occur. @returns {Array} an array of {@link Number} objects */ TimingRepeatComponent.prototype.frequency = function() { return this.json['frequency']; }; /** Identifies the occurrence of daily life that determines timing. @returns {Array} an array of {@link String} objects */ TimingRepeatComponent.prototype.when = function() { return this.json['when']; }; /** How long each repetition should last. @returns {Array} an array of {@link Number} objects */ TimingRepeatComponent.prototype.duration = function() { return this.json['duration']; }; /** The units of time for the duration. @returns {Array} an array of {@link String} objects */ TimingRepeatComponent.prototype.units = function() { return this.json['units']; }; /** A total count of the desired number of repetitions. @returns {Array} an array of {@link Number} objects */ TimingRepeatComponent.prototype.count = function() { return this.json['count']; }; /** When to stop repeating the timing schedule. @returns {Array} an array of {@link Date} objects */ TimingRepeatComponent.prototype.end = function() { if (this.json['end']) { return DT.DateTime.parse(this.json['end']); } }; return TimingRepeatComponent; })(Element); /** Specifies an event that may occur multiple times. Timing schedules are used for to record when things are expected or requested to occur. @class Timing @exports Timing as Timing */ Timing = (function(superClass) { extend(Timing, superClass); function Timing(json) { this.json = json; Timing.__super__.constructor.call(this, this.json); } /** Identifies specific time periods when the event should occur. @returns {Array} an array of {@link Period} objects */ Timing.prototype.event = function() { var i, item, len, ref, results; if (this.json['event']) { ref = this.json['event']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Period(item)); } return results; } }; /** Identifies a repeating pattern to the intended time periods. @returns {TimingRepeatComponent} */ Timing.prototype.repeat = function() { if (this.json['repeat']) { return new TimingRepeatComponent(this.json['repeat']); } }; return Timing; })(Element); module.exports.Timing = Timing; /** There is a variety of postal address formats defined around the world. This format defines a superset that is the basis for all addresses around the world. @class Address @exports Address as Address */ Address = (function(superClass) { extend(Address, superClass); function Address(json) { this.json = json; Address.__super__.constructor.call(this, this.json); } /** The purpose of this address. @returns {Array} an array of {@link String} objects */ Address.prototype.use = function() { return this.json['use']; }; /** A full text representation of the address. @returns {Array} an array of {@link String} objects */ Address.prototype.text = function() { return this.json['text']; }; /** This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information. @returns {Array} an array of {@link String} objects */ Address.prototype.line = function() { return this.json['line']; }; /** The name of the city, town, village or other community or delivery center. @returns {Array} an array of {@link String} objects */ Address.prototype.city = function() { return this.json['city']; }; /** Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes). @returns {Array} an array of {@link String} objects */ Address.prototype.state = function() { return this.json['state']; }; /** A postal code designating a region defined by the postal service. @returns {Array} an array of {@link String} objects */ Address.prototype.postalCode = function() { return this.json['postalCode']; }; /** Country - a nation as commonly understood or generally accepted. @returns {Array} an array of {@link String} objects */ Address.prototype.country = function() { return this.json['country']; }; /** Time period when address was/is in use. @returns {Period} */ Address.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return Address; })(Element); module.exports.Address = Address; /** A human's name with the ability to identify parts and usage. @class HumanName @exports HumanName as HumanName */ HumanName = (function(superClass) { extend(HumanName, superClass); function HumanName(json) { this.json = json; HumanName.__super__.constructor.call(this, this.json); } /** Identifies the purpose for this name. @returns {Array} an array of {@link String} objects */ HumanName.prototype.use = function() { return this.json['use']; }; /** A full text representation of the name. @returns {Array} an array of {@link String} objects */ HumanName.prototype.text = function() { return this.json['text']; }; /** The part of a name that links to the genealogy. In some cultures (e.g. Eritrea) the family name of a son is the first name of his father. @returns {Array} an array of {@link String} objects */ HumanName.prototype.family = function() { return this.json['family']; }; /** Given name. @returns {Array} an array of {@link String} objects */ HumanName.prototype.given = function() { return this.json['given']; }; /** Part of the name that is acquired as a title due to academic, legal, employment or nobility status, etc. and that appears at the start of the name. @returns {Array} an array of {@link String} objects */ HumanName.prototype.prefix = function() { return this.json['prefix']; }; /** Part of the name that is acquired as a title due to academic, legal, employment or nobility status, etc. and that appears at the end of the name. @returns {Array} an array of {@link String} objects */ HumanName.prototype.suffix = function() { return this.json['suffix']; }; /** Indicates the period of time when this name was valid for the named person. @returns {Period} */ HumanName.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return HumanName; })(Element); module.exports.HumanName = HumanName; /** Details for All kinds of technology mediated contact points for a person or organization, including telephone, email, etc. @class ContactPoint @exports ContactPoint as ContactPoint */ ContactPoint = (function(superClass) { extend(ContactPoint, superClass); function ContactPoint(json) { this.json = json; ContactPoint.__super__.constructor.call(this, this.json); } /** Telecommunications form for contact point - what communications system is required to make use of the contact. @returns {Array} an array of {@link String} objects */ ContactPoint.prototype.system = function() { return this.json['system']; }; /** The actual contact point details, in a form that is meaningful to the designated communication system (i.e. phone number or email address). @returns {Array} an array of {@link String} objects */ ContactPoint.prototype.value = function() { return this.json['value']; }; /** Identifies the purpose for the contact point. @returns {Array} an array of {@link String} objects */ ContactPoint.prototype.use = function() { return this.json['use']; }; /** Time period when the contact point was/is in use. @returns {Period} */ ContactPoint.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return ContactPoint; })(Element); module.exports.ContactPoint = ContactPoint; /** Embedded class @class ResourceMetaComponent @exports ResourceMetaComponent as ResourceMetaComponent */ ResourceMetaComponent = (function(superClass) { extend(ResourceMetaComponent, superClass); function ResourceMetaComponent(json) { this.json = json; ResourceMetaComponent.__super__.constructor.call(this, this.json); } /** The version specific identifier, as it appears in the version portion of the url. This values changes when the resource is created, updated, or deleted. @returns {Array} an array of {@link String} objects */ ResourceMetaComponent.prototype.versionId = function() { return this.json['versionId']; }; /** When the resource last changed - e.g. when the version changed. @returns {Array} an array of {@link Date} objects */ ResourceMetaComponent.prototype.lastUpdated = function() { if (this.json['lastUpdated']) { return DT.DateTime.parse(this.json['lastUpdated']); } }; /** A list of profiles that this resource claims to conform to. The URL is a reference to Profile.url. @returns {Array} an array of {@link String} objects */ ResourceMetaComponent.prototype.profile = function() { return this.json['profile']; }; /** Security labels applied to this resource. These tags connect specific resources to the overall security policy and infrastructure. @returns {Array} an array of {@link Coding} objects */ ResourceMetaComponent.prototype.security = function() { var i, item, len, ref, results; if (this.json['security']) { ref = this.json['security']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Tags applied to this resource. Tags are intended to to be used to identify and relate resources to process and workflow, and applications are not required to consider the tags when interpreting the meaning of a resource. @returns {Array} an array of {@link Coding} objects */ ResourceMetaComponent.prototype.tag = function() { var i, item, len, ref, results; if (this.json['tag']) { ref = this.json['tag']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; return ResourceMetaComponent; })(BackboneElement); /** Base Resource for everything. @class Resource @exports Resource as Resource */ Resource = (function(superClass) { extend(Resource, superClass); function Resource(json) { this.json = json; Resource.__super__.constructor.call(this, this.json); } /** The logical id of the resource, as used in the url for the resoure. Once assigned, this value never changes. @returns {Array} an array of {@link String} objects */ Resource.prototype.id = function() { return this.json['id']; }; /** The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content may not always be associated with version changes to the resource. @returns {ResourceMetaComponent} */ Resource.prototype.meta = function() { if (this.json['meta']) { return new ResourceMetaComponent(this.json['meta']); } }; /** A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. @returns {Array} an array of {@link String} objects */ Resource.prototype.implicitRules = function() { return this.json['implicitRules']; }; /** The base language in which the resource is written. @returns {Array} an array of {@link String} objects */ Resource.prototype.language = function() { return this.json['language']; }; return Resource; })(Base); module.exports.Resource = Resource; /** @class DomainResource @exports DomainResource as DomainResource */ DomainResource = (function(superClass) { extend(DomainResource, superClass); function DomainResource(json) { this.json = json; DomainResource.__super__.constructor.call(this, this.json); } /** A human-readable narrative that contains a summary of the resource, and may be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it "clinically safe" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety. @returns {Narrative} */ DomainResource.prototype.text = function() { if (this.json['text']) { return new Narrative(this.json['text']); } }; /** These resources do not have an independent existence apart from the resource that contains them - they cannot be identified independently, and nor can they have their own independent transaction scope. @returns {Array} an array of {@link Resource} objects */ DomainResource.prototype.contained = function() { var i, item, len, ref, req, results, typeName; if (this.json['contained']) { ref = this.json['contained']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; typeName = this.json['contained'].resourceType; req = require('./' + typeName.toLowerCase())[typeName]; results.push(new req(item)); } return results; } }; /** May be used to represent additional information that is not part of the basic definition of the resource. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. @returns {Array} an array of {@link Extension} objects */ DomainResource.prototype.extension = function() { var i, item, len, ref, results; if (this.json['extension']) { ref = this.json['extension']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; /** May be used to represent additional information that is not part of the basic definition of the resource, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions. @returns {Array} an array of {@link Extension} objects */ DomainResource.prototype.modifierExtension = function() { var i, item, len, ref, results; if (this.json['modifierExtension']) { ref = this.json['modifierExtension']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; return DomainResource; })(Resource); module.exports.DomainResource = DomainResource; /** Embedded class @class ParametersParameterComponent @exports ParametersParameterComponent as ParametersParameterComponent */ ParametersParameterComponent = (function(superClass) { extend(ParametersParameterComponent, superClass); function ParametersParameterComponent(json) { this.json = json; ParametersParameterComponent.__super__.constructor.call(this, this.json); } /** The name of the parameter (reference to the operation definition). @returns {Array} an array of {@link String} objects */ ParametersParameterComponent.prototype.name = function() { return this.json['name']; }; /** If the parameter is a data type. @returns {Array} an array of {@link } objects */ ParametersParameterComponent.prototype.value = function() { return this.json['value']; }; /** If the parameter is a whole resource. @returns {Resource} */ ParametersParameterComponent.prototype.resource = function() { var req, typeName; if (this.json['resource']) { typeName = this.json['resource'].resourceType; req = require('./' + typeName.toLowerCase())[typeName]; return new req(this.json['resource']); } }; return ParametersParameterComponent; })(BackboneElement); /** This special resource type is used to represent [operation](operations.html] request and response. It has no other use, and there is no RESTful end=point associated with it. @class Parameters @exports Parameters as Parameters */ Parameters = (function(superClass) { extend(Parameters, superClass); function Parameters(json) { this.json = json; Parameters.__super__.constructor.call(this, this.json); } /** A parameter passed to or received from the operation. @returns {Array} an array of {@link ParametersParameterComponent} objects */ Parameters.prototype.parameter = function() { var i, item, len, ref, results; if (this.json['parameter']) { ref = this.json['parameter']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ParametersParameterComponent(item)); } return results; } }; return Parameters; })(Resource); module.exports.Parameters = Parameters; }).call(this); },{"../cql-datatypes":117}],174:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, Coverage, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Financial instrument which may be used to pay for or reimburse for health care products and services. @class Coverage @exports Coverage as Coverage */ Coverage = (function(superClass) { extend(Coverage, superClass); function Coverage(json) { this.json = json; Coverage.__super__.constructor.call(this, this.json); } /** The program or plan underwriter or payor. @returns {Reference} */ Coverage.prototype.issuer = function() { if (this.json['issuer']) { return new Reference(this.json['issuer']); } }; /** Time period during which the coverage is in force. A missing start date indicates the start date isn't known, a missing end date means the coverage is continuing to be in force. @returns {Period} */ Coverage.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** The type of coverage: social program, medical plan, accident coverage (workers compensation, auto), group health. @returns {Coding} */ Coverage.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The main (and possibly only) identifier for the coverage - often referred to as a Subscriber Id, Certificate number or Personal Health Number or Case ID. @returns {Array} an array of {@link Identifier} objects */ Coverage.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Identifies a style or collective of coverage issues by the underwriter, for example may be used to identify a class of coverage or employer group. May also be referred to as a Policy or Group ID. @returns {Array} an array of {@link String} objects */ Coverage.prototype.group = function() { return this.json['group']; }; /** Identifies a style or collective of coverage issues by the underwriter, for example may be used to identify a class of coverage or employer group. May also be referred to as a Policy or Group ID. @returns {Array} an array of {@link String} objects */ Coverage.prototype.plan = function() { return this.json['plan']; }; /** Identifies a sub-style or sub-collective of coverage issues by the underwriter, for example may be used to identify a specific employer group within a class of employers. May be referred to as a Section or Division ID. @returns {Array} an array of {@link String} objects */ Coverage.prototype.subplan = function() { return this.json['subplan']; }; /** A unique identifier for a dependent under the coverage. @returns {Array} an array of {@link Number} objects */ Coverage.prototype.dependent = function() { return this.json['dependent']; }; /** An optional counter for a particular instance of the identified coverage which increments upon each renewal. @returns {Array} an array of {@link Number} objects */ Coverage.prototype.sequence = function() { return this.json['sequence']; }; /** The party who 'owns' the insurance contractual relationship to the policy or to whom the benefit of the policy is due. @returns {Reference} */ Coverage.prototype.subscriber = function() { if (this.json['subscriber']) { return new Reference(this.json['subscriber']); } }; /** The identifier for a community of providers. @returns {Identifier} */ Coverage.prototype.network = function() { if (this.json['network']) { return new Identifier(this.json['network']); } }; /** The policy(s) which constitute this insurance coverage. @returns {Array} an array of {@link Reference} objects */ Coverage.prototype.contract = function() { var i, item, len, ref, results; if (this.json['contract']) { ref = this.json['contract']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return Coverage; })(DomainResource); module.exports.Coverage = Coverage; }).call(this); },{"../cql-datatypes":117,"./core":173}],175:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DataElement, DataElementBindingComponent, DataElementMappingComponent, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class DataElementBindingComponent @exports DataElementBindingComponent as DataElementBindingComponent */ DataElementBindingComponent = (function(superClass) { extend(DataElementBindingComponent, superClass); function DataElementBindingComponent(json) { this.json = json; DataElementBindingComponent.__super__.constructor.call(this, this.json); } /** If true, then conformant systems may use additional codes or (where the data type permits) text alone to convey concepts not covered by the set of codes identified in the binding. If false, then conformant systems are constrained to the provided codes alone. @returns {Array} an array of {@link boolean} objects */ DataElementBindingComponent.prototype.isExtensible = function() { return this.json['isExtensible']; }; /** Indicates the degree of conformance expectations associated with this binding. @returns {Array} an array of {@link String} objects */ DataElementBindingComponent.prototype.conformance = function() { return this.json['conformance']; }; /** Describes the intended use of this particular set of codes. @returns {Array} an array of {@link String} objects */ DataElementBindingComponent.prototype.description = function() { return this.json['description']; }; /** Points to the value set that identifies the set of codes to be used. @returns {Reference} */ DataElementBindingComponent.prototype.valueSet = function() { if (this.json['valueSet']) { return new Reference(this.json['valueSet']); } }; return DataElementBindingComponent; })(BackboneElement); /** Embedded class @class DataElementMappingComponent @exports DataElementMappingComponent as DataElementMappingComponent */ DataElementMappingComponent = (function(superClass) { extend(DataElementMappingComponent, superClass); function DataElementMappingComponent(json) { this.json = json; DataElementMappingComponent.__super__.constructor.call(this, this.json); } /** A URI that identifies the specification that this mapping is expressed to. @returns {Array} an array of {@link String} objects */ DataElementMappingComponent.prototype.uri = function() { return this.json['uri']; }; /** If true, indicates that the official meaning of the data element is exactly equivalent to the mapped element. @returns {Array} an array of {@link boolean} objects */ DataElementMappingComponent.prototype.definitional = function() { return this.json['definitional']; }; /** A name for the specification that is being mapped to. @returns {Array} an array of {@link String} objects */ DataElementMappingComponent.prototype.name = function() { return this.json['name']; }; /** Comments about this mapping, including version notes, issues, scope limitations, and other important notes for usage. @returns {Array} an array of {@link String} objects */ DataElementMappingComponent.prototype.comments = function() { return this.json['comments']; }; /** Expresses what part of the target specification corresponds to this element. @returns {Array} an array of {@link String} objects */ DataElementMappingComponent.prototype.map = function() { return this.json['map']; }; return DataElementMappingComponent; })(BackboneElement); /** The formal description of a single piece of information that can be gathered and reported. @class DataElement @exports DataElement as DataElement */ DataElement = (function(superClass) { extend(DataElement, superClass); function DataElement(json) { this.json = json; DataElement.__super__.constructor.call(this, this.json); } /** The identifier that is used to identify this data element when it is referenced in a Profile, Questionnaire or an instance. @returns {Identifier} */ DataElement.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** The identifier that is used to identify this version of the data element when it is referenced in a Profile, Questionnaire or instance. This is an arbitrary value managed by the definition author manually. @returns {Array} an array of {@link String} objects */ DataElement.prototype.version = function() { return this.json['version']; }; /** Details of the individual or organization who accepts responsibility for publishing the data element. @returns {Array} an array of {@link String} objects */ DataElement.prototype.publisher = function() { return this.json['publisher']; }; /** Contact details to assist a user in finding and communicating with the publisher. @returns {Array} an array of {@link ContactPoint} objects */ DataElement.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** The status of the data element. @returns {Array} an array of {@link String} objects */ DataElement.prototype.status = function() { return this.json['status']; }; /** The date that this version of the data element was published. @returns {Array} an array of {@link Date} objects */ DataElement.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The term used by humans to refer to the data element. Should ideally be unique within the context in which the data element is expected to be used. @returns {Array} an array of {@link String} objects */ DataElement.prototype.name = function() { return this.json['name']; }; /** A set of terms from external terminologies that may be used to assist with indexing and searching of data element definitions. @returns {Array} an array of {@link CodeableConcept} objects */ DataElement.prototype.category = function() { var i, item, len, ref, results; if (this.json['category']) { ref = this.json['category']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** A code that provides the meaning for a data element according to a particular terminology. @returns {Array} an array of {@link Coding} objects */ DataElement.prototype.code = function() { var i, item, len, ref, results; if (this.json['code']) { ref = this.json['code']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** The default/suggested phrasing to use when prompting a human to capture the data element. @returns {Array} an array of {@link String} objects */ DataElement.prototype.question = function() { return this.json['question']; }; /** Provides a complete explanation of the meaning of the data element for human readability. @returns {Array} an array of {@link String} objects */ DataElement.prototype.definition = function() { return this.json['definition']; }; /** Comments about the use of the element, including notes about how to use the data properly, exceptions to proper use, etc. @returns {Array} an array of {@link String} objects */ DataElement.prototype.comments = function() { return this.json['comments']; }; /** Explains why this element is needed and why it's been constrained as it has. @returns {Array} an array of {@link String} objects */ DataElement.prototype.requirements = function() { return this.json['requirements']; }; /** Identifies additional names by which this element might also be known. @returns {Array} an array of {@link String} objects */ DataElement.prototype.synonym = function() { return this.json['synonym']; }; /** The FHIR data type that is the type for this element. @returns {Array} an array of {@link String} objects */ DataElement.prototype.type = function() { return this.json['type']; }; /** An sample value for this element demonstrating the type of information that would typically be captured. @returns {Array} an array of {@link } objects */ DataElement.prototype.example = function() { return this.json['example']; }; /** Indicates the shortest length that SHALL be supported by conformant instances without truncation. @returns {Array} an array of {@link Number} objects */ DataElement.prototype.maxLength = function() { return this.json['maxLength']; }; /** Identifies the units of measure in which the data element should be captured or expressed. @returns {CodeableConcept} */ DataElement.prototype.units = function() { if (this.json['units']) { return new CodeableConcept(this.json['units']); } }; /** Binds to a value set if this element is coded (code, Coding, CodeableConcept). @returns {DataElementBindingComponent} */ DataElement.prototype.binding = function() { if (this.json['binding']) { return new DataElementBindingComponent(this.json['binding']); } }; /** Identifies a concept from an external specification that roughly corresponds to this element. @returns {Array} an array of {@link DataElementMappingComponent} objects */ DataElement.prototype.mapping = function() { var i, item, len, ref, results; if (this.json['mapping']) { ref = this.json['mapping']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DataElementMappingComponent(item)); } return results; } }; return DataElement; })(DomainResource); module.exports.DataElement = DataElement; }).call(this); },{"../cql-datatypes":117,"./core":173}],176:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, Device, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource identifies an instance of a manufactured thing that is used in the provision of healthcare without being substantially changed through that activity. The device may be a machine, an insert, a computer, an application, etc. This includes durable (reusable) medical equipment as well as disposable equipment used for diagnostic, treatment, and research for healthcare and public health. @class Device @exports Device as Device */ Device = (function(superClass) { extend(Device, superClass); function Device(json) { this.json = json; Device.__super__.constructor.call(this, this.json); } /** Identifiers assigned to this device by various organizations. The most likely organizations to assign identifiers are the manufacturer and the owner, though regulatory agencies may also assign an identifier. The identifiers identify the particular device, not the kind of device. @returns {Array} an array of {@link Identifier} objects */ Device.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** A kind of this device. @returns {CodeableConcept} */ Device.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** A name of the manufacturer. @returns {Array} an array of {@link String} objects */ Device.prototype.manufacturer = function() { return this.json['manufacturer']; }; /** The "model" - an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type. @returns {Array} an array of {@link String} objects */ Device.prototype.model = function() { return this.json['model']; }; /** The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware. @returns {Array} an array of {@link String} objects */ Device.prototype.version = function() { return this.json['version']; }; /** Date of expiry of this device (if applicable). @returns {Array} an array of {@link Date} objects */ Device.prototype.expiry = function() { if (this.json['expiry']) { return DT.DateTime.parse(this.json['expiry']); } }; /** FDA Mandated Unique Device Identifier. Use the human readable information (the content that the user sees, which is sometimes different to the exact syntax represented in the barcode) - see http://www.fda.gov/MedicalDevices/DeviceRegulationandGuidance/UniqueDeviceIdentification/default.htm. @returns {Array} an array of {@link String} objects */ Device.prototype.udi = function() { return this.json['udi']; }; /** Lot number assigned by the manufacturer. @returns {Array} an array of {@link String} objects */ Device.prototype.lotNumber = function() { return this.json['lotNumber']; }; /** An organization that is responsible for the provision and ongoing maintenance of the device. @returns {Reference} */ Device.prototype.owner = function() { if (this.json['owner']) { return new Reference(this.json['owner']); } }; /** The resource may be found in a literal location (i.e. GPS coordinates), a logical place (i.e. "in/with the patient"), or a coded location. @returns {Reference} */ Device.prototype.location = function() { if (this.json['location']) { return new Reference(this.json['location']); } }; /** Patient information, if the resource is affixed to a person. @returns {Reference} */ Device.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** Contact details for an organization or a particular human that is responsible for the device. @returns {Array} an array of {@link ContactPoint} objects */ Device.prototype.contact = function() { var i, item, len, ref, results; if (this.json['contact']) { ref = this.json['contact']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** A network address on which the device may be contacted directly. @returns {Array} an array of {@link String} objects */ Device.prototype.url = function() { return this.json['url']; }; return Device; })(DomainResource); module.exports.Device = Device; }).call(this); },{"../cql-datatypes":117,"./core":173}],177:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DeviceComponent, DeviceComponentProductionSpecificationComponent, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class DeviceComponentProductionSpecificationComponent @exports DeviceComponentProductionSpecificationComponent as DeviceComponentProductionSpecificationComponent */ DeviceComponentProductionSpecificationComponent = (function(superClass) { extend(DeviceComponentProductionSpecificationComponent, superClass); function DeviceComponentProductionSpecificationComponent(json) { this.json = json; DeviceComponentProductionSpecificationComponent.__super__.constructor.call(this, this.json); } /** Describes the specification type, such as, serial number, part number, hardware revision, software revision, etc. @returns {CodeableConcept} */ DeviceComponentProductionSpecificationComponent.prototype.specType = function() { if (this.json['specType']) { return new CodeableConcept(this.json['specType']); } }; /** Describes the internal component unique identification. This is a provision for manufacture specific standard components using a private OID. 11073-10101 has a partition for private OID semantic that the manufacture can make use of. @returns {Identifier} */ DeviceComponentProductionSpecificationComponent.prototype.componentId = function() { if (this.json['componentId']) { return new Identifier(this.json['componentId']); } }; /** Describes the printable string defining the component. @returns {Array} an array of {@link String} objects */ DeviceComponentProductionSpecificationComponent.prototype.productionSpec = function() { return this.json['productionSpec']; }; return DeviceComponentProductionSpecificationComponent; })(BackboneElement); /** Describes the characteristics, operational status and capabilities of a medical-related component of a medical device. @class DeviceComponent @exports DeviceComponent as DeviceComponent */ DeviceComponent = (function(superClass) { extend(DeviceComponent, superClass); function DeviceComponent(json) { this.json = json; DeviceComponent.__super__.constructor.call(this, this.json); } /** Describes the specific component type as defined in the object-oriented or metric nomenclature partition. @returns {CodeableConcept} */ DeviceComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Describes the local assigned unique identification by the software. For example: handle ID. @returns {Identifier} */ DeviceComponent.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** Describes the timestamp for the most recent system change which includes device configuration or setting change. @returns {Array} an array of {@link Date} objects */ DeviceComponent.prototype.lastSystemChange = function() { if (this.json['lastSystemChange']) { return DT.DateTime.parse(this.json['lastSystemChange']); } }; /** Describes the link to the source Device that contains administrative device information such as manufacture, serial number, etc. @returns {Reference} */ DeviceComponent.prototype.source = function() { if (this.json['source']) { return new Reference(this.json['source']); } }; /** Describes the link to the parent resource. For example: Channel is linked to its VMD parent. @returns {Reference} */ DeviceComponent.prototype.parent = function() { if (this.json['parent']) { return new Reference(this.json['parent']); } }; /** Indicates current operational status of the device. For example: On, Off, Standby, etc. @returns {Array} an array of {@link CodeableConcept} objects */ DeviceComponent.prototype.operationalStatus = function() { var i, item, len, ref, results; if (this.json['operationalStatus']) { ref = this.json['operationalStatus']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Describes the parameter group supported by the current device component that is based on some nomenclature, e.g., cardiovascular. @returns {CodeableConcept} */ DeviceComponent.prototype.parameterGroup = function() { if (this.json['parameterGroup']) { return new CodeableConcept(this.json['parameterGroup']); } }; /** Describes the physical principle of the measurement. For example: thermal, chemical, acoustical, etc. @returns {Array} an array of {@link String} objects */ DeviceComponent.prototype.measurementPrinciple = function() { return this.json['measurementPrinciple']; }; /** Describes the production specification such as component revision, serial number, etc. @returns {Array} an array of {@link DeviceComponentProductionSpecificationComponent} objects */ DeviceComponent.prototype.productionSpecification = function() { var i, item, len, ref, results; if (this.json['productionSpecification']) { ref = this.json['productionSpecification']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DeviceComponentProductionSpecificationComponent(item)); } return results; } }; /** Describes the language code for the human-readable text string produced by the device. This language code will follow the IETF language tag. Example: en-US. @returns {CodeableConcept} */ DeviceComponent.prototype.languageCode = function() { if (this.json['languageCode']) { return new CodeableConcept(this.json['languageCode']); } }; return DeviceComponent; })(DomainResource); module.exports.DeviceComponent = DeviceComponent; }).call(this); },{"../cql-datatypes":117,"./core":173}],178:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DeviceUseRequest, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Represents a request for the use of a device. @class DeviceUseRequest @exports DeviceUseRequest as DeviceUseRequest */ DeviceUseRequest = (function(superClass) { extend(DeviceUseRequest, superClass); function DeviceUseRequest(json) { this.json = json; DeviceUseRequest.__super__.constructor.call(this, this.json); } /** Body site where the device is to be used. @returns {Array} an array of {@link CodeableConcept} objects */ DeviceUseRequest.prototype.bodySite = function() { var i, item, len, ref, results; if (this.json['bodySite']) { ref = this.json['bodySite']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The status of the request. @returns {Array} an array of {@link String} objects */ DeviceUseRequest.prototype.status = function() { return this.json['status']; }; /** The mode of the request. @returns {Array} an array of {@link String} objects */ DeviceUseRequest.prototype.mode = function() { return this.json['mode']; }; /** The details of the device to be used. @returns {Reference} */ DeviceUseRequest.prototype.device = function() { if (this.json['device']) { return new Reference(this.json['device']); } }; /** An encounter that provides additional context in which this request is made. @returns {Reference} */ DeviceUseRequest.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** Identifiers assigned to this order by the orderer or by the receiver. @returns {Array} an array of {@link Identifier} objects */ DeviceUseRequest.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Reason or justification for the use of this device. @returns {Array} an array of {@link CodeableConcept} objects */ DeviceUseRequest.prototype.indication = function() { var i, item, len, ref, results; if (this.json['indication']) { ref = this.json['indication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Details about this request that were not represented at all or sufficiently in one of the attributes provided in a class. These may include for example a comment, an instruction, or a note associated with the statement. @returns {Array} an array of {@link String} objects */ DeviceUseRequest.prototype.notes = function() { return this.json['notes']; }; /** The proposed act must be performed if the indicated conditions occur, e.g.., shortness of breath, SpO2 less than x%. @returns {Array} an array of {@link CodeableConcept} objects */ DeviceUseRequest.prototype.prnReason = function() { var i, item, len, ref, results; if (this.json['prnReason']) { ref = this.json['prnReason']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The time when the request was made. @returns {Array} an array of {@link Date} objects */ DeviceUseRequest.prototype.orderedOn = function() { if (this.json['orderedOn']) { return DT.DateTime.parse(this.json['orderedOn']); } }; /** The time at which the request was made/recorded. @returns {Array} an array of {@link Date} objects */ DeviceUseRequest.prototype.recordedOn = function() { if (this.json['recordedOn']) { return DT.DateTime.parse(this.json['recordedOn']); } }; /** The patient who will use the device. @returns {Reference} */ DeviceUseRequest.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The timing schedule for the use of the device The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Timing} */ DeviceUseRequest.prototype.timingTiming = function() { if (this.json['timingTiming']) { return new Timing(this.json['timingTiming']); } }; /** The timing schedule for the use of the device The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Period} */ DeviceUseRequest.prototype.timingPeriod = function() { if (this.json['timingPeriod']) { return new Period(this.json['timingPeriod']); } }; /** The timing schedule for the use of the device The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Array} an array of {@link Date} objects */ DeviceUseRequest.prototype.timingDateTime = function() { if (this.json['timingDateTime']) { return DT.DateTime.parse(this.json['timingDateTime']); } }; /** Characterizes how quickly the use of device must be initiated. Includes concepts such as stat, urgent, routine. @returns {Array} an array of {@link String} objects */ DeviceUseRequest.prototype.priority = function() { return this.json['priority']; }; return DeviceUseRequest; })(DomainResource); module.exports.DeviceUseRequest = DeviceUseRequest; }).call(this); },{"../cql-datatypes":117,"./core":173}],179:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DeviceUseStatement, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A record of a device being used by a patient where the record is the result of a report from the patient or another clinician. @class DeviceUseStatement @exports DeviceUseStatement as DeviceUseStatement */ DeviceUseStatement = (function(superClass) { extend(DeviceUseStatement, superClass); function DeviceUseStatement(json) { this.json = json; DeviceUseStatement.__super__.constructor.call(this, this.json); } /** Body site where the device was used. @returns {Array} an array of {@link CodeableConcept} objects */ DeviceUseStatement.prototype.bodySite = function() { var i, item, len, ref, results; if (this.json['bodySite']) { ref = this.json['bodySite']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The time period over which the device was used. @returns {Period} */ DeviceUseStatement.prototype.whenUsed = function() { if (this.json['whenUsed']) { return new Period(this.json['whenUsed']); } }; /** The details of the device used. @returns {Reference} */ DeviceUseStatement.prototype.device = function() { if (this.json['device']) { return new Reference(this.json['device']); } }; /** An external identifier for this statement such as an IRI. @returns {Array} an array of {@link Identifier} objects */ DeviceUseStatement.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Reason or justification for the use of the device. @returns {Array} an array of {@link CodeableConcept} objects */ DeviceUseStatement.prototype.indication = function() { var i, item, len, ref, results; if (this.json['indication']) { ref = this.json['indication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Details about the device statement that were not represented at all or sufficiently in one of the attributes provided in a class. These may include for example a comment, an instruction, or a note associated with the statement. @returns {Array} an array of {@link String} objects */ DeviceUseStatement.prototype.notes = function() { return this.json['notes']; }; /** The time at which the statement was made/recorded. @returns {Array} an array of {@link Date} objects */ DeviceUseStatement.prototype.recordedOn = function() { if (this.json['recordedOn']) { return DT.DateTime.parse(this.json['recordedOn']); } }; /** The patient who used the device. @returns {Reference} */ DeviceUseStatement.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** How often the device was used. @returns {Timing} */ DeviceUseStatement.prototype.timingTiming = function() { if (this.json['timingTiming']) { return new Timing(this.json['timingTiming']); } }; /** How often the device was used. @returns {Period} */ DeviceUseStatement.prototype.timingPeriod = function() { if (this.json['timingPeriod']) { return new Period(this.json['timingPeriod']); } }; /** How often the device was used. @returns {Array} an array of {@link Date} objects */ DeviceUseStatement.prototype.timingDateTime = function() { if (this.json['timingDateTime']) { return DT.DateTime.parse(this.json['timingDateTime']); } }; return DeviceUseStatement; })(DomainResource); module.exports.DeviceUseStatement = DeviceUseStatement; }).call(this); },{"../cql-datatypes":117,"./core":173}],180:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DiagnosticOrder, DiagnosticOrderEventComponent, DiagnosticOrderItemComponent, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class DiagnosticOrderEventComponent @exports DiagnosticOrderEventComponent as DiagnosticOrderEventComponent */ DiagnosticOrderEventComponent = (function(superClass) { extend(DiagnosticOrderEventComponent, superClass); function DiagnosticOrderEventComponent(json) { this.json = json; DiagnosticOrderEventComponent.__super__.constructor.call(this, this.json); } /** The status for the event. @returns {Array} an array of {@link String} objects */ DiagnosticOrderEventComponent.prototype.status = function() { return this.json['status']; }; /** Additional information about the event that occurred - e.g. if the status remained unchanged. @returns {CodeableConcept} */ DiagnosticOrderEventComponent.prototype.description = function() { if (this.json['description']) { return new CodeableConcept(this.json['description']); } }; /** The date/time at which the event occurred. @returns {Array} an array of {@link Date} objects */ DiagnosticOrderEventComponent.prototype.dateTime = function() { if (this.json['dateTime']) { return DT.DateTime.parse(this.json['dateTime']); } }; /** The person who was responsible for performing or recording the action. @returns {Reference} */ DiagnosticOrderEventComponent.prototype.actor = function() { if (this.json['actor']) { return new Reference(this.json['actor']); } }; return DiagnosticOrderEventComponent; })(BackboneElement); /** Embedded class @class DiagnosticOrderItemComponent @exports DiagnosticOrderItemComponent as DiagnosticOrderItemComponent */ DiagnosticOrderItemComponent = (function(superClass) { extend(DiagnosticOrderItemComponent, superClass); function DiagnosticOrderItemComponent(json) { this.json = json; DiagnosticOrderItemComponent.__super__.constructor.call(this, this.json); } /** A code that identifies a particular diagnostic investigation, or panel of investigations, that have been requested. @returns {CodeableConcept} */ DiagnosticOrderItemComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** If the item is related to a specific speciment. @returns {Array} an array of {@link Reference} objects */ DiagnosticOrderItemComponent.prototype.specimen = function() { var i, item, len, ref, results; if (this.json['specimen']) { ref = this.json['specimen']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Anatomical location where the request test should be performed. @returns {CodeableConcept} */ DiagnosticOrderItemComponent.prototype.bodySite = function() { if (this.json['bodySite']) { return new CodeableConcept(this.json['bodySite']); } }; /** The status of this individual item within the order. @returns {Array} an array of {@link String} objects */ DiagnosticOrderItemComponent.prototype.status = function() { return this.json['status']; }; /** A summary of the events of interest that have occurred as this item of the request is processed. @returns {Array} an array of {@link DiagnosticOrderEventComponent} objects */ DiagnosticOrderItemComponent.prototype.event = function() { var i, item, len, ref, results; if (this.json['event']) { ref = this.json['event']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DiagnosticOrderEventComponent(item)); } return results; } }; return DiagnosticOrderItemComponent; })(BackboneElement); /** A request for a diagnostic investigation service to be performed. @class DiagnosticOrder @exports DiagnosticOrder as DiagnosticOrder */ DiagnosticOrder = (function(superClass) { extend(DiagnosticOrder, superClass); function DiagnosticOrder(json) { this.json = json; DiagnosticOrder.__super__.constructor.call(this, this.json); } /** Who or what the investigation is to be performed on. This is usually a human patient, but diagnostic tests can also be requested on animals, groups of humans or animals, devices such as dialysis machines, or even locations (typically for environmental scans). @returns {Reference} */ DiagnosticOrder.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The practitioner that holds legal responsibility for ordering the investigation. @returns {Reference} */ DiagnosticOrder.prototype.orderer = function() { if (this.json['orderer']) { return new Reference(this.json['orderer']); } }; /** Identifiers assigned to this order by the order or by the receiver. @returns {Array} an array of {@link Identifier} objects */ DiagnosticOrder.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** An encounter that provides additional information about the healthcare context in which this request is made. @returns {Reference} */ DiagnosticOrder.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** An explanation or justification for why this diagnostic investigation is being requested. @returns {Array} an array of {@link String} objects */ DiagnosticOrder.prototype.clinicalNotes = function() { return this.json['clinicalNotes']; }; /** Additional clinical information about the patient or specimen that may influence test interpretations. @returns {Array} an array of {@link Reference} objects */ DiagnosticOrder.prototype.supportingInformation = function() { var i, item, len, ref, results; if (this.json['supportingInformation']) { ref = this.json['supportingInformation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** One or more specimens that the diagnostic investigation is about. @returns {Array} an array of {@link Reference} objects */ DiagnosticOrder.prototype.specimen = function() { var i, item, len, ref, results; if (this.json['specimen']) { ref = this.json['specimen']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The status of the order. @returns {Array} an array of {@link String} objects */ DiagnosticOrder.prototype.status = function() { return this.json['status']; }; /** The clinical priority associated with this order. @returns {Array} an array of {@link String} objects */ DiagnosticOrder.prototype.priority = function() { return this.json['priority']; }; /** A summary of the events of interest that have occurred as the request is processed. E.g. when the order was made, various processing steps (specimens received), when it was completed. @returns {Array} an array of {@link DiagnosticOrderEventComponent} objects */ DiagnosticOrder.prototype.event = function() { var i, item, len, ref, results; if (this.json['event']) { ref = this.json['event']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DiagnosticOrderEventComponent(item)); } return results; } }; /** The specific diagnostic investigations that are requested as part of this request. Sometimes, there can only be one item per request, but in most contexts, more than one investigation can be requested. @returns {Array} an array of {@link DiagnosticOrderItemComponent} objects */ DiagnosticOrder.prototype.item = function() { var i, item, len, ref, results; if (this.json['item']) { ref = this.json['item']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DiagnosticOrderItemComponent(item)); } return results; } }; return DiagnosticOrder; })(DomainResource); module.exports.DiagnosticOrder = DiagnosticOrder; }).call(this); },{"../cql-datatypes":117,"./core":173}],181:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DiagnosticReport, DiagnosticReportImageComponent, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class DiagnosticReportImageComponent @exports DiagnosticReportImageComponent as DiagnosticReportImageComponent */ DiagnosticReportImageComponent = (function(superClass) { extend(DiagnosticReportImageComponent, superClass); function DiagnosticReportImageComponent(json) { this.json = json; DiagnosticReportImageComponent.__super__.constructor.call(this, this.json); } /** A comment about the image. Typically, this is used to provide an explanation for why the image is included, or to draw the viewer's attention to important features. @returns {Array} an array of {@link String} objects */ DiagnosticReportImageComponent.prototype.comment = function() { return this.json['comment']; }; /** Reference to the image source. @returns {Reference} */ DiagnosticReportImageComponent.prototype.link = function() { if (this.json['link']) { return new Reference(this.json['link']); } }; return DiagnosticReportImageComponent; })(BackboneElement); /** The findings and interpretation of diagnostic tests performed on patients, groups of patients, devices, and locations, and/or specimens derived from these. The report includes clinical context such as requesting and provider information, and some mix of atomic results, images, textual and coded interpretation, and formatted representation of diagnostic reports. @class DiagnosticReport @exports DiagnosticReport as DiagnosticReport */ DiagnosticReport = (function(superClass) { extend(DiagnosticReport, superClass); function DiagnosticReport(json) { this.json = json; DiagnosticReport.__super__.constructor.call(this, this.json); } /** A code or name that describes this diagnostic report. @returns {CodeableConcept} */ DiagnosticReport.prototype.name = function() { if (this.json['name']) { return new CodeableConcept(this.json['name']); } }; /** The status of the diagnostic report as a whole. @returns {Array} an array of {@link String} objects */ DiagnosticReport.prototype.status = function() { return this.json['status']; }; /** The date and/or time that this version of the report was released from the source diagnostic service. @returns {Array} an array of {@link Date} objects */ DiagnosticReport.prototype.issued = function() { if (this.json['issued']) { return DT.DateTime.parse(this.json['issued']); } }; /** The subject of the report. Usually, but not always, this is a patient. However diagnostic services also perform analyses on specimens collected from a variety of other sources. @returns {Reference} */ DiagnosticReport.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The diagnostic service that is responsible for issuing the report. @returns {Reference} */ DiagnosticReport.prototype.performer = function() { if (this.json['performer']) { return new Reference(this.json['performer']); } }; /** The local ID assigned to the report by the order filler, usually by the Information System of the diagnostic service provider. @returns {Identifier} */ DiagnosticReport.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** Details concerning a test requested. @returns {Array} an array of {@link Reference} objects */ DiagnosticReport.prototype.requestDetail = function() { var i, item, len, ref, results; if (this.json['requestDetail']) { ref = this.json['requestDetail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The section of the diagnostic service that performs the examination e.g. biochemistry, hematology, MRI. @returns {CodeableConcept} */ DiagnosticReport.prototype.serviceCategory = function() { if (this.json['serviceCategory']) { return new CodeableConcept(this.json['serviceCategory']); } }; /** The time or time-period the observed values are related to. This is usually either the time of the procedure or of specimen collection(s), but very often the source of the date/time is not known, only the date/time itself. @returns {Array} an array of {@link Date} objects */ DiagnosticReport.prototype.diagnosticDateTime = function() { if (this.json['diagnosticDateTime']) { return DT.DateTime.parse(this.json['diagnosticDateTime']); } }; /** The time or time-period the observed values are related to. This is usually either the time of the procedure or of specimen collection(s), but very often the source of the date/time is not known, only the date/time itself. @returns {Period} */ DiagnosticReport.prototype.diagnosticPeriod = function() { if (this.json['diagnosticPeriod']) { return new Period(this.json['diagnosticPeriod']); } }; /** Details about the specimens on which this Disagnostic report is based. @returns {Array} an array of {@link Reference} objects */ DiagnosticReport.prototype.specimen = function() { var i, item, len, ref, results; if (this.json['specimen']) { ref = this.json['specimen']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Observations that are part of this diagnostic report. Observations can be simple name/value pairs (e.g. "atomic" results), or they can be grouping observations that include references to other members of the group (e.g. "panels"). @returns {Array} an array of {@link Reference} objects */ DiagnosticReport.prototype.result = function() { var i, item, len, ref, results; if (this.json['result']) { ref = this.json['result']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** One or more links to full details of any imaging performed during the diagnostic investigation. Typically, this is imaging performed by DICOM enabled modalities, but this is not required. A fully enabled PACS viewer can use this information to provide views of the source images. @returns {Array} an array of {@link Reference} objects */ DiagnosticReport.prototype.imagingStudy = function() { var i, item, len, ref, results; if (this.json['imagingStudy']) { ref = this.json['imagingStudy']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** A list of key images associated with this report. The images are generally created during the diagnostic process, and may be directly of the patient, or of treated specimens (i.e. slides of interest). @returns {Array} an array of {@link DiagnosticReportImageComponent} objects */ DiagnosticReport.prototype.image = function() { var i, item, len, ref, results; if (this.json['image']) { ref = this.json['image']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DiagnosticReportImageComponent(item)); } return results; } }; /** Concise and clinically contextualized narrative interpretation of the diagnostic report. @returns {Array} an array of {@link String} objects */ DiagnosticReport.prototype.conclusion = function() { return this.json['conclusion']; }; /** Codes for the conclusion. @returns {Array} an array of {@link CodeableConcept} objects */ DiagnosticReport.prototype.codedDiagnosis = function() { var i, item, len, ref, results; if (this.json['codedDiagnosis']) { ref = this.json['codedDiagnosis']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Rich text representation of the entire result as issued by the diagnostic service. Multiple formats are allowed but they SHALL be semantically equivalent. @returns {Array} an array of {@link Attachment} objects */ DiagnosticReport.prototype.presentedForm = function() { var i, item, len, ref, results; if (this.json['presentedForm']) { ref = this.json['presentedForm']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Attachment(item)); } return results; } }; return DiagnosticReport; })(DomainResource); module.exports.DiagnosticReport = DiagnosticReport; }).call(this); },{"../cql-datatypes":117,"./core":173}],182:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DocumentManifest, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A manifest that defines a set of documents. @class DocumentManifest @exports DocumentManifest as DocumentManifest */ DocumentManifest = (function(superClass) { extend(DocumentManifest, superClass); function DocumentManifest(json) { this.json = json; DocumentManifest.__super__.constructor.call(this, this.json); } /** A single identifier that uniquely identifies this manifest. Principally used to refer to the manifest in non-FHIR contexts. @returns {Identifier} */ DocumentManifest.prototype.masterIdentifier = function() { if (this.json['masterIdentifier']) { return new Identifier(this.json['masterIdentifier']); } }; /** Other identifiers associated with the document, including version independent, source record and workflow related identifiers. @returns {Array} an array of {@link Identifier} objects */ DocumentManifest.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Who or what the set of documents is about. The documents can be about a person, (patient or healthcare practitioner), a device (i.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure). If the documents cross more than one subject, then more than one subject is allowed here (unusual use case). @returns {Array} an array of {@link Reference} objects */ DocumentManifest.prototype.subject = function() { var i, item, len, ref, results; if (this.json['subject']) { ref = this.json['subject']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** A patient, practitioner, or organization for which this set of documents is intended. @returns {Array} an array of {@link Reference} objects */ DocumentManifest.prototype.recipient = function() { var i, item, len, ref, results; if (this.json['recipient']) { ref = this.json['recipient']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Specifies the kind of this set of documents (e.g. Patient Summary, Discharge Summary, Prescription, etc.). The type of a set of documents may be the same as one of the documents in it - especially if there is only one - but it may be wider. @returns {CodeableConcept} */ DocumentManifest.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Identifies who is responsible for adding the information to the document. @returns {Array} an array of {@link Reference} objects */ DocumentManifest.prototype.author = function() { var i, item, len, ref, results; if (this.json['author']) { ref = this.json['author']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** When the document manifest was created for submission to the server (not necessarily the same thing as the actual resource last modified time, since it may be modified, replicated etc). @returns {Array} an array of {@link Date} objects */ DocumentManifest.prototype.created = function() { if (this.json['created']) { return DT.DateTime.parse(this.json['created']); } }; /** Identifies the source system, application, or software that produced the document manifest. @returns {Array} an array of {@link String} objects */ DocumentManifest.prototype.source = function() { return this.json['source']; }; /** The status of this document manifest. @returns {Array} an array of {@link String} objects */ DocumentManifest.prototype.status = function() { return this.json['status']; }; /** Whether this document manifest replaces another. @returns {Reference} */ DocumentManifest.prototype.supercedes = function() { if (this.json['supercedes']) { return new Reference(this.json['supercedes']); } }; /** Human-readable description of the source document. This is sometimes known as the "title". @returns {Array} an array of {@link String} objects */ DocumentManifest.prototype.description = function() { return this.json['description']; }; /** A code specifying the level of confidentiality of this set of Documents. @returns {CodeableConcept} */ DocumentManifest.prototype.confidentiality = function() { if (this.json['confidentiality']) { return new CodeableConcept(this.json['confidentiality']); } }; /** The list of resources that describe the parts of this document reference. Usually, these would be document references, but direct references to binary attachments and images are also allowed. @returns {Array} an array of {@link Reference} objects */ DocumentManifest.prototype.content = function() { var i, item, len, ref, results; if (this.json['content']) { ref = this.json['content']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return DocumentManifest; })(DomainResource); module.exports.DocumentManifest = DocumentManifest; }).call(this); },{"../cql-datatypes":117,"./core":173}],183:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DocumentReference, DocumentReferenceContextComponent, DocumentReferenceRelatesToComponent, DocumentReferenceServiceComponent, DocumentReferenceServiceParameterComponent, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class DocumentReferenceRelatesToComponent @exports DocumentReferenceRelatesToComponent as DocumentReferenceRelatesToComponent */ DocumentReferenceRelatesToComponent = (function(superClass) { extend(DocumentReferenceRelatesToComponent, superClass); function DocumentReferenceRelatesToComponent(json) { this.json = json; DocumentReferenceRelatesToComponent.__super__.constructor.call(this, this.json); } /** The type of relationship that this document has with anther document. @returns {Array} an array of {@link String} objects */ DocumentReferenceRelatesToComponent.prototype.code = function() { return this.json['code']; }; /** The target document of this relationship. @returns {Reference} */ DocumentReferenceRelatesToComponent.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; return DocumentReferenceRelatesToComponent; })(BackboneElement); /** Embedded class @class DocumentReferenceServiceParameterComponent @exports DocumentReferenceServiceParameterComponent as DocumentReferenceServiceParameterComponent */ DocumentReferenceServiceParameterComponent = (function(superClass) { extend(DocumentReferenceServiceParameterComponent, superClass); function DocumentReferenceServiceParameterComponent(json) { this.json = json; DocumentReferenceServiceParameterComponent.__super__.constructor.call(this, this.json); } /** The name of a parameter. @returns {Array} an array of {@link String} objects */ DocumentReferenceServiceParameterComponent.prototype.name = function() { return this.json['name']; }; /** The value of the named parameter. @returns {Array} an array of {@link String} objects */ DocumentReferenceServiceParameterComponent.prototype.value = function() { return this.json['value']; }; return DocumentReferenceServiceParameterComponent; })(BackboneElement); /** Embedded class @class DocumentReferenceServiceComponent @exports DocumentReferenceServiceComponent as DocumentReferenceServiceComponent */ DocumentReferenceServiceComponent = (function(superClass) { extend(DocumentReferenceServiceComponent, superClass); function DocumentReferenceServiceComponent(json) { this.json = json; DocumentReferenceServiceComponent.__super__.constructor.call(this, this.json); } /** The type of the service that can be used to access the documents. @returns {CodeableConcept} */ DocumentReferenceServiceComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Where the service end-point is located. @returns {Array} an array of {@link String} objects */ DocumentReferenceServiceComponent.prototype.address = function() { return this.json['address']; }; /** A list of named parameters that is used in the service call. @returns {Array} an array of {@link DocumentReferenceServiceParameterComponent} objects */ DocumentReferenceServiceComponent.prototype.parameter = function() { var i, item, len, ref, results; if (this.json['parameter']) { ref = this.json['parameter']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DocumentReferenceServiceParameterComponent(item)); } return results; } }; return DocumentReferenceServiceComponent; })(BackboneElement); /** Embedded class @class DocumentReferenceContextComponent @exports DocumentReferenceContextComponent as DocumentReferenceContextComponent */ DocumentReferenceContextComponent = (function(superClass) { extend(DocumentReferenceContextComponent, superClass); function DocumentReferenceContextComponent(json) { this.json = json; DocumentReferenceContextComponent.__super__.constructor.call(this, this.json); } /** This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a "History and Physical Report" in which the procedure being documented is necessarily a "History and Physical" act. @returns {Array} an array of {@link CodeableConcept} objects */ DocumentReferenceContextComponent.prototype.event = function() { var i, item, len, ref, results; if (this.json['event']) { ref = this.json['event']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The time period over which the service that is described by the document was provided. @returns {Period} */ DocumentReferenceContextComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** The kind of facility where the patient was seen. @returns {CodeableConcept} */ DocumentReferenceContextComponent.prototype.facilityType = function() { if (this.json['facilityType']) { return new CodeableConcept(this.json['facilityType']); } }; return DocumentReferenceContextComponent; })(BackboneElement); /** A reference to a document. @class DocumentReference @exports DocumentReference as DocumentReference */ DocumentReference = (function(superClass) { extend(DocumentReference, superClass); function DocumentReference(json) { this.json = json; DocumentReference.__super__.constructor.call(this, this.json); } /** Document identifier as assigned by the source of the document. This identifier is specific to this version of the document. This unique identifier may be used elsewhere to identify this version of the document. @returns {Identifier} */ DocumentReference.prototype.masterIdentifier = function() { if (this.json['masterIdentifier']) { return new Identifier(this.json['masterIdentifier']); } }; /** Other identifiers associated with the document, including version independent, source record and workflow related identifiers. @returns {Array} an array of {@link Identifier} objects */ DocumentReference.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Who or what the document is about. The document can be about a person, (patient or healthcare practitioner), a device (I.e. machine) or even a group of subjects (such as a document about a herd of farm animals, or a set of patients that share a common exposure). @returns {Reference} */ DocumentReference.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Specifies the particular kind of document (e.g. Patient Summary, Discharge Summary, Prescription, etc.). @returns {CodeableConcept} */ DocumentReference.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** A categorization for the type of the document. This may be implied by or derived from the code specified in the Document Type. @returns {CodeableConcept} */ DocumentReference.prototype["class"] = function() { if (this.json['class']) { return new CodeableConcept(this.json['class']); } }; /** Identifies who is responsible for adding the information to the document. @returns {Array} an array of {@link Reference} objects */ DocumentReference.prototype.author = function() { var i, item, len, ref, results; if (this.json['author']) { ref = this.json['author']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Identifies the organization or group who is responsible for ongoing maintenance of and access to the document. @returns {Reference} */ DocumentReference.prototype.custodian = function() { if (this.json['custodian']) { return new Reference(this.json['custodian']); } }; /** A reference to a domain or server that manages policies under which the document is accessed and/or made available. @returns {Array} an array of {@link String} objects */ DocumentReference.prototype.policyManager = function() { return this.json['policyManager']; }; /** Which person or organization authenticates that this document is valid. @returns {Reference} */ DocumentReference.prototype.authenticator = function() { if (this.json['authenticator']) { return new Reference(this.json['authenticator']); } }; /** When the document was created. @returns {Array} an array of {@link Date} objects */ DocumentReference.prototype.created = function() { if (this.json['created']) { return DT.DateTime.parse(this.json['created']); } }; /** When the document reference was created. @returns {Array} an array of {@link Date} objects */ DocumentReference.prototype.indexed = function() { if (this.json['indexed']) { return DT.DateTime.parse(this.json['indexed']); } }; /** The status of this document reference. @returns {Array} an array of {@link String} objects */ DocumentReference.prototype.status = function() { return this.json['status']; }; /** The status of the underlying document. @returns {CodeableConcept} */ DocumentReference.prototype.docStatus = function() { if (this.json['docStatus']) { return new CodeableConcept(this.json['docStatus']); } }; /** Relationships that this document has with other document references that already exist. @returns {Array} an array of {@link DocumentReferenceRelatesToComponent} objects */ DocumentReference.prototype.relatesTo = function() { var i, item, len, ref, results; if (this.json['relatesTo']) { ref = this.json['relatesTo']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DocumentReferenceRelatesToComponent(item)); } return results; } }; /** Human-readable description of the source document. This is sometimes known as the "title". @returns {Array} an array of {@link String} objects */ DocumentReference.prototype.description = function() { return this.json['description']; }; /** A code specifying the level of confidentiality of the XDS Document. @returns {Array} an array of {@link CodeableConcept} objects */ DocumentReference.prototype.confidentiality = function() { var i, item, len, ref, results; if (this.json['confidentiality']) { ref = this.json['confidentiality']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The primary language in which the source document is written. @returns {Array} an array of {@link String} objects */ DocumentReference.prototype.primaryLanguage = function() { return this.json['primaryLanguage']; }; /** The mime type of the source document. @returns {Array} an array of {@link String} objects */ DocumentReference.prototype.mimeType = function() { return this.json['mimeType']; }; /** An identifier that identifies that the format and content of the document conforms to additional rules beyond the base format indicated in the mimeType. @returns {Array} an array of {@link String} objects */ DocumentReference.prototype.format = function() { return this.json['format']; }; /** The size of the source document this reference refers to in bytes. @returns {Array} an array of {@link Number} objects */ DocumentReference.prototype.size = function() { return this.json['size']; }; /** A hash of the source document to ensure that changes have not occurred. @returns {Array} an array of {@link } objects */ DocumentReference.prototype.hash = function() { return this.json['hash']; }; /** A url at which the document can be accessed. @returns {Array} an array of {@link String} objects */ DocumentReference.prototype.location = function() { return this.json['location']; }; /** A description of a service call that can be used to retrieve the document. @returns {DocumentReferenceServiceComponent} */ DocumentReference.prototype.service = function() { if (this.json['service']) { return new DocumentReferenceServiceComponent(this.json['service']); } }; /** The clinical context in which the document was prepared. @returns {DocumentReferenceContextComponent} */ DocumentReference.prototype.context = function() { if (this.json['context']) { return new DocumentReferenceContextComponent(this.json['context']); } }; return DocumentReference; })(DomainResource); module.exports.DocumentReference = DocumentReference; }).call(this); },{"../cql-datatypes":117,"./core":173}],184:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Eligibility, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides the insurance eligibility details from the insurer regarding a specified coverage and optionally some class of service. @class Eligibility @exports Eligibility as Eligibility */ Eligibility = (function(superClass) { extend(Eligibility, superClass); function Eligibility(json) { this.json = json; Eligibility.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ Eligibility.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ Eligibility.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ Eligibility.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ Eligibility.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who is target of the request. @returns {Reference} */ Eligibility.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ Eligibility.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ Eligibility.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; return Eligibility; })(DomainResource); module.exports.Eligibility = Eligibility; }).call(this); },{"../cql-datatypes":117,"./core":173}],185:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, EligibilityResponse, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides eligibility and plan details from the processing of an Eligibility resource. @class EligibilityResponse @exports EligibilityResponse as EligibilityResponse */ EligibilityResponse = (function(superClass) { extend(EligibilityResponse, superClass); function EligibilityResponse(json) { this.json = json; EligibilityResponse.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ EligibilityResponse.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Original request resource referrence. @returns {Reference} */ EligibilityResponse.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Transaction status: error, complete. @returns {Array} an array of {@link String} objects */ EligibilityResponse.prototype.outcome = function() { return this.json['outcome']; }; /** A description of the status of the adjudication. @returns {Array} an array of {@link String} objects */ EligibilityResponse.prototype.disposition = function() { return this.json['disposition']; }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ EligibilityResponse.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ EligibilityResponse.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ EligibilityResponse.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who produced this adjudicated response. @returns {Reference} */ EligibilityResponse.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ EligibilityResponse.prototype.requestProvider = function() { if (this.json['requestProvider']) { return new Reference(this.json['requestProvider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ EligibilityResponse.prototype.requestOrganization = function() { if (this.json['requestOrganization']) { return new Reference(this.json['requestOrganization']); } }; return EligibilityResponse; })(DomainResource); module.exports.EligibilityResponse = EligibilityResponse; }).call(this); },{"../cql-datatypes":117,"./core":173}],186:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Encounter, EncounterHospitalizationAccomodationComponent, EncounterHospitalizationComponent, EncounterLocationComponent, EncounterParticipantComponent, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class EncounterParticipantComponent @exports EncounterParticipantComponent as EncounterParticipantComponent */ EncounterParticipantComponent = (function(superClass) { extend(EncounterParticipantComponent, superClass); function EncounterParticipantComponent(json) { this.json = json; EncounterParticipantComponent.__super__.constructor.call(this, this.json); } /** Role of participant in encounter. @returns {Array} an array of {@link CodeableConcept} objects */ EncounterParticipantComponent.prototype.type = function() { var i, item, len, ref, results; if (this.json['type']) { ref = this.json['type']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Persons involved in the encounter other than the patient. @returns {Reference} */ EncounterParticipantComponent.prototype.individual = function() { if (this.json['individual']) { return new Reference(this.json['individual']); } }; return EncounterParticipantComponent; })(BackboneElement); /** Embedded class @class EncounterHospitalizationAccomodationComponent @exports EncounterHospitalizationAccomodationComponent as EncounterHospitalizationAccomodationComponent */ EncounterHospitalizationAccomodationComponent = (function(superClass) { extend(EncounterHospitalizationAccomodationComponent, superClass); function EncounterHospitalizationAccomodationComponent(json) { this.json = json; EncounterHospitalizationAccomodationComponent.__super__.constructor.call(this, this.json); } /** The bed that is assigned to the patient. @returns {Reference} */ EncounterHospitalizationAccomodationComponent.prototype.bed = function() { if (this.json['bed']) { return new Reference(this.json['bed']); } }; /** Period during which the patient was assigned the bed. @returns {Period} */ EncounterHospitalizationAccomodationComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return EncounterHospitalizationAccomodationComponent; })(BackboneElement); /** Embedded class @class EncounterHospitalizationComponent @exports EncounterHospitalizationComponent as EncounterHospitalizationComponent */ EncounterHospitalizationComponent = (function(superClass) { extend(EncounterHospitalizationComponent, superClass); function EncounterHospitalizationComponent(json) { this.json = json; EncounterHospitalizationComponent.__super__.constructor.call(this, this.json); } /** Pre-admission identifier. @returns {Identifier} */ EncounterHospitalizationComponent.prototype.preAdmissionIdentifier = function() { if (this.json['preAdmissionIdentifier']) { return new Identifier(this.json['preAdmissionIdentifier']); } }; /** The location from which the patient came before admission. @returns {Reference} */ EncounterHospitalizationComponent.prototype.origin = function() { if (this.json['origin']) { return new Reference(this.json['origin']); } }; /** From where patient was admitted (physician referral, transfer). @returns {CodeableConcept} */ EncounterHospitalizationComponent.prototype.admitSource = function() { if (this.json['admitSource']) { return new CodeableConcept(this.json['admitSource']); } }; /** Period during which the patient was admitted. @returns {Period} */ EncounterHospitalizationComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** Where the patient stays during this encounter. @returns {Array} an array of {@link EncounterHospitalizationAccomodationComponent} objects */ EncounterHospitalizationComponent.prototype.accomodation = function() { var i, item, len, ref, results; if (this.json['accomodation']) { ref = this.json['accomodation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new EncounterHospitalizationAccomodationComponent(item)); } return results; } }; /** Dietary restrictions for the patient. @returns {CodeableConcept} */ EncounterHospitalizationComponent.prototype.diet = function() { if (this.json['diet']) { return new CodeableConcept(this.json['diet']); } }; /** Special courtesies (VIP, board member). @returns {Array} an array of {@link CodeableConcept} objects */ EncounterHospitalizationComponent.prototype.specialCourtesy = function() { var i, item, len, ref, results; if (this.json['specialCourtesy']) { ref = this.json['specialCourtesy']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Wheelchair, translator, stretcher, etc. @returns {Array} an array of {@link CodeableConcept} objects */ EncounterHospitalizationComponent.prototype.specialArrangement = function() { var i, item, len, ref, results; if (this.json['specialArrangement']) { ref = this.json['specialArrangement']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Location to which the patient is discharged. @returns {Reference} */ EncounterHospitalizationComponent.prototype.destination = function() { if (this.json['destination']) { return new Reference(this.json['destination']); } }; /** Category or kind of location after discharge. @returns {CodeableConcept} */ EncounterHospitalizationComponent.prototype.dischargeDisposition = function() { if (this.json['dischargeDisposition']) { return new CodeableConcept(this.json['dischargeDisposition']); } }; /** The final diagnosis given a patient before release from the hospital after all testing, surgery, and workup are complete. @returns {Reference} */ EncounterHospitalizationComponent.prototype.dischargeDiagnosis = function() { if (this.json['dischargeDiagnosis']) { return new Reference(this.json['dischargeDiagnosis']); } }; /** Whether this hospitalization is a readmission. @returns {Array} an array of {@link boolean} objects */ EncounterHospitalizationComponent.prototype.reAdmission = function() { return this.json['reAdmission']; }; return EncounterHospitalizationComponent; })(BackboneElement); /** Embedded class @class EncounterLocationComponent @exports EncounterLocationComponent as EncounterLocationComponent */ EncounterLocationComponent = (function(superClass) { extend(EncounterLocationComponent, superClass); function EncounterLocationComponent(json) { this.json = json; EncounterLocationComponent.__super__.constructor.call(this, this.json); } /** The location where the encounter takes place. @returns {Reference} */ EncounterLocationComponent.prototype.location = function() { if (this.json['location']) { return new Reference(this.json['location']); } }; /** Time period during which the patient was present at the location. @returns {Period} */ EncounterLocationComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return EncounterLocationComponent; })(BackboneElement); /** An interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. @class Encounter @exports Encounter as Encounter */ Encounter = (function(superClass) { extend(Encounter, superClass); function Encounter(json) { this.json = json; Encounter.__super__.constructor.call(this, this.json); } /** Identifier(s) by which this encounter is known. @returns {Array} an array of {@link Identifier} objects */ Encounter.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** planned | in progress | onleave | finished | cancelled. @returns {Array} an array of {@link String} objects */ Encounter.prototype.status = function() { return this.json['status']; }; /** inpatient | outpatient | ambulatory | emergency +. @returns {Array} an array of {@link String} objects */ Encounter.prototype["class"] = function() { return this.json['class']; }; /** Specific type of encounter (e.g. e-mail consultation, surgical day-care, skilled nursing, rehabilitation). @returns {Array} an array of {@link CodeableConcept} objects */ Encounter.prototype.type = function() { var i, item, len, ref, results; if (this.json['type']) { ref = this.json['type']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The patient present at the encounter. @returns {Reference} */ Encounter.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The main practitioner responsible for providing the service. @returns {Array} an array of {@link EncounterParticipantComponent} objects */ Encounter.prototype.participant = function() { var i, item, len, ref, results; if (this.json['participant']) { ref = this.json['participant']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new EncounterParticipantComponent(item)); } return results; } }; /** The appointment that scheduled this encounter. @returns {Reference} */ Encounter.prototype.fulfills = function() { if (this.json['fulfills']) { return new Reference(this.json['fulfills']); } }; /** The start and end time of the encounter. @returns {Period} */ Encounter.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** Quantity of time the encounter lasted. This excludes the time during leaves of absence. @returns {Duration} */ Encounter.prototype.length = function() { if (this.json['length']) { return new Duration(this.json['length']); } }; /** Reason the encounter takes place, expressed as a code. For admissions, this can be used for a coded admission diagnosis. @returns {CodeableConcept} */ Encounter.prototype.reason = function() { if (this.json['reason']) { return new CodeableConcept(this.json['reason']); } }; /** Reason the encounter takes place, as specified using information from another resource. For admissions, this is the admission diagnosis. @returns {Reference} */ Encounter.prototype.indication = function() { if (this.json['indication']) { return new Reference(this.json['indication']); } }; /** Indicates the urgency of the encounter. @returns {CodeableConcept} */ Encounter.prototype.priority = function() { if (this.json['priority']) { return new CodeableConcept(this.json['priority']); } }; /** Details about an admission to a clinic. @returns {EncounterHospitalizationComponent} */ Encounter.prototype.hospitalization = function() { if (this.json['hospitalization']) { return new EncounterHospitalizationComponent(this.json['hospitalization']); } }; /** List of locations at which the patient has been. @returns {Array} an array of {@link EncounterLocationComponent} objects */ Encounter.prototype.location = function() { var i, item, len, ref, results; if (this.json['location']) { ref = this.json['location']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new EncounterLocationComponent(item)); } return results; } }; /** Department or team providing care. @returns {Reference} */ Encounter.prototype.serviceProvider = function() { if (this.json['serviceProvider']) { return new Reference(this.json['serviceProvider']); } }; /** Another Encounter of which this encounter is a part of (administratively or in time). @returns {Reference} */ Encounter.prototype.partOf = function() { if (this.json['partOf']) { return new Reference(this.json['partOf']); } }; return Encounter; })(DomainResource); module.exports.Encounter = Encounter; }).call(this); },{"../cql-datatypes":117,"./core":173}],187:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Enrollment, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides the insurance Enrollment details to the insurer regarding a specified coverage. @class Enrollment @exports Enrollment as Enrollment */ Enrollment = (function(superClass) { extend(Enrollment, superClass); function Enrollment(json) { this.json = json; Enrollment.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ Enrollment.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ Enrollment.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ Enrollment.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ Enrollment.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who is target of the request. @returns {Reference} */ Enrollment.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ Enrollment.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ Enrollment.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Patient Resource. @returns {Reference} */ Enrollment.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Reference to the program or plan identification, underwriter or payor. @returns {Reference} */ Enrollment.prototype.coverage = function() { if (this.json['coverage']) { return new Reference(this.json['coverage']); } }; /** The relationship of the patient to the subscriber. @returns {Coding} */ Enrollment.prototype.relationship = function() { if (this.json['relationship']) { return new Coding(this.json['relationship']); } }; return Enrollment; })(DomainResource); module.exports.Enrollment = Enrollment; }).call(this); },{"../cql-datatypes":117,"./core":173}],188:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, EnrollmentResponse, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides Enrollment and plan details from the processing of an Enrollment resource. @class EnrollmentResponse @exports EnrollmentResponse as EnrollmentResponse */ EnrollmentResponse = (function(superClass) { extend(EnrollmentResponse, superClass); function EnrollmentResponse(json) { this.json = json; EnrollmentResponse.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ EnrollmentResponse.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Original request resource referrence. @returns {Reference} */ EnrollmentResponse.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Transaction status: error, complete. @returns {Array} an array of {@link String} objects */ EnrollmentResponse.prototype.outcome = function() { return this.json['outcome']; }; /** A description of the status of the adjudication. @returns {Array} an array of {@link String} objects */ EnrollmentResponse.prototype.disposition = function() { return this.json['disposition']; }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ EnrollmentResponse.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ EnrollmentResponse.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ EnrollmentResponse.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who produced this adjudicated response. @returns {Reference} */ EnrollmentResponse.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ EnrollmentResponse.prototype.requestProvider = function() { if (this.json['requestProvider']) { return new Reference(this.json['requestProvider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ EnrollmentResponse.prototype.requestOrganization = function() { if (this.json['requestOrganization']) { return new Reference(this.json['requestOrganization']); } }; return EnrollmentResponse; })(DomainResource); module.exports.EnrollmentResponse = EnrollmentResponse; }).call(this); },{"../cql-datatypes":117,"./core":173}],189:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, ExplanationOfBenefit, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides: the claim details; adjudication details from the processing of a Claim; and optionally account balance information , for informing the subscriber of the benefits provided. @class ExplanationOfBenefit @exports ExplanationOfBenefit as ExplanationOfBenefit */ ExplanationOfBenefit = (function(superClass) { extend(ExplanationOfBenefit, superClass); function ExplanationOfBenefit(json) { this.json = json; ExplanationOfBenefit.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ ExplanationOfBenefit.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Original request resource referrence. @returns {Reference} */ ExplanationOfBenefit.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Transaction status: error, complete. @returns {Array} an array of {@link String} objects */ ExplanationOfBenefit.prototype.outcome = function() { return this.json['outcome']; }; /** A description of the status of the adjudication. @returns {Array} an array of {@link String} objects */ ExplanationOfBenefit.prototype.disposition = function() { return this.json['disposition']; }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ ExplanationOfBenefit.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ ExplanationOfBenefit.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ ExplanationOfBenefit.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who produced this adjudicated response. @returns {Reference} */ ExplanationOfBenefit.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ ExplanationOfBenefit.prototype.requestProvider = function() { if (this.json['requestProvider']) { return new Reference(this.json['requestProvider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ ExplanationOfBenefit.prototype.requestOrganization = function() { if (this.json['requestOrganization']) { return new Reference(this.json['requestOrganization']); } }; return ExplanationOfBenefit; })(DomainResource); module.exports.ExplanationOfBenefit = ExplanationOfBenefit; }).call(this); },{"../cql-datatypes":117,"./core":173}],190:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, ExtensionDefinition, ExtensionDefinitionMappingComponent, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ExtensionDefinitionMappingComponent @exports ExtensionDefinitionMappingComponent as ExtensionDefinitionMappingComponent */ ExtensionDefinitionMappingComponent = (function(superClass) { extend(ExtensionDefinitionMappingComponent, superClass); function ExtensionDefinitionMappingComponent(json) { this.json = json; ExtensionDefinitionMappingComponent.__super__.constructor.call(this, this.json); } /** An Internal id that is used to identify this mapping set when specific mappings are made. @returns {Array} an array of {@link String} objects */ ExtensionDefinitionMappingComponent.prototype.identity = function() { return this.json['identity']; }; /** A URI that identifies the specification that this mapping is expressed to. @returns {Array} an array of {@link String} objects */ ExtensionDefinitionMappingComponent.prototype.uri = function() { return this.json['uri']; }; /** A name for the specification that is being mapped to. @returns {Array} an array of {@link String} objects */ ExtensionDefinitionMappingComponent.prototype.name = function() { return this.json['name']; }; /** Comments about this mapping, including version notes, issues, scope limitations, and other important notes for usage. @returns {Array} an array of {@link String} objects */ ExtensionDefinitionMappingComponent.prototype.comments = function() { return this.json['comments']; }; return ExtensionDefinitionMappingComponent; })(BackboneElement); /** Defines an extension that can be used in resources. @class ExtensionDefinition @exports ExtensionDefinition as ExtensionDefinition */ ExtensionDefinition = (function(superClass) { extend(ExtensionDefinition, superClass); function ExtensionDefinition(json) { this.json = json; ExtensionDefinition.__super__.constructor.call(this, this.json); } /** The URL at which this definition is (or will be) published, and which is used to reference this profile in extension urls in operational FHIR systems. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.url = function() { return this.json['url']; }; /** Formal identifier that is used to identify this profile when it is represented in other formats (e.g. ISO 11179(, or referenced in a specification, model, design or an instance (should be globally unique OID, UUID, or URI), (if it's not possible to use the literal URI). @returns {Array} an array of {@link Identifier} objects */ ExtensionDefinition.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** A free text natural language name identifying the extension. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.name = function() { return this.json['name']; }; /** Defined so that applications can use this name when displaying the value of the extension to the user. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.display = function() { return this.json['display']; }; /** Details of the individual or organization who accepts responsibility for publishing the extension definition. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.publisher = function() { return this.json['publisher']; }; /** Contact details to assist a user in finding and communicating with the publisher. @returns {Array} an array of {@link ContactPoint} objects */ ExtensionDefinition.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** A free text natural language description of the extension and its use. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.description = function() { return this.json['description']; }; /** A set of terms from external terminologies that may be used to assist with indexing and searching of extension definitions. @returns {Array} an array of {@link Coding} objects */ ExtensionDefinition.prototype.code = function() { var i, item, len, ref, results; if (this.json['code']) { ref = this.json['code']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** The status of the extension. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.status = function() { return this.json['status']; }; /** This extension definition was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. @returns {Array} an array of {@link boolean} objects */ ExtensionDefinition.prototype.experimental = function() { return this.json['experimental']; }; /** The date that this version of the extension was published. @returns {Array} an array of {@link Date} objects */ ExtensionDefinition.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Scope and Usage that this extension was created to meet. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.requirements = function() { return this.json['requirements']; }; /** An external specification that the content is mapped to. @returns {Array} an array of {@link ExtensionDefinitionMappingComponent} objects */ ExtensionDefinition.prototype.mapping = function() { var i, item, len, ref, results; if (this.json['mapping']) { ref = this.json['mapping']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ExtensionDefinitionMappingComponent(item)); } return results; } }; /** Identifies the type of context to which the extension applies. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.contextType = function() { return this.json['contextType']; }; /** Identifies the types of resource or data type elements to which the extension can be applied. @returns {Array} an array of {@link String} objects */ ExtensionDefinition.prototype.context = function() { return this.json['context']; }; /** Definition of the elements that are defined to be in the extension. @returns {Array} an array of {@link ElementDefinition} objects */ ExtensionDefinition.prototype.element = function() { var i, item, len, ref, results; if (this.json['element']) { ref = this.json['element']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ElementDefinition(item)); } return results; } }; return ExtensionDefinition; })(DomainResource); module.exports.ExtensionDefinition = ExtensionDefinition; }).call(this); },{"../cql-datatypes":117,"./core":173}],191:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, FamilyHistory, FamilyHistoryRelationComponent, FamilyHistoryRelationConditionComponent, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class FamilyHistoryRelationConditionComponent @exports FamilyHistoryRelationConditionComponent as FamilyHistoryRelationConditionComponent */ FamilyHistoryRelationConditionComponent = (function(superClass) { extend(FamilyHistoryRelationConditionComponent, superClass); function FamilyHistoryRelationConditionComponent(json) { this.json = json; FamilyHistoryRelationConditionComponent.__super__.constructor.call(this, this.json); } /** The actual condition specified. Could be a coded condition (like MI or Diabetes) or a less specific string like 'cancer' depending on how much is known about the condition and the capabilities of the creating system. @returns {CodeableConcept} */ FamilyHistoryRelationConditionComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Indicates what happened as a result of this condition. If the condition resulted in death, deceased date is captured on the relation. @returns {CodeableConcept} */ FamilyHistoryRelationConditionComponent.prototype.outcome = function() { if (this.json['outcome']) { return new CodeableConcept(this.json['outcome']); } }; FamilyHistoryRelationConditionComponent.prototype.onsetAge = function() { return new Quantity(this.json['onsetAge']); }; /** Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Range} */ FamilyHistoryRelationConditionComponent.prototype.onsetRange = function() { if (this.json['onsetRange']) { return new Range(this.json['onsetRange']); } }; /** Either the age of onset, range of approximate age or descriptive string can be recorded. For conditions with multiple occurrences, this describes the first known occurrence. @returns {Array} an array of {@link String} objects */ FamilyHistoryRelationConditionComponent.prototype.onsetString = function() { return this.json['onsetString']; }; /** An area where general notes can be placed about this specific condition. @returns {Array} an array of {@link String} objects */ FamilyHistoryRelationConditionComponent.prototype.note = function() { return this.json['note']; }; return FamilyHistoryRelationConditionComponent; })(BackboneElement); /** Embedded class @class FamilyHistoryRelationComponent @exports FamilyHistoryRelationComponent as FamilyHistoryRelationComponent */ FamilyHistoryRelationComponent = (function(superClass) { extend(FamilyHistoryRelationComponent, superClass); function FamilyHistoryRelationComponent(json) { this.json = json; FamilyHistoryRelationComponent.__super__.constructor.call(this, this.json); } /** This will either be a name or a description. E.g. "Aunt Susan", "my cousin with the red hair". @returns {Array} an array of {@link String} objects */ FamilyHistoryRelationComponent.prototype.name = function() { return this.json['name']; }; /** The type of relationship this person has to the patient (father, mother, brother etc.). @returns {CodeableConcept} */ FamilyHistoryRelationComponent.prototype.relationship = function() { if (this.json['relationship']) { return new CodeableConcept(this.json['relationship']); } }; /** The actual or approximate date of birth of the relative. @returns {Period} */ FamilyHistoryRelationComponent.prototype.bornPeriod = function() { if (this.json['bornPeriod']) { return new Period(this.json['bornPeriod']); } }; /** The actual or approximate date of birth of the relative. @returns {Array} an array of {@link Date} objects */ FamilyHistoryRelationComponent.prototype.bornDate = function() { if (this.json['bornDate']) { return DT.DateTime.parse(this.json['bornDate']); } }; /** The actual or approximate date of birth of the relative. @returns {Array} an array of {@link String} objects */ FamilyHistoryRelationComponent.prototype.bornString = function() { return this.json['bornString']; }; FamilyHistoryRelationComponent.prototype.ageAge = function() { return new Quantity(this.json['ageAge']); }; /** The actual or approximate age of the relative at the time the family history is recorded. @returns {Range} */ FamilyHistoryRelationComponent.prototype.ageRange = function() { if (this.json['ageRange']) { return new Range(this.json['ageRange']); } }; /** The actual or approximate age of the relative at the time the family history is recorded. @returns {Array} an array of {@link String} objects */ FamilyHistoryRelationComponent.prototype.ageString = function() { return this.json['ageString']; }; /** If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link boolean} objects */ FamilyHistoryRelationComponent.prototype.deceasedBoolean = function() { return this.json['deceasedBoolean']; }; FamilyHistoryRelationComponent.prototype.deceasedAge = function() { return new Quantity(this.json['deceasedAge']); }; /** If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Range} */ FamilyHistoryRelationComponent.prototype.deceasedRange = function() { if (this.json['deceasedRange']) { return new Range(this.json['deceasedRange']); } }; /** If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link Date} objects */ FamilyHistoryRelationComponent.prototype.deceasedDate = function() { if (this.json['deceasedDate']) { return DT.DateTime.parse(this.json['deceasedDate']); } }; /** If this resource is indicating that the related person is deceased, then an indicator of whether the person is deceased (yes) or not (no) or the age or age range or description of age at death - can be indicated here. If the reason for death is known, then it can be indicated in the outcome code of the condition - in this case the deceased property should still be set. @returns {Array} an array of {@link String} objects */ FamilyHistoryRelationComponent.prototype.deceasedString = function() { return this.json['deceasedString']; }; /** This property allows a non condition-specific note to the made about the related person. Ideally, the note would be in the condition property, but this is not always possible. @returns {Array} an array of {@link String} objects */ FamilyHistoryRelationComponent.prototype.note = function() { return this.json['note']; }; /** The significant Conditions (or condition) that the family member had. This is a repeating section to allow a system to represent more than one condition per resource, though there is nothing stopping multiple resources - one per condition. @returns {Array} an array of {@link FamilyHistoryRelationConditionComponent} objects */ FamilyHistoryRelationComponent.prototype.condition = function() { var i, item, len, ref, results; if (this.json['condition']) { ref = this.json['condition']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new FamilyHistoryRelationConditionComponent(item)); } return results; } }; return FamilyHistoryRelationComponent; })(BackboneElement); /** Significant health events and conditions for people related to the subject relevant in the context of care for the subject. @class FamilyHistory @exports FamilyHistory as FamilyHistory */ FamilyHistory = (function(superClass) { extend(FamilyHistory, superClass); function FamilyHistory(json) { this.json = json; FamilyHistory.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this family history record that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ FamilyHistory.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The person who this history concerns. @returns {Reference} */ FamilyHistory.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The date (and possibly time) when the family history was taken. @returns {Array} an array of {@link Date} objects */ FamilyHistory.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Conveys information about family history not specific to individual relations. @returns {Array} an array of {@link String} objects */ FamilyHistory.prototype.note = function() { return this.json['note']; }; /** The related person. Each FamilyHistory resource contains the entire family history for a single person. @returns {Array} an array of {@link FamilyHistoryRelationComponent} objects */ FamilyHistory.prototype.relation = function() { var i, item, len, ref, results; if (this.json['relation']) { ref = this.json['relation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new FamilyHistoryRelationComponent(item)); } return results; } }; return FamilyHistory; })(DomainResource); module.exports.FamilyHistory = FamilyHistory; }).call(this); },{"../cql-datatypes":117,"./core":173}],192:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, Group, GroupCharacteristicComponent, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class GroupCharacteristicComponent @exports GroupCharacteristicComponent as GroupCharacteristicComponent */ GroupCharacteristicComponent = (function(superClass) { extend(GroupCharacteristicComponent, superClass); function GroupCharacteristicComponent(json) { this.json = json; GroupCharacteristicComponent.__super__.constructor.call(this, this.json); } /** A code that identifies the kind of trait being asserted. @returns {CodeableConcept} */ GroupCharacteristicComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** The value of the trait that holds (or does not hold - see 'exclude') for members of the group. @returns {CodeableConcept} */ GroupCharacteristicComponent.prototype.valueCodeableConcept = function() { if (this.json['valueCodeableConcept']) { return new CodeableConcept(this.json['valueCodeableConcept']); } }; /** The value of the trait that holds (or does not hold - see 'exclude') for members of the group. @returns {Array} an array of {@link boolean} objects */ GroupCharacteristicComponent.prototype.valueBoolean = function() { return this.json['valueBoolean']; }; /** The value of the trait that holds (or does not hold - see 'exclude') for members of the group. @returns {Quantity} */ GroupCharacteristicComponent.prototype.valueQuantity = function() { if (this.json['valueQuantity']) { return new Quantity(this.json['valueQuantity']); } }; /** The value of the trait that holds (or does not hold - see 'exclude') for members of the group. @returns {Range} */ GroupCharacteristicComponent.prototype.valueRange = function() { if (this.json['valueRange']) { return new Range(this.json['valueRange']); } }; /** If true, indicates the characteristic is one that is NOT held by members of the group. @returns {Array} an array of {@link boolean} objects */ GroupCharacteristicComponent.prototype.exclude = function() { return this.json['exclude']; }; return GroupCharacteristicComponent; })(BackboneElement); /** Represents a defined collection of entities that may be discussed or acted upon collectively but which are not expected to act collectively and are not formally or legally recognized. I.e. A collection of entities that isn't an Organization. @class Group @exports Group as Group */ Group = (function(superClass) { extend(Group, superClass); function Group(json) { this.json = json; Group.__super__.constructor.call(this, this.json); } /** A unique business identifier for this group. @returns {Identifier} */ Group.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** Identifies the broad classification of the kind of resources the group includes. @returns {Array} an array of {@link String} objects */ Group.prototype.type = function() { return this.json['type']; }; /** If true, indicates that the resource refers to a specific group of real individuals. If false, the group defines a set of intended individuals. @returns {Array} an array of {@link boolean} objects */ Group.prototype.actual = function() { return this.json['actual']; }; /** Provides a specific type of resource the group includes. E.g. "cow", "syringe", etc. @returns {CodeableConcept} */ Group.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** A label assigned to the group for human identification and communication. @returns {Array} an array of {@link String} objects */ Group.prototype.name = function() { return this.json['name']; }; /** A count of the number of resource instances that are part of the group. @returns {Array} an array of {@link Number} objects */ Group.prototype.quantity = function() { return this.json['quantity']; }; /** Identifies the traits shared by members of the group. @returns {Array} an array of {@link GroupCharacteristicComponent} objects */ Group.prototype.characteristic = function() { var i, item, len, ref, results; if (this.json['characteristic']) { ref = this.json['characteristic']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new GroupCharacteristicComponent(item)); } return results; } }; /** Identifies the resource instances that are members of the group. @returns {Array} an array of {@link Reference} objects */ Group.prototype.member = function() { var i, item, len, ref, results; if (this.json['member']) { ref = this.json['member']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return Group; })(DomainResource); module.exports.Group = Group; }).call(this); },{"../cql-datatypes":117,"./core":173}],193:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HealthcareService, HealthcareServiceAvailableTimeComponent, HealthcareServiceNotAvailableTimeComponent, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, ServiceTypeComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ServiceTypeComponent @exports ServiceTypeComponent as ServiceTypeComponent */ ServiceTypeComponent = (function(superClass) { extend(ServiceTypeComponent, superClass); function ServiceTypeComponent(json) { this.json = json; ServiceTypeComponent.__super__.constructor.call(this, this.json); } /** The specific type of service being delivered or performed. @returns {CodeableConcept} */ ServiceTypeComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Collection of Specialties handled by the Service Site. This is more of a Medical Term. @returns {Array} an array of {@link CodeableConcept} objects */ ServiceTypeComponent.prototype.specialty = function() { var i, item, len, ref, results; if (this.json['specialty']) { ref = this.json['specialty']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; return ServiceTypeComponent; })(BackboneElement); /** Embedded class @class HealthcareServiceAvailableTimeComponent @exports HealthcareServiceAvailableTimeComponent as HealthcareServiceAvailableTimeComponent */ HealthcareServiceAvailableTimeComponent = (function(superClass) { extend(HealthcareServiceAvailableTimeComponent, superClass); function HealthcareServiceAvailableTimeComponent(json) { this.json = json; HealthcareServiceAvailableTimeComponent.__super__.constructor.call(this, this.json); } /** Indicates which Days of the week are available between the Start and End Times. @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareServiceAvailableTimeComponent.prototype.daysOfWeek = function() { var i, item, len, ref, results; if (this.json['daysOfWeek']) { ref = this.json['daysOfWeek']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Is this always available? (hence times are irrelevant) e.g. 24 hour service. @returns {Array} an array of {@link boolean} objects */ HealthcareServiceAvailableTimeComponent.prototype.allDay = function() { return this.json['allDay']; }; /** The opening time of day (the date is not included). Note: If the AllDay flag is set, then this time is ignored. @returns {Array} an array of {@link Date} objects */ HealthcareServiceAvailableTimeComponent.prototype.availableStartTime = function() { if (this.json['availableStartTime']) { return DT.DateTime.parse(this.json['availableStartTime']); } }; /** The closing time of day (the date is not included). Note: If the AllDay flag is set, then this time is ignored. @returns {Array} an array of {@link Date} objects */ HealthcareServiceAvailableTimeComponent.prototype.availableEndTime = function() { if (this.json['availableEndTime']) { return DT.DateTime.parse(this.json['availableEndTime']); } }; return HealthcareServiceAvailableTimeComponent; })(BackboneElement); /** Embedded class @class HealthcareServiceNotAvailableTimeComponent @exports HealthcareServiceNotAvailableTimeComponent as HealthcareServiceNotAvailableTimeComponent */ HealthcareServiceNotAvailableTimeComponent = (function(superClass) { extend(HealthcareServiceNotAvailableTimeComponent, superClass); function HealthcareServiceNotAvailableTimeComponent(json) { this.json = json; HealthcareServiceNotAvailableTimeComponent.__super__.constructor.call(this, this.json); } /** The reason that can be presented to the user as to why this time is not available. @returns {Array} an array of {@link String} objects */ HealthcareServiceNotAvailableTimeComponent.prototype.description = function() { return this.json['description']; }; /** Service is not available (seasonally or for a public holiday) from this date. @returns {Array} an array of {@link Date} objects */ HealthcareServiceNotAvailableTimeComponent.prototype.startDate = function() { if (this.json['startDate']) { return DT.DateTime.parse(this.json['startDate']); } }; /** Service is not available (seasonally or for a public holiday) until this date. @returns {Array} an array of {@link Date} objects */ HealthcareServiceNotAvailableTimeComponent.prototype.endDate = function() { if (this.json['endDate']) { return DT.DateTime.parse(this.json['endDate']); } }; return HealthcareServiceNotAvailableTimeComponent; })(BackboneElement); /** (informative) The details of a Healthcare Service available at a location. @class HealthcareService @exports HealthcareService as HealthcareService */ HealthcareService = (function(superClass) { extend(HealthcareService, superClass); function HealthcareService(json) { this.json = json; HealthcareService.__super__.constructor.call(this, this.json); } /** External Ids for this item. @returns {Array} an array of {@link Identifier} objects */ HealthcareService.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The location where this healthcare service may be provided. @returns {Reference} */ HealthcareService.prototype.location = function() { if (this.json['location']) { return new Reference(this.json['location']); } }; /** Identifies the broad category of service being performed or delivered. Selecting a Service Category then determines the list of relevant service types that can be selected in the Primary Service Type. @returns {CodeableConcept} */ HealthcareService.prototype.serviceCategory = function() { if (this.json['serviceCategory']) { return new CodeableConcept(this.json['serviceCategory']); } }; /** A specific type of service that may be delivered or performed. @returns {Array} an array of {@link ServiceTypeComponent} objects */ HealthcareService.prototype.serviceType = function() { var i, item, len, ref, results; if (this.json['serviceType']) { ref = this.json['serviceType']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ServiceTypeComponent(item)); } return results; } }; /** Further description of the service as it would be presented to a consumer while searching. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.serviceName = function() { return this.json['serviceName']; }; /** Additional description of the or any specific issues not covered by the other attributes, which can be displayed as further detail under the serviceName. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.comment = function() { return this.json['comment']; }; /** Extra details about the service that can't be placed in the other fields. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.extraDetails = function() { return this.json['extraDetails']; }; /** The free provision code provides a link to the Free Provision reference entity to enable the selection of one free provision type. @returns {CodeableConcept} */ HealthcareService.prototype.freeProvisionCode = function() { if (this.json['freeProvisionCode']) { return new CodeableConcept(this.json['freeProvisionCode']); } }; /** Does this service have specific eligibility requirements that need to be met in order to use the service. @returns {CodeableConcept} */ HealthcareService.prototype.eligibility = function() { if (this.json['eligibility']) { return new CodeableConcept(this.json['eligibility']); } }; /** The description of service eligibility should, in general, not exceed one or two paragraphs. It should be sufficient for a prospective consumer to determine if they are likely to be eligible or not. Where eligibility requirements and conditions are complex, it may simply be noted that an eligibility assessment is required. Where eligibility is determined by an outside source, such as an Act of Parliament, this should be noted, preferably with a reference to a commonly available copy of the source document such as a web page. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.eligibilityNote = function() { return this.json['eligibilityNote']; }; /** Indicates whether or not a prospective consumer will require an appointment for a particular service at a Site to be provided by the Organization. Indicates if an appointment is required for access to this service. If this flag is 'NotDefined', then this flag is overridden by the Site's availability flag. (ConditionalIndicator Enum). @returns {CodeableConcept} */ HealthcareService.prototype.appointmentRequired = function() { if (this.json['appointmentRequired']) { return new CodeableConcept(this.json['appointmentRequired']); } }; /** If there is an image associated with this Service Site, its URI can be included here. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.imageURI = function() { return this.json['imageURI']; }; /** A Collection of times that the Service Site is available. @returns {Array} an array of {@link HealthcareServiceAvailableTimeComponent} objects */ HealthcareService.prototype.availableTime = function() { var i, item, len, ref, results; if (this.json['availableTime']) { ref = this.json['availableTime']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new HealthcareServiceAvailableTimeComponent(item)); } return results; } }; /** Not avail times - need better description. @returns {Array} an array of {@link HealthcareServiceNotAvailableTimeComponent} objects */ HealthcareService.prototype.notAvailableTime = function() { var i, item, len, ref, results; if (this.json['notAvailableTime']) { ref = this.json['notAvailableTime']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new HealthcareServiceNotAvailableTimeComponent(item)); } return results; } }; /** A description of Site availability exceptions, e.g., public holiday availability. Succinctly describing all possible exceptions to normal Site availability as details in the Available Times and Not Available Times. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.availabilityExceptions = function() { return this.json['availabilityExceptions']; }; /** The public part of the 'keys' allocated to an Organization by an accredited body to support secure exchange of data over the internet. To be provided by the Organization, where available. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.publicKey = function() { return this.json['publicKey']; }; /** Program Names that can be used to categorize the service. @returns {Array} an array of {@link String} objects */ HealthcareService.prototype.programName = function() { return this.json['programName']; }; /** List of contacts related to this specific healthcare service. If this is empty, then refer to the location's contacts. @returns {Array} an array of {@link ContactPoint} objects */ HealthcareService.prototype.contactPoint = function() { var i, item, len, ref, results; if (this.json['contactPoint']) { ref = this.json['contactPoint']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** Collection of Characteristics (attributes). @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareService.prototype.characteristic = function() { var i, item, len, ref, results; if (this.json['characteristic']) { ref = this.json['characteristic']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Ways that the service accepts referrals. @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareService.prototype.referralMethod = function() { var i, item, len, ref, results; if (this.json['referralMethod']) { ref = this.json['referralMethod']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The setting where this service can be provided, such is in home, or at location in organisation. @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareService.prototype.setting = function() { var i, item, len, ref, results; if (this.json['setting']) { ref = this.json['setting']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Collection of Target Groups for the Service Site (The target audience that this service is for). @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareService.prototype.targetGroup = function() { var i, item, len, ref, results; if (this.json['targetGroup']) { ref = this.json['targetGroup']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Need better description. @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareService.prototype.coverageArea = function() { var i, item, len, ref, results; if (this.json['coverageArea']) { ref = this.json['coverageArea']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Need better description. @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareService.prototype.catchmentArea = function() { var i, item, len, ref, results; if (this.json['catchmentArea']) { ref = this.json['catchmentArea']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** List of the specific. @returns {Array} an array of {@link CodeableConcept} objects */ HealthcareService.prototype.serviceCode = function() { var i, item, len, ref, results; if (this.json['serviceCode']) { ref = this.json['serviceCode']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; return HealthcareService; })(DomainResource); module.exports.HealthcareService = HealthcareService; }).call(this); },{"../cql-datatypes":117,"./core":173}],194:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, ImagingObjectSelection, InstanceComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, SeriesComponent, StudyComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class InstanceComponent @exports InstanceComponent as InstanceComponent */ InstanceComponent = (function(superClass) { extend(InstanceComponent, superClass); function InstanceComponent(json) { this.json = json; InstanceComponent.__super__.constructor.call(this, this.json); } /** SOP class uid of the selected instance. @returns {oid} */ InstanceComponent.prototype.sopClass = function() { if (this.json['sopClass']) { return new oid(this.json['sopClass']); } }; /** SOP Instance uid of the selected instance. @returns {oid} */ InstanceComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** The DICOM Application Entity Title where the DICOM SOP instance can be retrieved. @returns {Array} an array of {@link String} objects */ InstanceComponent.prototype.retrieveAETitle = function() { return this.json['retrieveAETitle']; }; /** WADO-RS URL to retrieve the DICOM SOP Instance. @returns {Array} an array of {@link String} objects */ InstanceComponent.prototype.retrieveUrl = function() { return this.json['retrieveUrl']; }; return InstanceComponent; })(BackboneElement); /** Embedded class @class SeriesComponent @exports SeriesComponent as SeriesComponent */ SeriesComponent = (function(superClass) { extend(SeriesComponent, superClass); function SeriesComponent(json) { this.json = json; SeriesComponent.__super__.constructor.call(this, this.json); } /** Series instance uid of the SOP instances in the selection. @returns {oid} */ SeriesComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** The DICOM Application Entity Title where the series can be retrieved. Note that this AE Title is provided to retrieve all SOP instances of the series not only those in the selection. @returns {Array} an array of {@link String} objects */ SeriesComponent.prototype.retrieveAETitle = function() { return this.json['retrieveAETitle']; }; /** WADO-RS URL to retrieve the series Note that this URL retrieves all SOP instances of the series not only those in the selection. @returns {Array} an array of {@link String} objects */ SeriesComponent.prototype.retrieveUrl = function() { return this.json['retrieveUrl']; }; /** Identity and locating information of the selected DICOM SOP instances. @returns {Array} an array of {@link InstanceComponent} objects */ SeriesComponent.prototype.instance = function() { var i, item, len, ref, results; if (this.json['instance']) { ref = this.json['instance']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new InstanceComponent(item)); } return results; } }; return SeriesComponent; })(BackboneElement); /** Embedded class @class StudyComponent @exports StudyComponent as StudyComponent */ StudyComponent = (function(superClass) { extend(StudyComponent, superClass); function StudyComponent(json) { this.json = json; StudyComponent.__super__.constructor.call(this, this.json); } /** Study instance uid of the SOP instances in the selection. @returns {oid} */ StudyComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** The DICOM Application Entity Title where the study can be retrieved. Note that this AE Title is provided to retrieve all SOP instances of the study, not only those in the selection. @returns {Array} an array of {@link String} objects */ StudyComponent.prototype.retrieveAETitle = function() { return this.json['retrieveAETitle']; }; /** WADO-RS URL to retrieve the study. Note that this URL retrieves all SOP instances of the study, not only those in the selection. @returns {Array} an array of {@link String} objects */ StudyComponent.prototype.retrieveUrl = function() { return this.json['retrieveUrl']; }; /** Series indetity and locating information of the DICOM SOP instances in the selection. @returns {Array} an array of {@link SeriesComponent} objects */ StudyComponent.prototype.series = function() { var i, item, len, ref, results; if (this.json['series']) { ref = this.json['series']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SeriesComponent(item)); } return results; } }; return StudyComponent; })(BackboneElement); /** A set of DICOM SOP Instances of a patient, selected for some application purpose, e.g., quality assurance, teaching, conference, consulting, etc. Objects selected can be from different studies, but must be of the same patient. @class ImagingObjectSelection @exports ImagingObjectSelection as ImagingObjectSelection */ ImagingObjectSelection = (function(superClass) { extend(ImagingObjectSelection, superClass); function ImagingObjectSelection(json) { this.json = json; ImagingObjectSelection.__super__.constructor.call(this, this.json); } /** Instance UID of the DICOM KOS SOP Instances represenetd in this resource. @returns {oid} */ ImagingObjectSelection.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** A patient resource reference which is the patient subject of all DICOM SOP Instances in this key object selection. @returns {Reference} */ ImagingObjectSelection.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The reason for, or significance of, the selection of objects referenced in the resource. @returns {CodeableConcept} */ ImagingObjectSelection.prototype.title = function() { if (this.json['title']) { return new CodeableConcept(this.json['title']); } }; /** Text description of the DICOM SOP instances selected in the key object selection. This should be aligned with the content of the title element, and can provide further explanation of the SOP instances in the selection. @returns {Array} an array of {@link String} objects */ ImagingObjectSelection.prototype.description = function() { return this.json['description']; }; /** Author of key object selection. It can be a human authtor or a device which made the decision of the SOP instances selected. For example, a radiologist selected a set of imaging SOP instances to attached in a diagnostic report, and a CAD application may author a selection to describe SOP instances it used to generate a detection conclusion. @returns {Reference} */ ImagingObjectSelection.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** Date and time when the key object selection was authored. Note that this is the date and time the DICOM SOP instances in the selection were selected (selection decision making). It is different from the creation date and time of the selection resource. @returns {Array} an array of {@link Date} objects */ ImagingObjectSelection.prototype.authoringTime = function() { if (this.json['authoringTime']) { return DT.DateTime.parse(this.json['authoringTime']); } }; /** Study identity and locating information of the DICOM SOP instances in the selection. @returns {Array} an array of {@link StudyComponent} objects */ ImagingObjectSelection.prototype.study = function() { var i, item, len, ref, results; if (this.json['study']) { ref = this.json['study']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new StudyComponent(item)); } return results; } }; return ImagingObjectSelection; })(DomainResource); module.exports.ImagingObjectSelection = ImagingObjectSelection; }).call(this); },{"../cql-datatypes":117,"./core":173}],195:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, ImagingStudy, ImagingStudySeriesComponent, ImagingStudySeriesInstanceComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ImagingStudySeriesInstanceComponent @exports ImagingStudySeriesInstanceComponent as ImagingStudySeriesInstanceComponent */ ImagingStudySeriesInstanceComponent = (function(superClass) { extend(ImagingStudySeriesInstanceComponent, superClass); function ImagingStudySeriesInstanceComponent(json) { this.json = json; ImagingStudySeriesInstanceComponent.__super__.constructor.call(this, this.json); } /** The number of this image in the series. @returns {Array} an array of {@link Number} objects */ ImagingStudySeriesInstanceComponent.prototype.number = function() { return this.json['number']; }; /** Formal identifier for this image. @returns {oid} */ ImagingStudySeriesInstanceComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** DICOM Image type. @returns {oid} */ ImagingStudySeriesInstanceComponent.prototype.sopclass = function() { if (this.json['sopclass']) { return new oid(this.json['sopclass']); } }; /** The type of the instance. @returns {Array} an array of {@link String} objects */ ImagingStudySeriesInstanceComponent.prototype.type = function() { return this.json['type']; }; /** The description of the instance. @returns {Array} an array of {@link String} objects */ ImagingStudySeriesInstanceComponent.prototype.title = function() { return this.json['title']; }; /** WADO-RS url where image is available. @returns {Array} an array of {@link String} objects */ ImagingStudySeriesInstanceComponent.prototype.url = function() { return this.json['url']; }; /** A FHIR resource with content for this instance. @returns {Reference} */ ImagingStudySeriesInstanceComponent.prototype.attachment = function() { if (this.json['attachment']) { return new Reference(this.json['attachment']); } }; return ImagingStudySeriesInstanceComponent; })(BackboneElement); /** Embedded class @class ImagingStudySeriesComponent @exports ImagingStudySeriesComponent as ImagingStudySeriesComponent */ ImagingStudySeriesComponent = (function(superClass) { extend(ImagingStudySeriesComponent, superClass); function ImagingStudySeriesComponent(json) { this.json = json; ImagingStudySeriesComponent.__super__.constructor.call(this, this.json); } /** The Numeric identifier of this series in the study. @returns {Array} an array of {@link Number} objects */ ImagingStudySeriesComponent.prototype.number = function() { return this.json['number']; }; /** The modality of this series sequence. @returns {Array} an array of {@link String} objects */ ImagingStudySeriesComponent.prototype.modality = function() { return this.json['modality']; }; /** Formal identifier for this series. @returns {oid} */ ImagingStudySeriesComponent.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** A description of the series. @returns {Array} an array of {@link String} objects */ ImagingStudySeriesComponent.prototype.description = function() { return this.json['description']; }; /** Sequence that contains attributes from the. @returns {Array} an array of {@link Number} objects */ ImagingStudySeriesComponent.prototype.numberOfInstances = function() { return this.json['numberOfInstances']; }; /** Availability of series (online, offline or nearline). @returns {Array} an array of {@link String} objects */ ImagingStudySeriesComponent.prototype.availability = function() { return this.json['availability']; }; /** WADO-RS URI where Series is available. @returns {Array} an array of {@link String} objects */ ImagingStudySeriesComponent.prototype.url = function() { return this.json['url']; }; /** Body part examined. See DICOM Part 16 Annex L for the mapping from DICOM to Snomed. @returns {Coding} */ ImagingStudySeriesComponent.prototype.bodySite = function() { if (this.json['bodySite']) { return new Coding(this.json['bodySite']); } }; /** The date when the series was started. @returns {Array} an array of {@link Date} objects */ ImagingStudySeriesComponent.prototype.dateTime = function() { if (this.json['dateTime']) { return DT.DateTime.parse(this.json['dateTime']); } }; /** A single image taken from a patient. @returns {Array} an array of {@link ImagingStudySeriesInstanceComponent} objects */ ImagingStudySeriesComponent.prototype.instance = function() { var i, item, len, ref, results; if (this.json['instance']) { ref = this.json['instance']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ImagingStudySeriesInstanceComponent(item)); } return results; } }; return ImagingStudySeriesComponent; })(BackboneElement); /** Representation of the content produced in a DICOM imaging study. A study comprises a set of Series, each of which includes a set of Service-Object Pair Instances (SOP Instances - images or other data) acquired or produced in a common context. A Series is of only one modality (e.g., X-ray, CT, MR, ultrasound), but a Study may have multiple Series of different modalities. @class ImagingStudy @exports ImagingStudy as ImagingStudy */ ImagingStudy = (function(superClass) { extend(ImagingStudy, superClass); function ImagingStudy(json) { this.json = json; ImagingStudy.__super__.constructor.call(this, this.json); } /** Date and Time the study started. @returns {Array} an array of {@link Date} objects */ ImagingStudy.prototype.started = function() { if (this.json['started']) { return DT.DateTime.parse(this.json['started']); } }; /** The patient for whom the images are of. @returns {Reference} */ ImagingStudy.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** Formal identifier for the study. @returns {oid} */ ImagingStudy.prototype.uid = function() { if (this.json['uid']) { return new oid(this.json['uid']); } }; /** Accession Number. @returns {Identifier} */ ImagingStudy.prototype.accession = function() { if (this.json['accession']) { return new Identifier(this.json['accession']); } }; /** Other identifiers for the study. @returns {Array} an array of {@link Identifier} objects */ ImagingStudy.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** A list of the diagnostic orders that resulted in this imaging study being performed. @returns {Array} an array of {@link Reference} objects */ ImagingStudy.prototype.order = function() { var i, item, len, ref, results; if (this.json['order']) { ref = this.json['order']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** A list of all the Series.ImageModality values that are actual acquisition modalities, i.e. those in the DICOM Context Group 29 (value set OID 1.2.840.10008.6.1.19). @returns {Array} an array of {@link String} objects */ ImagingStudy.prototype.modalityList = function() { return this.json['modalityList']; }; /** The requesting/referring physician. @returns {Reference} */ ImagingStudy.prototype.referrer = function() { if (this.json['referrer']) { return new Reference(this.json['referrer']); } }; /** Availability of study (online, offline or nearline). @returns {Array} an array of {@link String} objects */ ImagingStudy.prototype.availability = function() { return this.json['availability']; }; /** WADO-RS URI where Study is available. @returns {Array} an array of {@link String} objects */ ImagingStudy.prototype.url = function() { return this.json['url']; }; /** Number of Series in Study. @returns {Array} an array of {@link Number} objects */ ImagingStudy.prototype.numberOfSeries = function() { return this.json['numberOfSeries']; }; /** Number of SOP Instances in Study. @returns {Array} an array of {@link Number} objects */ ImagingStudy.prototype.numberOfInstances = function() { return this.json['numberOfInstances']; }; /** Diagnoses etc provided with request. @returns {Array} an array of {@link String} objects */ ImagingStudy.prototype.clinicalInformation = function() { return this.json['clinicalInformation']; }; /** Type of procedure performed. @returns {Array} an array of {@link Coding} objects */ ImagingStudy.prototype.procedure = function() { var i, item, len, ref, results; if (this.json['procedure']) { ref = this.json['procedure']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Who read study and interpreted the images. @returns {Reference} */ ImagingStudy.prototype.interpreter = function() { if (this.json['interpreter']) { return new Reference(this.json['interpreter']); } }; /** Institution-generated description or classification of the Study (component) performed. @returns {Array} an array of {@link String} objects */ ImagingStudy.prototype.description = function() { return this.json['description']; }; /** Each study has one or more series of image instances. @returns {Array} an array of {@link ImagingStudySeriesComponent} objects */ ImagingStudy.prototype.series = function() { var i, item, len, ref, results; if (this.json['series']) { ref = this.json['series']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ImagingStudySeriesComponent(item)); } return results; } }; return ImagingStudy; })(DomainResource); module.exports.ImagingStudy = ImagingStudy; }).call(this); },{"../cql-datatypes":117,"./core":173}],196:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Immunization, ImmunizationExplanationComponent, ImmunizationReactionComponent, ImmunizationVaccinationProtocolComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ImmunizationExplanationComponent @exports ImmunizationExplanationComponent as ImmunizationExplanationComponent */ ImmunizationExplanationComponent = (function(superClass) { extend(ImmunizationExplanationComponent, superClass); function ImmunizationExplanationComponent(json) { this.json = json; ImmunizationExplanationComponent.__super__.constructor.call(this, this.json); } /** Reasons why a vaccine was administered. @returns {Array} an array of {@link CodeableConcept} objects */ ImmunizationExplanationComponent.prototype.reason = function() { var i, item, len, ref, results; if (this.json['reason']) { ref = this.json['reason']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Refusal or exemption reasons. @returns {Array} an array of {@link CodeableConcept} objects */ ImmunizationExplanationComponent.prototype.refusalReason = function() { var i, item, len, ref, results; if (this.json['refusalReason']) { ref = this.json['refusalReason']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; return ImmunizationExplanationComponent; })(BackboneElement); /** Embedded class @class ImmunizationReactionComponent @exports ImmunizationReactionComponent as ImmunizationReactionComponent */ ImmunizationReactionComponent = (function(superClass) { extend(ImmunizationReactionComponent, superClass); function ImmunizationReactionComponent(json) { this.json = json; ImmunizationReactionComponent.__super__.constructor.call(this, this.json); } /** Date of reaction to the immunization. @returns {Array} an array of {@link Date} objects */ ImmunizationReactionComponent.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Details of the reaction. @returns {Reference} */ ImmunizationReactionComponent.prototype.detail = function() { if (this.json['detail']) { return new Reference(this.json['detail']); } }; /** Self-reported indicator. @returns {Array} an array of {@link boolean} objects */ ImmunizationReactionComponent.prototype.reported = function() { return this.json['reported']; }; return ImmunizationReactionComponent; })(BackboneElement); /** Embedded class @class ImmunizationVaccinationProtocolComponent @exports ImmunizationVaccinationProtocolComponent as ImmunizationVaccinationProtocolComponent */ ImmunizationVaccinationProtocolComponent = (function(superClass) { extend(ImmunizationVaccinationProtocolComponent, superClass); function ImmunizationVaccinationProtocolComponent(json) { this.json = json; ImmunizationVaccinationProtocolComponent.__super__.constructor.call(this, this.json); } /** Nominal position in a series. @returns {Array} an array of {@link Number} objects */ ImmunizationVaccinationProtocolComponent.prototype.doseSequence = function() { return this.json['doseSequence']; }; /** Contains the description about the protocol under which the vaccine was administered. @returns {Array} an array of {@link String} objects */ ImmunizationVaccinationProtocolComponent.prototype.description = function() { return this.json['description']; }; /** Indicates the authority who published the protocol? E.g. ACIP. @returns {Reference} */ ImmunizationVaccinationProtocolComponent.prototype.authority = function() { if (this.json['authority']) { return new Reference(this.json['authority']); } }; /** One possible path to achieve presumed immunity against a disease - within the context of an authority. @returns {Array} an array of {@link String} objects */ ImmunizationVaccinationProtocolComponent.prototype.series = function() { return this.json['series']; }; /** The recommended number of doses to achieve immunity. @returns {Array} an array of {@link Number} objects */ ImmunizationVaccinationProtocolComponent.prototype.seriesDoses = function() { return this.json['seriesDoses']; }; /** The targeted disease. @returns {CodeableConcept} */ ImmunizationVaccinationProtocolComponent.prototype.doseTarget = function() { if (this.json['doseTarget']) { return new CodeableConcept(this.json['doseTarget']); } }; /** Indicates if the immunization event should "count" against the protocol. @returns {CodeableConcept} */ ImmunizationVaccinationProtocolComponent.prototype.doseStatus = function() { if (this.json['doseStatus']) { return new CodeableConcept(this.json['doseStatus']); } }; /** Provides an explanation as to why a immunization event should or should not count against the protocol. @returns {CodeableConcept} */ ImmunizationVaccinationProtocolComponent.prototype.doseStatusReason = function() { if (this.json['doseStatusReason']) { return new CodeableConcept(this.json['doseStatusReason']); } }; return ImmunizationVaccinationProtocolComponent; })(BackboneElement); /** Immunization event information. @class Immunization @exports Immunization as Immunization */ Immunization = (function(superClass) { extend(Immunization, superClass); function Immunization(json) { this.json = json; Immunization.__super__.constructor.call(this, this.json); } /** A unique identifier assigned to this adverse reaction record. @returns {Array} an array of {@link Identifier} objects */ Immunization.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Date vaccine administered or was to be administered. @returns {Array} an array of {@link Date} objects */ Immunization.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Vaccine that was administered or was to be administered. @returns {CodeableConcept} */ Immunization.prototype.vaccineType = function() { if (this.json['vaccineType']) { return new CodeableConcept(this.json['vaccineType']); } }; /** The patient to whom the vaccine was to be administered. @returns {Reference} */ Immunization.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Indicates if the vaccination was refused. @returns {Array} an array of {@link boolean} objects */ Immunization.prototype.refusedIndicator = function() { return this.json['refusedIndicator']; }; /** True if this administration was reported rather than directly administered. @returns {Array} an array of {@link boolean} objects */ Immunization.prototype.reported = function() { return this.json['reported']; }; /** Clinician who administered the vaccine. @returns {Reference} */ Immunization.prototype.performer = function() { if (this.json['performer']) { return new Reference(this.json['performer']); } }; /** Clinician who ordered the vaccination. @returns {Reference} */ Immunization.prototype.requester = function() { if (this.json['requester']) { return new Reference(this.json['requester']); } }; /** Name of vaccine manufacturer. @returns {Reference} */ Immunization.prototype.manufacturer = function() { if (this.json['manufacturer']) { return new Reference(this.json['manufacturer']); } }; /** The service delivery location where the vaccine administration occurred. @returns {Reference} */ Immunization.prototype.location = function() { if (this.json['location']) { return new Reference(this.json['location']); } }; /** Lot number of the vaccine product. @returns {Array} an array of {@link String} objects */ Immunization.prototype.lotNumber = function() { return this.json['lotNumber']; }; /** Date vaccine batch expires. @returns {Array} an array of {@link Date} objects */ Immunization.prototype.expirationDate = function() { if (this.json['expirationDate']) { return DT.DateTime.parse(this.json['expirationDate']); } }; /** Body site where vaccine was administered. @returns {CodeableConcept} */ Immunization.prototype.site = function() { if (this.json['site']) { return new CodeableConcept(this.json['site']); } }; /** The path by which the vaccine product is taken into the body. @returns {CodeableConcept} */ Immunization.prototype.route = function() { if (this.json['route']) { return new CodeableConcept(this.json['route']); } }; /** The quantity of vaccine product that was administered. @returns {Quantity} */ Immunization.prototype.doseQuantity = function() { if (this.json['doseQuantity']) { return new Quantity(this.json['doseQuantity']); } }; /** Reasons why a vaccine was administered or refused. @returns {ImmunizationExplanationComponent} */ Immunization.prototype.explanation = function() { if (this.json['explanation']) { return new ImmunizationExplanationComponent(this.json['explanation']); } }; /** Categorical data indicating that an adverse event is associated in time to an immunization. @returns {Array} an array of {@link ImmunizationReactionComponent} objects */ Immunization.prototype.reaction = function() { var i, item, len, ref, results; if (this.json['reaction']) { ref = this.json['reaction']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ImmunizationReactionComponent(item)); } return results; } }; /** Contains information about the protocol(s) under which the vaccine was administered. @returns {Array} an array of {@link ImmunizationVaccinationProtocolComponent} objects */ Immunization.prototype.vaccinationProtocol = function() { var i, item, len, ref, results; if (this.json['vaccinationProtocol']) { ref = this.json['vaccinationProtocol']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ImmunizationVaccinationProtocolComponent(item)); } return results; } }; return Immunization; })(DomainResource); module.exports.Immunization = Immunization; }).call(this); },{"../cql-datatypes":117,"./core":173}],197:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, ImmunizationRecommendation, ImmunizationRecommendationRecommendationComponent, ImmunizationRecommendationRecommendationDateCriterionComponent, ImmunizationRecommendationRecommendationProtocolComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ImmunizationRecommendationRecommendationDateCriterionComponent @exports ImmunizationRecommendationRecommendationDateCriterionComponent as ImmunizationRecommendationRecommendationDateCriterionComponent */ ImmunizationRecommendationRecommendationDateCriterionComponent = (function(superClass) { extend(ImmunizationRecommendationRecommendationDateCriterionComponent, superClass); function ImmunizationRecommendationRecommendationDateCriterionComponent(json) { this.json = json; ImmunizationRecommendationRecommendationDateCriterionComponent.__super__.constructor.call(this, this.json); } /** Date classification of recommendation - e.g. earliest date to give, latest date to give, etc. @returns {CodeableConcept} */ ImmunizationRecommendationRecommendationDateCriterionComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** Date recommendation. @returns {Array} an array of {@link Date} objects */ ImmunizationRecommendationRecommendationDateCriterionComponent.prototype.value = function() { if (this.json['value']) { return DT.DateTime.parse(this.json['value']); } }; return ImmunizationRecommendationRecommendationDateCriterionComponent; })(BackboneElement); /** Embedded class @class ImmunizationRecommendationRecommendationProtocolComponent @exports ImmunizationRecommendationRecommendationProtocolComponent as ImmunizationRecommendationRecommendationProtocolComponent */ ImmunizationRecommendationRecommendationProtocolComponent = (function(superClass) { extend(ImmunizationRecommendationRecommendationProtocolComponent, superClass); function ImmunizationRecommendationRecommendationProtocolComponent(json) { this.json = json; ImmunizationRecommendationRecommendationProtocolComponent.__super__.constructor.call(this, this.json); } /** Indicates the nominal position in a series of the next dose. This is the recommended dose number as per a specified protocol. @returns {Array} an array of {@link Number} objects */ ImmunizationRecommendationRecommendationProtocolComponent.prototype.doseSequence = function() { return this.json['doseSequence']; }; /** Contains the description about the protocol under which the vaccine was administered. @returns {Array} an array of {@link String} objects */ ImmunizationRecommendationRecommendationProtocolComponent.prototype.description = function() { return this.json['description']; }; /** Indicates the authority who published the protocol? E.g. ACIP. @returns {Reference} */ ImmunizationRecommendationRecommendationProtocolComponent.prototype.authority = function() { if (this.json['authority']) { return new Reference(this.json['authority']); } }; /** One possible path to achieve presumed immunity against a disease - within the context of an authority. @returns {Array} an array of {@link String} objects */ ImmunizationRecommendationRecommendationProtocolComponent.prototype.series = function() { return this.json['series']; }; return ImmunizationRecommendationRecommendationProtocolComponent; })(BackboneElement); /** Embedded class @class ImmunizationRecommendationRecommendationComponent @exports ImmunizationRecommendationRecommendationComponent as ImmunizationRecommendationRecommendationComponent */ ImmunizationRecommendationRecommendationComponent = (function(superClass) { extend(ImmunizationRecommendationRecommendationComponent, superClass); function ImmunizationRecommendationRecommendationComponent(json) { this.json = json; ImmunizationRecommendationRecommendationComponent.__super__.constructor.call(this, this.json); } /** The date the immunization recommendation was created. @returns {Array} an array of {@link Date} objects */ ImmunizationRecommendationRecommendationComponent.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Vaccine that pertains to the recommendation. @returns {CodeableConcept} */ ImmunizationRecommendationRecommendationComponent.prototype.vaccineType = function() { if (this.json['vaccineType']) { return new CodeableConcept(this.json['vaccineType']); } }; /** This indicates the next recommended dose number (e.g. dose 2 is the next recommended dose). @returns {Array} an array of {@link Number} objects */ ImmunizationRecommendationRecommendationComponent.prototype.doseNumber = function() { return this.json['doseNumber']; }; /** Vaccine administration status. @returns {CodeableConcept} */ ImmunizationRecommendationRecommendationComponent.prototype.forecastStatus = function() { if (this.json['forecastStatus']) { return new CodeableConcept(this.json['forecastStatus']); } }; /** Vaccine date recommendations - e.g. earliest date to administer, latest date to administer, etc. @returns {Array} an array of {@link ImmunizationRecommendationRecommendationDateCriterionComponent} objects */ ImmunizationRecommendationRecommendationComponent.prototype.dateCriterion = function() { var i, item, len, ref, results; if (this.json['dateCriterion']) { ref = this.json['dateCriterion']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ImmunizationRecommendationRecommendationDateCriterionComponent(item)); } return results; } }; /** Contains information about the protocol under which the vaccine was administered. @returns {ImmunizationRecommendationRecommendationProtocolComponent} */ ImmunizationRecommendationRecommendationComponent.prototype.protocol = function() { if (this.json['protocol']) { return new ImmunizationRecommendationRecommendationProtocolComponent(this.json['protocol']); } }; /** Immunization event history that supports the status and recommendation. @returns {Array} an array of {@link Reference} objects */ ImmunizationRecommendationRecommendationComponent.prototype.supportingImmunization = function() { var i, item, len, ref, results; if (this.json['supportingImmunization']) { ref = this.json['supportingImmunization']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Patient Information that supports the status and recommendation. This includes patient observations, adverse reactions and allergy/intolerance information. @returns {Array} an array of {@link Reference} objects */ ImmunizationRecommendationRecommendationComponent.prototype.supportingPatientInformation = function() { var i, item, len, ref, results; if (this.json['supportingPatientInformation']) { ref = this.json['supportingPatientInformation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return ImmunizationRecommendationRecommendationComponent; })(BackboneElement); /** A patient's point-of-time immunization status and recommendation with optional supporting justification. @class ImmunizationRecommendation @exports ImmunizationRecommendation as ImmunizationRecommendation */ ImmunizationRecommendation = (function(superClass) { extend(ImmunizationRecommendation, superClass); function ImmunizationRecommendation(json) { this.json = json; ImmunizationRecommendation.__super__.constructor.call(this, this.json); } /** A unique identifier assigned to this particular recommendation record. @returns {Array} an array of {@link Identifier} objects */ ImmunizationRecommendation.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The patient who is the subject of the profile. @returns {Reference} */ ImmunizationRecommendation.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Vaccine administration recommendations. @returns {Array} an array of {@link ImmunizationRecommendationRecommendationComponent} objects */ ImmunizationRecommendation.prototype.recommendation = function() { var i, item, len, ref, results; if (this.json['recommendation']) { ref = this.json['recommendation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ImmunizationRecommendationRecommendationComponent(item)); } return results; } }; return ImmunizationRecommendation; })(DomainResource); module.exports.ImmunizationRecommendation = ImmunizationRecommendation; }).call(this); },{"../cql-datatypes":117,"./core":173}],198:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, List, ListEntryComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ListEntryComponent @exports ListEntryComponent as ListEntryComponent */ ListEntryComponent = (function(superClass) { extend(ListEntryComponent, superClass); function ListEntryComponent(json) { this.json = json; ListEntryComponent.__super__.constructor.call(this, this.json); } /** The flag allows the system constructing the list to make one or more statements about the role and significance of the item in the list. @returns {Array} an array of {@link CodeableConcept} objects */ ListEntryComponent.prototype.flag = function() { var i, item, len, ref, results; if (this.json['flag']) { ref = this.json['flag']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** True if this item is marked as deleted in the list. @returns {Array} an array of {@link boolean} objects */ ListEntryComponent.prototype.deleted = function() { return this.json['deleted']; }; /** When this item was added to the list. @returns {Array} an array of {@link Date} objects */ ListEntryComponent.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** A reference to the actual resource from which data was derived. @returns {Reference} */ ListEntryComponent.prototype.item = function() { if (this.json['item']) { return new Reference(this.json['item']); } }; return ListEntryComponent; })(BackboneElement); /** A set of information summarized from a list of other resources. @class List @exports List as List */ List = (function(superClass) { extend(List, superClass); function List(json) { this.json = json; List.__super__.constructor.call(this, this.json); } /** Identifier for the List assigned for business purposes outside the context of FHIR. @returns {Array} an array of {@link Identifier} objects */ List.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** This code defines the purpose of the list - why it was created. @returns {CodeableConcept} */ List.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** The common subject (or patient) of the resources that are in the list, if there is one. @returns {Reference} */ List.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The entity responsible for deciding what the contents of the list were. @returns {Reference} */ List.prototype.source = function() { if (this.json['source']) { return new Reference(this.json['source']); } }; /** The date that the list was prepared. @returns {Array} an array of {@link Date} objects */ List.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Whether items in the list have a meaningful order. @returns {Array} an array of {@link boolean} objects */ List.prototype.ordered = function() { return this.json['ordered']; }; /** How this list was prepared - whether it is a working list that is suitable for being maintained on an ongoing basis, or if it represents a snapshot of a list of items from another source, or whether it is a prepared list where items may be marked as added, modified or deleted. @returns {Array} an array of {@link String} objects */ List.prototype.mode = function() { return this.json['mode']; }; /** Entries in this list. @returns {Array} an array of {@link ListEntryComponent} objects */ List.prototype.entry = function() { var i, item, len, ref, results; if (this.json['entry']) { ref = this.json['entry']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ListEntryComponent(item)); } return results; } }; /** If the list is empty, why the list is empty. @returns {CodeableConcept} */ List.prototype.emptyReason = function() { if (this.json['emptyReason']) { return new CodeableConcept(this.json['emptyReason']); } }; return List; })(DomainResource); module.exports.List = List; }).call(this); },{"../cql-datatypes":117,"./core":173}],199:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Location, LocationPositionComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class LocationPositionComponent @exports LocationPositionComponent as LocationPositionComponent */ LocationPositionComponent = (function(superClass) { extend(LocationPositionComponent, superClass); function LocationPositionComponent(json) { this.json = json; LocationPositionComponent.__super__.constructor.call(this, this.json); } /** Longitude. The value domain and the interpretation are the same as for the text of the longitude element in KML (see notes below). @returns {Array} an array of {@link Number} objects */ LocationPositionComponent.prototype.longitude = function() { return this.json['longitude']; }; /** Latitude. The value domain and the interpretation are the same as for the text of the latitude element in KML (see notes below). @returns {Array} an array of {@link Number} objects */ LocationPositionComponent.prototype.latitude = function() { return this.json['latitude']; }; /** Altitude. The value domain and the interpretation are the same as for the text of the altitude element in KML (see notes below). @returns {Array} an array of {@link Number} objects */ LocationPositionComponent.prototype.altitude = function() { return this.json['altitude']; }; return LocationPositionComponent; })(BackboneElement); /** Details and position information for a physical place where services are provided and resources and participants may be stored, found, contained or accommodated. @class Location @exports Location as Location */ Location = (function(superClass) { extend(Location, superClass); function Location(json) { this.json = json; Location.__super__.constructor.call(this, this.json); } /** Unique code or number identifying the location to its users. @returns {Array} an array of {@link Identifier} objects */ Location.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Name of the location as used by humans. Does not need to be unique. @returns {Array} an array of {@link String} objects */ Location.prototype.name = function() { return this.json['name']; }; /** Description of the Location, which helps in finding or referencing the place. @returns {Array} an array of {@link String} objects */ Location.prototype.description = function() { return this.json['description']; }; /** Indicates the type of function performed at the location. @returns {CodeableConcept} */ Location.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The contact details of communication devices available at the location. This can include phone numbers, fax numbers, mobile numbers, email addresses and web sites. @returns {Array} an array of {@link ContactPoint} objects */ Location.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** Physical location. @returns {Address} */ Location.prototype.address = function() { if (this.json['address']) { return new Address(this.json['address']); } }; /** Physical form of the location, e.g. building, room, vehicle, road. @returns {CodeableConcept} */ Location.prototype.physicalType = function() { if (this.json['physicalType']) { return new CodeableConcept(this.json['physicalType']); } }; /** The absolute geographic location of the Location, expressed in a KML compatible manner (see notes below for KML). @returns {LocationPositionComponent} */ Location.prototype.position = function() { if (this.json['position']) { return new LocationPositionComponent(this.json['position']); } }; /** The organization that is responsible for the provisioning and upkeep of the location. @returns {Reference} */ Location.prototype.managingOrganization = function() { if (this.json['managingOrganization']) { return new Reference(this.json['managingOrganization']); } }; /** active | suspended | inactive. @returns {Array} an array of {@link String} objects */ Location.prototype.status = function() { return this.json['status']; }; /** Another Location which this Location is physically part of. @returns {Reference} */ Location.prototype.partOf = function() { if (this.json['partOf']) { return new Reference(this.json['partOf']); } }; /** Indicates whether a resource instance represents a specific location or a class of locations. @returns {Array} an array of {@link String} objects */ Location.prototype.mode = function() { return this.json['mode']; }; return Location; })(DomainResource); module.exports.Location = Location; }).call(this); },{"../cql-datatypes":117,"./core":173}],200:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Media, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A photo, video, or audio recording acquired or used in healthcare. The actual content may be inline or provided by direct reference. @class Media @exports Media as Media */ Media = (function(superClass) { extend(Media, superClass); function Media(json) { this.json = json; Media.__super__.constructor.call(this, this.json); } /** Whether the media is a photo (still image), an audio recording, or a video recording. @returns {Array} an array of {@link String} objects */ Media.prototype.type = function() { return this.json['type']; }; /** Details of the type of the media - usually, how it was acquired (what type of device). If images sourced from a DICOM system, are wrapped in a Media resource, then this is the modality. @returns {CodeableConcept} */ Media.prototype.subtype = function() { if (this.json['subtype']) { return new CodeableConcept(this.json['subtype']); } }; /** Identifiers associated with the image - these may include identifiers for the image itself, identifiers for the context of its collection (e.g. series ids) and context ids such as accession numbers or other workflow identifiers. @returns {Array} an array of {@link Identifier} objects */ Media.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The date/time when the media was originally recorded. For video and audio, if the length of the recording is not insignificant, this is the start of the recording. @returns {Array} an array of {@link Date} objects */ Media.prototype.created = function() { if (this.json['created']) { return DT.DateTime.parse(this.json['created']); } }; /** Who/What this Media is a record of. @returns {Reference} */ Media.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The person who administered the collection of the image. @returns {Reference} */ Media.prototype.operator = function() { if (this.json['operator']) { return new Reference(this.json['operator']); } }; /** The name of the imaging view e.g Lateral or Antero-posterior (AP). @returns {CodeableConcept} */ Media.prototype.view = function() { if (this.json['view']) { return new CodeableConcept(this.json['view']); } }; /** The name of the device / manufacturer of the device that was used to make the recording. @returns {Array} an array of {@link String} objects */ Media.prototype.deviceName = function() { return this.json['deviceName']; }; /** Height of the image in pixels(photo/video). @returns {Array} an array of {@link Number} objects */ Media.prototype.height = function() { return this.json['height']; }; /** Width of the image in pixels (photo/video). @returns {Array} an array of {@link Number} objects */ Media.prototype.width = function() { return this.json['width']; }; /** The number of frames in a photo. This is used with a multi-page fax, or an imaging acquisition context that takes multiple slices in a single image, or an animated gif. If there is more than one frame, this SHALL have a value in order to alert interface software that a multi-frame capable rendering widget is required. @returns {Array} an array of {@link Number} objects */ Media.prototype.frames = function() { return this.json['frames']; }; /** The duration of the recording in seconds - for audio and video. @returns {Array} an array of {@link Number} objects */ Media.prototype.duration = function() { return this.json['duration']; }; /** The actual content of the media - inline or by direct reference to the media source file. @returns {Attachment} */ Media.prototype.content = function() { if (this.json['content']) { return new Attachment(this.json['content']); } }; return Media; })(DomainResource); module.exports.Media = Media; }).call(this); },{"../cql-datatypes":117,"./core":173}],201:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Medication, MedicationPackageComponent, MedicationPackageContentComponent, MedicationProductComponent, MedicationProductIngredientComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class MedicationProductIngredientComponent @exports MedicationProductIngredientComponent as MedicationProductIngredientComponent */ MedicationProductIngredientComponent = (function(superClass) { extend(MedicationProductIngredientComponent, superClass); function MedicationProductIngredientComponent(json) { this.json = json; MedicationProductIngredientComponent.__super__.constructor.call(this, this.json); } /** The actual ingredient - either a substance (simple ingredient) or another medication. @returns {Reference} */ MedicationProductIngredientComponent.prototype.item = function() { if (this.json['item']) { return new Reference(this.json['item']); } }; /** Specifies how many (or how much) of the items there are in this Medication. E.g. 250 mg per tablet. @returns {Ratio} */ MedicationProductIngredientComponent.prototype.amount = function() { if (this.json['amount']) { return new Ratio(this.json['amount']); } }; return MedicationProductIngredientComponent; })(BackboneElement); /** Embedded class @class MedicationProductComponent @exports MedicationProductComponent as MedicationProductComponent */ MedicationProductComponent = (function(superClass) { extend(MedicationProductComponent, superClass); function MedicationProductComponent(json) { this.json = json; MedicationProductComponent.__super__.constructor.call(this, this.json); } /** Describes the form of the item. Powder; tables; carton. @returns {CodeableConcept} */ MedicationProductComponent.prototype.form = function() { if (this.json['form']) { return new CodeableConcept(this.json['form']); } }; /** Identifies a particular constituent of interest in the product. @returns {Array} an array of {@link MedicationProductIngredientComponent} objects */ MedicationProductComponent.prototype.ingredient = function() { var i, item, len, ref, results; if (this.json['ingredient']) { ref = this.json['ingredient']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MedicationProductIngredientComponent(item)); } return results; } }; return MedicationProductComponent; })(BackboneElement); /** Embedded class @class MedicationPackageContentComponent @exports MedicationPackageContentComponent as MedicationPackageContentComponent */ MedicationPackageContentComponent = (function(superClass) { extend(MedicationPackageContentComponent, superClass); function MedicationPackageContentComponent(json) { this.json = json; MedicationPackageContentComponent.__super__.constructor.call(this, this.json); } /** Identifies one of the items in the package. @returns {Reference} */ MedicationPackageContentComponent.prototype.item = function() { if (this.json['item']) { return new Reference(this.json['item']); } }; /** The amount of the product that is in the package. @returns {Quantity} */ MedicationPackageContentComponent.prototype.amount = function() { if (this.json['amount']) { return new Quantity(this.json['amount']); } }; return MedicationPackageContentComponent; })(BackboneElement); /** Embedded class @class MedicationPackageComponent @exports MedicationPackageComponent as MedicationPackageComponent */ MedicationPackageComponent = (function(superClass) { extend(MedicationPackageComponent, superClass); function MedicationPackageComponent(json) { this.json = json; MedicationPackageComponent.__super__.constructor.call(this, this.json); } /** The kind of container that this package comes as. @returns {CodeableConcept} */ MedicationPackageComponent.prototype.container = function() { if (this.json['container']) { return new CodeableConcept(this.json['container']); } }; /** A set of components that go to make up the described item. @returns {Array} an array of {@link MedicationPackageContentComponent} objects */ MedicationPackageComponent.prototype.content = function() { var i, item, len, ref, results; if (this.json['content']) { ref = this.json['content']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MedicationPackageContentComponent(item)); } return results; } }; return MedicationPackageComponent; })(BackboneElement); /** Primarily used for identification and definition of Medication, but also covers ingredients and packaging. @class Medication @exports Medication as Medication */ Medication = (function(superClass) { extend(Medication, superClass); function Medication(json) { this.json = json; Medication.__super__.constructor.call(this, this.json); } /** The common/commercial name of the medication absent information such as strength, form, etc. E.g. Acetaminophen, Tylenol 3, etc. The fully coordinated name is communicated as the display of Medication.code. @returns {Array} an array of {@link String} objects */ Medication.prototype.name = function() { return this.json['name']; }; /** A code (or set of codes) that identify this medication. Usage note: This could be a standard drug code such as a drug regulator code, RxNorm code, SNOMED CT code, etc. It could also be a local formulary code, optionally with translations to the standard drug codes. @returns {CodeableConcept} */ Medication.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** Set to true if the item is attributable to a specific manufacturer (even if we don't know who that is). @returns {Array} an array of {@link boolean} objects */ Medication.prototype.isBrand = function() { return this.json['isBrand']; }; /** Describes the details of the manufacturer. @returns {Reference} */ Medication.prototype.manufacturer = function() { if (this.json['manufacturer']) { return new Reference(this.json['manufacturer']); } }; /** Medications are either a single administrable product or a package that contains one or more products. @returns {Array} an array of {@link String} objects */ Medication.prototype.kind = function() { return this.json['kind']; }; /** Information that only applies to products (not packages). @returns {MedicationProductComponent} */ Medication.prototype.product = function() { if (this.json['product']) { return new MedicationProductComponent(this.json['product']); } }; /** Information that only applies to packages (not products). @returns {MedicationPackageComponent} */ Medication.prototype["package"] = function() { if (this.json['package']) { return new MedicationPackageComponent(this.json['package']); } }; return Medication; })(DomainResource); module.exports.Medication = Medication; }).call(this); },{"../cql-datatypes":117,"./core":173}],202:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, MedicationAdministration, MedicationAdministrationDosageComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class MedicationAdministrationDosageComponent @exports MedicationAdministrationDosageComponent as MedicationAdministrationDosageComponent */ MedicationAdministrationDosageComponent = (function(superClass) { extend(MedicationAdministrationDosageComponent, superClass); function MedicationAdministrationDosageComponent(json) { this.json = json; MedicationAdministrationDosageComponent.__super__.constructor.call(this, this.json); } /** The timing schedule for giving the medication to the patient. This may be a single time point (using dateTime) or it may be a start and end dateTime (Period). @returns {Array} an array of {@link Date} objects */ MedicationAdministrationDosageComponent.prototype.timingDateTime = function() { if (this.json['timingDateTime']) { return DT.DateTime.parse(this.json['timingDateTime']); } }; /** The timing schedule for giving the medication to the patient. This may be a single time point (using dateTime) or it may be a start and end dateTime (Period). @returns {Period} */ MedicationAdministrationDosageComponent.prototype.timingPeriod = function() { if (this.json['timingPeriod']) { return new Period(this.json['timingPeriod']); } }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {Array} an array of {@link boolean} objects */ MedicationAdministrationDosageComponent.prototype.asNeededBoolean = function() { return this.json['asNeededBoolean']; }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {CodeableConcept} */ MedicationAdministrationDosageComponent.prototype.asNeededCodeableConcept = function() { if (this.json['asNeededCodeableConcept']) { return new CodeableConcept(this.json['asNeededCodeableConcept']); } }; /** A coded specification of the anatomic site where the medication first entered the body. E.g. "left arm". @returns {CodeableConcept} */ MedicationAdministrationDosageComponent.prototype.site = function() { if (this.json['site']) { return new CodeableConcept(this.json['site']); } }; /** A code specifying the route or physiological path of administration of a therapeutic agent into or onto the patient. E.g. topical, intravenous, etc. @returns {CodeableConcept} */ MedicationAdministrationDosageComponent.prototype.route = function() { if (this.json['route']) { return new CodeableConcept(this.json['route']); } }; /** A coded value indicating the method by which the medication was introduced into or onto the body. Most commonly used for injections. Examples: Slow Push; Deep IV. Terminologies used often pre-coordinate this term with the route and or form of administration. @returns {CodeableConcept} */ MedicationAdministrationDosageComponent.prototype.method = function() { if (this.json['method']) { return new CodeableConcept(this.json['method']); } }; /** The amount of the medication given at one administration event. Use this value when the administration is essentially an instantaneous event such as a swallowing a tablet or giving an injection. @returns {Quantity} */ MedicationAdministrationDosageComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** Identifies the speed with which the medication was introduced into the patient. Typically the rate for an infusion e.g. 200ml in 2 hours. May also expressed as a rate per unit of time such as 100ml per hour - the duration is then not specified, or is specified in the quantity. @returns {Ratio} */ MedicationAdministrationDosageComponent.prototype.rate = function() { if (this.json['rate']) { return new Ratio(this.json['rate']); } }; /** The maximum total quantity of a therapeutic substance that was administered to the patient over the specified period of time. E.g. 1000mg in 24 hours. @returns {Ratio} */ MedicationAdministrationDosageComponent.prototype.maxDosePerPeriod = function() { if (this.json['maxDosePerPeriod']) { return new Ratio(this.json['maxDosePerPeriod']); } }; return MedicationAdministrationDosageComponent; })(BackboneElement); /** Describes the event of a patient being given a dose of a medication. This may be as simple as swallowing a tablet or it may be a long running infusion. Related resources tie this event to the authorizing prescription, and the specific encounter between patient and health care practitioner. @class MedicationAdministration @exports MedicationAdministration as MedicationAdministration */ MedicationAdministration = (function(superClass) { extend(MedicationAdministration, superClass); function MedicationAdministration(json) { this.json = json; MedicationAdministration.__super__.constructor.call(this, this.json); } /** External identifier - FHIR will generate its own internal IDs (probably URLs) which do not need to be explicitly managed by the resource. The identifier here is one that would be used by another non-FHIR system - for example an automated medication pump would provide a record each time it operated; an administration while the patient was off the ward might be made with a different system and entered after the event. Particularly important if these records have to be updated. @returns {Array} an array of {@link Identifier} objects */ MedicationAdministration.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Will generally be set to show that the administration has been completed. For some long running administrations such as infusions it is possible for an administration to be started but not completed or it may be paused while some other process is under way. @returns {Array} an array of {@link String} objects */ MedicationAdministration.prototype.status = function() { return this.json['status']; }; /** The person or animal to whom the medication was given. @returns {Reference} */ MedicationAdministration.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The individual who was responsible for giving the medication to the patient. @returns {Reference} */ MedicationAdministration.prototype.practitioner = function() { if (this.json['practitioner']) { return new Reference(this.json['practitioner']); } }; /** The visit or admission the or other contact between patient and health care provider the medication administration was performed as part of. @returns {Reference} */ MedicationAdministration.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** The original request, instruction or authority to perform the administration. @returns {Reference} */ MedicationAdministration.prototype.prescription = function() { if (this.json['prescription']) { return new Reference(this.json['prescription']); } }; /** Set this to true if the record is saying that the medication was NOT administered. @returns {Array} an array of {@link boolean} objects */ MedicationAdministration.prototype.wasNotGiven = function() { return this.json['wasNotGiven']; }; /** A code indicating why the administration was not performed. @returns {Array} an array of {@link CodeableConcept} objects */ MedicationAdministration.prototype.reasonNotGiven = function() { var i, item, len, ref, results; if (this.json['reasonNotGiven']) { ref = this.json['reasonNotGiven']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** An interval of time during which the administration took place. For many administrations, such as swallowing a tablet the lower and upper values of the interval will be the same. @returns {Array} an array of {@link Date} objects */ MedicationAdministration.prototype.effectiveTimeDateTime = function() { if (this.json['effectiveTimeDateTime']) { return DT.DateTime.parse(this.json['effectiveTimeDateTime']); } }; /** An interval of time during which the administration took place. For many administrations, such as swallowing a tablet the lower and upper values of the interval will be the same. @returns {Period} */ MedicationAdministration.prototype.effectiveTimePeriod = function() { if (this.json['effectiveTimePeriod']) { return new Period(this.json['effectiveTimePeriod']); } }; /** Identifies the medication that was administered. This is either a link to a resource representing the details of the medication or a simple attribute carrying a code that identifies the medication from a known list of medications. @returns {Reference} */ MedicationAdministration.prototype.medication = function() { if (this.json['medication']) { return new Reference(this.json['medication']); } }; /** The device used in administering the medication to the patient. E.g. a particular infusion pump. @returns {Array} an array of {@link Reference} objects */ MedicationAdministration.prototype.device = function() { var i, item, len, ref, results; if (this.json['device']) { ref = this.json['device']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Provides details of how much of the medication was administered. @returns {Array} an array of {@link MedicationAdministrationDosageComponent} objects */ MedicationAdministration.prototype.dosage = function() { var i, item, len, ref, results; if (this.json['dosage']) { ref = this.json['dosage']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MedicationAdministrationDosageComponent(item)); } return results; } }; return MedicationAdministration; })(DomainResource); module.exports.MedicationAdministration = MedicationAdministration; }).call(this); },{"../cql-datatypes":117,"./core":173}],203:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, MedicationDispense, MedicationDispenseDispenseComponent, MedicationDispenseDispenseDosageComponent, MedicationDispenseSubstitutionComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class MedicationDispenseDispenseDosageComponent @exports MedicationDispenseDispenseDosageComponent as MedicationDispenseDispenseDosageComponent */ MedicationDispenseDispenseDosageComponent = (function(superClass) { extend(MedicationDispenseDispenseDosageComponent, superClass); function MedicationDispenseDispenseDosageComponent(json) { this.json = json; MedicationDispenseDispenseDosageComponent.__super__.constructor.call(this, this.json); } /** Additional instructions such as "Swallow with plenty of water" which may or may not be coded. @returns {CodeableConcept} */ MedicationDispenseDispenseDosageComponent.prototype.additionalInstructions = function() { if (this.json['additionalInstructions']) { return new CodeableConcept(this.json['additionalInstructions']); } }; /** The timing schedule for giving the medication to the patient. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Array} an array of {@link Date} objects */ MedicationDispenseDispenseDosageComponent.prototype.scheduleDateTime = function() { if (this.json['scheduleDateTime']) { return DT.DateTime.parse(this.json['scheduleDateTime']); } }; /** The timing schedule for giving the medication to the patient. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Period} */ MedicationDispenseDispenseDosageComponent.prototype.schedulePeriod = function() { if (this.json['schedulePeriod']) { return new Period(this.json['schedulePeriod']); } }; /** The timing schedule for giving the medication to the patient. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Timing} */ MedicationDispenseDispenseDosageComponent.prototype.scheduleTiming = function() { if (this.json['scheduleTiming']) { return new Timing(this.json['scheduleTiming']); } }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {Array} an array of {@link boolean} objects */ MedicationDispenseDispenseDosageComponent.prototype.asNeededBoolean = function() { return this.json['asNeededBoolean']; }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {CodeableConcept} */ MedicationDispenseDispenseDosageComponent.prototype.asNeededCodeableConcept = function() { if (this.json['asNeededCodeableConcept']) { return new CodeableConcept(this.json['asNeededCodeableConcept']); } }; /** A coded specification of the anatomic site where the medication first enters the body. @returns {CodeableConcept} */ MedicationDispenseDispenseDosageComponent.prototype.site = function() { if (this.json['site']) { return new CodeableConcept(this.json['site']); } }; /** A code specifying the route or physiological path of administration of a therapeutic agent into or onto a subject. @returns {CodeableConcept} */ MedicationDispenseDispenseDosageComponent.prototype.route = function() { if (this.json['route']) { return new CodeableConcept(this.json['route']); } }; /** A coded value indicating the method by which the medication is introduced into or onto the body. Most commonly used for injections. Examples: Slow Push; Deep IV. Terminologies used often pre-coordinate this term with the route and or form of administration. @returns {CodeableConcept} */ MedicationDispenseDispenseDosageComponent.prototype.method = function() { if (this.json['method']) { return new CodeableConcept(this.json['method']); } }; /** The amount of therapeutic or other substance given at one administration event. @returns {Quantity} */ MedicationDispenseDispenseDosageComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** Identifies the speed with which the substance is introduced into the subject. Typically the rate for an infusion. 200ml in 2 hours. @returns {Ratio} */ MedicationDispenseDispenseDosageComponent.prototype.rate = function() { if (this.json['rate']) { return new Ratio(this.json['rate']); } }; /** The maximum total quantity of a therapeutic substance that may be administered to a subject over the period of time, e.g. 1000mg in 24 hours. @returns {Ratio} */ MedicationDispenseDispenseDosageComponent.prototype.maxDosePerPeriod = function() { if (this.json['maxDosePerPeriod']) { return new Ratio(this.json['maxDosePerPeriod']); } }; return MedicationDispenseDispenseDosageComponent; })(BackboneElement); /** Embedded class @class MedicationDispenseDispenseComponent @exports MedicationDispenseDispenseComponent as MedicationDispenseDispenseComponent */ MedicationDispenseDispenseComponent = (function(superClass) { extend(MedicationDispenseDispenseComponent, superClass); function MedicationDispenseDispenseComponent(json) { this.json = json; MedicationDispenseDispenseComponent.__super__.constructor.call(this, this.json); } /** Identifier assigned by the dispensing facility. This is an identifier assigned outside FHIR. @returns {Identifier} */ MedicationDispenseDispenseComponent.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** A code specifying the state of the dispense event. @returns {Array} an array of {@link String} objects */ MedicationDispenseDispenseComponent.prototype.status = function() { return this.json['status']; }; /** Indicates the type of dispensing event that is performed. Examples include: Trial Fill, Completion of Trial, Partial Fill, Emergency Fill, Samples, etc. @returns {CodeableConcept} */ MedicationDispenseDispenseComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The amount of medication that has been dispensed. Includes unit of measure. @returns {Quantity} */ MedicationDispenseDispenseComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** Identifies the medication being administered. This is either a link to a resource representing the details of the medication or a simple attribute carrying a code that identifies the medication from a known list of medications. @returns {Reference} */ MedicationDispenseDispenseComponent.prototype.medication = function() { if (this.json['medication']) { return new Reference(this.json['medication']); } }; /** The time when the dispensed product was packaged and reviewed. @returns {Array} an array of {@link Date} objects */ MedicationDispenseDispenseComponent.prototype.whenPrepared = function() { if (this.json['whenPrepared']) { return DT.DateTime.parse(this.json['whenPrepared']); } }; /** The time the dispensed product was provided to the patient or their representative. @returns {Array} an array of {@link Date} objects */ MedicationDispenseDispenseComponent.prototype.whenHandedOver = function() { if (this.json['whenHandedOver']) { return DT.DateTime.parse(this.json['whenHandedOver']); } }; /** Identification of the facility/location where the medication was shipped to, as part of the dispense event. @returns {Reference} */ MedicationDispenseDispenseComponent.prototype.destination = function() { if (this.json['destination']) { return new Reference(this.json['destination']); } }; /** Identifies the person who picked up the medication. This will usually be a patient or their carer, but some cases exist where it can be a healthcare professional. @returns {Array} an array of {@link Reference} objects */ MedicationDispenseDispenseComponent.prototype.receiver = function() { var i, item, len, ref, results; if (this.json['receiver']) { ref = this.json['receiver']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Indicates how the medication is to be used by the patient. @returns {Array} an array of {@link MedicationDispenseDispenseDosageComponent} objects */ MedicationDispenseDispenseComponent.prototype.dosage = function() { var i, item, len, ref, results; if (this.json['dosage']) { ref = this.json['dosage']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MedicationDispenseDispenseDosageComponent(item)); } return results; } }; return MedicationDispenseDispenseComponent; })(BackboneElement); /** Embedded class @class MedicationDispenseSubstitutionComponent @exports MedicationDispenseSubstitutionComponent as MedicationDispenseSubstitutionComponent */ MedicationDispenseSubstitutionComponent = (function(superClass) { extend(MedicationDispenseSubstitutionComponent, superClass); function MedicationDispenseSubstitutionComponent(json) { this.json = json; MedicationDispenseSubstitutionComponent.__super__.constructor.call(this, this.json); } /** A code signifying whether a different drug was dispensed from what was prescribed. @returns {CodeableConcept} */ MedicationDispenseSubstitutionComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Indicates the reason for the substitution of (or lack of substitution) from what was prescribed. @returns {Array} an array of {@link CodeableConcept} objects */ MedicationDispenseSubstitutionComponent.prototype.reason = function() { var i, item, len, ref, results; if (this.json['reason']) { ref = this.json['reason']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The person or organization that has primary responsibility for the substitution. @returns {Array} an array of {@link Reference} objects */ MedicationDispenseSubstitutionComponent.prototype.responsibleParty = function() { var i, item, len, ref, results; if (this.json['responsibleParty']) { ref = this.json['responsibleParty']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return MedicationDispenseSubstitutionComponent; })(BackboneElement); /** Dispensing a medication to a named patient. This includes a description of the supply provided and the instructions for administering the medication. @class MedicationDispense @exports MedicationDispense as MedicationDispense */ MedicationDispense = (function(superClass) { extend(MedicationDispense, superClass); function MedicationDispense(json) { this.json = json; MedicationDispense.__super__.constructor.call(this, this.json); } /** Identifier assigned by the dispensing facility - this is an identifier assigned outside FHIR. @returns {Identifier} */ MedicationDispense.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** A code specifying the state of the set of dispense events. @returns {Array} an array of {@link String} objects */ MedicationDispense.prototype.status = function() { return this.json['status']; }; /** A link to a resource representing the person to whom the medication will be given. @returns {Reference} */ MedicationDispense.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The individual responsible for dispensing the medication. @returns {Reference} */ MedicationDispense.prototype.dispenser = function() { if (this.json['dispenser']) { return new Reference(this.json['dispenser']); } }; /** Indicates the medication order that is being dispensed against. @returns {Array} an array of {@link Reference} objects */ MedicationDispense.prototype.authorizingPrescription = function() { var i, item, len, ref, results; if (this.json['authorizingPrescription']) { ref = this.json['authorizingPrescription']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Indicates the details of the dispense event such as the days supply and quantity of medication dispensed. @returns {Array} an array of {@link MedicationDispenseDispenseComponent} objects */ MedicationDispense.prototype.dispense = function() { var i, item, len, ref, results; if (this.json['dispense']) { ref = this.json['dispense']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MedicationDispenseDispenseComponent(item)); } return results; } }; /** Indicates whether or not substitution was made as part of the dispense. In some cases substitution will be expected but doesn't happen, in other cases substitution is not expected but does happen. This block explains what substitition did or did not happen and why. @returns {MedicationDispenseSubstitutionComponent} */ MedicationDispense.prototype.substitution = function() { if (this.json['substitution']) { return new MedicationDispenseSubstitutionComponent(this.json['substitution']); } }; return MedicationDispense; })(DomainResource); module.exports.MedicationDispense = MedicationDispense; }).call(this); },{"../cql-datatypes":117,"./core":173}],204:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, MedicationPrescription, MedicationPrescriptionDispenseComponent, MedicationPrescriptionDosageInstructionComponent, MedicationPrescriptionSubstitutionComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class MedicationPrescriptionDosageInstructionComponent @exports MedicationPrescriptionDosageInstructionComponent as MedicationPrescriptionDosageInstructionComponent */ MedicationPrescriptionDosageInstructionComponent = (function(superClass) { extend(MedicationPrescriptionDosageInstructionComponent, superClass); function MedicationPrescriptionDosageInstructionComponent(json) { this.json = json; MedicationPrescriptionDosageInstructionComponent.__super__.constructor.call(this, this.json); } /** Free text dosage instructions for cases where the instructions are too complex to code. @returns {Array} an array of {@link String} objects */ MedicationPrescriptionDosageInstructionComponent.prototype.text = function() { return this.json['text']; }; /** Additional instructions such as "Swallow with plenty of water" which may or may not be coded. @returns {CodeableConcept} */ MedicationPrescriptionDosageInstructionComponent.prototype.additionalInstructions = function() { if (this.json['additionalInstructions']) { return new CodeableConcept(this.json['additionalInstructions']); } }; /** The timing schedule for giving the medication to the patient. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Array} an array of {@link Date} objects */ MedicationPrescriptionDosageInstructionComponent.prototype.scheduledDateTime = function() { if (this.json['scheduledDateTime']) { return DT.DateTime.parse(this.json['scheduledDateTime']); } }; /** The timing schedule for giving the medication to the patient. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Period} */ MedicationPrescriptionDosageInstructionComponent.prototype.scheduledPeriod = function() { if (this.json['scheduledPeriod']) { return new Period(this.json['scheduledPeriod']); } }; /** The timing schedule for giving the medication to the patient. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Timing} */ MedicationPrescriptionDosageInstructionComponent.prototype.scheduledTiming = function() { if (this.json['scheduledTiming']) { return new Timing(this.json['scheduledTiming']); } }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {Array} an array of {@link boolean} objects */ MedicationPrescriptionDosageInstructionComponent.prototype.asNeededBoolean = function() { return this.json['asNeededBoolean']; }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {CodeableConcept} */ MedicationPrescriptionDosageInstructionComponent.prototype.asNeededCodeableConcept = function() { if (this.json['asNeededCodeableConcept']) { return new CodeableConcept(this.json['asNeededCodeableConcept']); } }; /** A coded specification of the anatomic site where the medication first enters the body. @returns {CodeableConcept} */ MedicationPrescriptionDosageInstructionComponent.prototype.site = function() { if (this.json['site']) { return new CodeableConcept(this.json['site']); } }; /** A code specifying the route or physiological path of administration of a therapeutic agent into or onto a patient. @returns {CodeableConcept} */ MedicationPrescriptionDosageInstructionComponent.prototype.route = function() { if (this.json['route']) { return new CodeableConcept(this.json['route']); } }; /** A coded value indicating the method by which the medication is introduced into or onto the body. Most commonly used for injections. Examples: Slow Push; Deep IV. Terminologies used often pre-coordinate this term with the route and or form of administration. @returns {CodeableConcept} */ MedicationPrescriptionDosageInstructionComponent.prototype.method = function() { if (this.json['method']) { return new CodeableConcept(this.json['method']); } }; /** The amount of therapeutic or other substance given at one administration event. @returns {Quantity} */ MedicationPrescriptionDosageInstructionComponent.prototype.doseQuantity = function() { if (this.json['doseQuantity']) { return new Quantity(this.json['doseQuantity']); } }; /** Identifies the speed with which the substance is introduced into the subject. Typically the rate for an infusion. 200ml in 2 hours. @returns {Ratio} */ MedicationPrescriptionDosageInstructionComponent.prototype.rate = function() { if (this.json['rate']) { return new Ratio(this.json['rate']); } }; /** The maximum total quantity of a therapeutic substance that may be administered to a subject over the period of time. E.g. 1000mg in 24 hours. @returns {Ratio} */ MedicationPrescriptionDosageInstructionComponent.prototype.maxDosePerPeriod = function() { if (this.json['maxDosePerPeriod']) { return new Ratio(this.json['maxDosePerPeriod']); } }; return MedicationPrescriptionDosageInstructionComponent; })(BackboneElement); /** Embedded class @class MedicationPrescriptionDispenseComponent @exports MedicationPrescriptionDispenseComponent as MedicationPrescriptionDispenseComponent */ MedicationPrescriptionDispenseComponent = (function(superClass) { extend(MedicationPrescriptionDispenseComponent, superClass); function MedicationPrescriptionDispenseComponent(json) { this.json = json; MedicationPrescriptionDispenseComponent.__super__.constructor.call(this, this.json); } /** Identifies the medication that is to be dispensed. This may be a more specifically defined than the medicationPrescription.medication . This is either a link to a resource representing the details of the medication or a simple attribute carrying a code that identifies the medication from a known list of medications. @returns {Reference} */ MedicationPrescriptionDispenseComponent.prototype.medication = function() { if (this.json['medication']) { return new Reference(this.json['medication']); } }; /** Design Comments: This indicates the validity period of a prescription (stale dating the Prescription) It reflects the prescriber perspective for the validity of the prescription. Dispenses must not be made against the prescription outside of this period. The lower-bound of the Dispensing Window signifies the earliest date that the prescription can be filled for the first time. If an upper-bound is not specified then the Prescription is open-ended or will default to a stale-date based on regulations. Rationale: Indicates when the Prescription becomes valid, and when it ceases to be a dispensable Prescription. @returns {Period} */ MedicationPrescriptionDispenseComponent.prototype.validityPeriod = function() { if (this.json['validityPeriod']) { return new Period(this.json['validityPeriod']); } }; /** An integer indicating the number of repeats of the Dispense. UsageNotes: For example, the number of times the prescribed quantity is to be supplied including the initial standard fill. @returns {Array} an array of {@link Number} objects */ MedicationPrescriptionDispenseComponent.prototype.numberOfRepeatsAllowed = function() { return this.json['numberOfRepeatsAllowed']; }; /** The amount that is to be dispensed. @returns {Quantity} */ MedicationPrescriptionDispenseComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** Identifies the period time over which the supplied product is expected to be used, or the length of time the dispense is expected to last. In some situations, this attribute may be used instead of quantity to identify the amount supplied by how long it is expected to last, rather than the physical quantity issued, e.g. 90 days supply of medication (based on an ordered dosage) When possible, it is always better to specify quantity, as this tends to be more precise. expectedSupplyDuration will always be an estimate that can be influenced by external factors. @returns {Duration} */ MedicationPrescriptionDispenseComponent.prototype.expectedSupplyDuration = function() { if (this.json['expectedSupplyDuration']) { return new Duration(this.json['expectedSupplyDuration']); } }; return MedicationPrescriptionDispenseComponent; })(BackboneElement); /** Embedded class @class MedicationPrescriptionSubstitutionComponent @exports MedicationPrescriptionSubstitutionComponent as MedicationPrescriptionSubstitutionComponent */ MedicationPrescriptionSubstitutionComponent = (function(superClass) { extend(MedicationPrescriptionSubstitutionComponent, superClass); function MedicationPrescriptionSubstitutionComponent(json) { this.json = json; MedicationPrescriptionSubstitutionComponent.__super__.constructor.call(this, this.json); } /** A code signifying whether a different drug should be dispensed from what was prescribed. @returns {CodeableConcept} */ MedicationPrescriptionSubstitutionComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Indicates the reason for the substitution, or why substitution must or must not be performed. @returns {CodeableConcept} */ MedicationPrescriptionSubstitutionComponent.prototype.reason = function() { if (this.json['reason']) { return new CodeableConcept(this.json['reason']); } }; return MedicationPrescriptionSubstitutionComponent; })(BackboneElement); /** An order for both supply of the medication and the instructions for administration of the medicine to a patient. @class MedicationPrescription @exports MedicationPrescription as MedicationPrescription */ MedicationPrescription = (function(superClass) { extend(MedicationPrescription, superClass); function MedicationPrescription(json) { this.json = json; MedicationPrescription.__super__.constructor.call(this, this.json); } /** External identifier - one that would be used by another non-FHIR system - for example a re-imbursement system might issue its own id for each prescription that is created. This is particularly important where FHIR only provides part of an erntire workflow process where records have to be tracked through an entire system. @returns {Array} an array of {@link Identifier} objects */ MedicationPrescription.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The date (and perhaps time) when the prescription was written. @returns {Array} an array of {@link Date} objects */ MedicationPrescription.prototype.dateWritten = function() { if (this.json['dateWritten']) { return DT.DateTime.parse(this.json['dateWritten']); } }; /** A code specifying the state of the order. Generally this will be active or completed state. @returns {Array} an array of {@link String} objects */ MedicationPrescription.prototype.status = function() { return this.json['status']; }; /** A link to a resource representing the person to whom the medication will be given. @returns {Reference} */ MedicationPrescription.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The healthcare professional responsible for authorizing the prescription. @returns {Reference} */ MedicationPrescription.prototype.prescriber = function() { if (this.json['prescriber']) { return new Reference(this.json['prescriber']); } }; /** A link to a resource that identifies the particular occurrence of contact between patient and health care provider. @returns {Reference} */ MedicationPrescription.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** Can be the reason or the indication for writing the prescription. @returns {CodeableConcept} */ MedicationPrescription.prototype.reasonCodeableConcept = function() { if (this.json['reasonCodeableConcept']) { return new CodeableConcept(this.json['reasonCodeableConcept']); } }; /** Can be the reason or the indication for writing the prescription. @returns {Reference} */ MedicationPrescription.prototype.reasonReference = function() { if (this.json['reasonReference']) { return new Reference(this.json['reasonReference']); } }; /** Identifies the medication being administered. This is either a link to a resource representing the details of the medication or a simple attribute carrying a code that identifies the medication from a known list of medications. @returns {Reference} */ MedicationPrescription.prototype.medication = function() { if (this.json['medication']) { return new Reference(this.json['medication']); } }; /** Indicates how the medication is to be used by the patient. @returns {Array} an array of {@link MedicationPrescriptionDosageInstructionComponent} objects */ MedicationPrescription.prototype.dosageInstruction = function() { var i, item, len, ref, results; if (this.json['dosageInstruction']) { ref = this.json['dosageInstruction']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MedicationPrescriptionDosageInstructionComponent(item)); } return results; } }; /** Deals with details of the dispense part of the order. @returns {MedicationPrescriptionDispenseComponent} */ MedicationPrescription.prototype.dispense = function() { if (this.json['dispense']) { return new MedicationPrescriptionDispenseComponent(this.json['dispense']); } }; /** Indicates whether or not substitution can or should be part of the dispense. In some cases substitution must happen, in other cases substitution must not happen, and in others it does not matter. This block explains the prescriber's intent. If nothing is specified substitution may be done. @returns {MedicationPrescriptionSubstitutionComponent} */ MedicationPrescription.prototype.substitution = function() { if (this.json['substitution']) { return new MedicationPrescriptionSubstitutionComponent(this.json['substitution']); } }; return MedicationPrescription; })(DomainResource); module.exports.MedicationPrescription = MedicationPrescription; }).call(this); },{"../cql-datatypes":117,"./core":173}],205:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, MedicationStatement, MedicationStatementDosageComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class MedicationStatementDosageComponent @exports MedicationStatementDosageComponent as MedicationStatementDosageComponent */ MedicationStatementDosageComponent = (function(superClass) { extend(MedicationStatementDosageComponent, superClass); function MedicationStatementDosageComponent(json) { this.json = json; MedicationStatementDosageComponent.__super__.constructor.call(this, this.json); } /** The timing schedule for giving the medication to the patient. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Timing} */ MedicationStatementDosageComponent.prototype.schedule = function() { if (this.json['schedule']) { return new Timing(this.json['schedule']); } }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {Array} an array of {@link boolean} objects */ MedicationStatementDosageComponent.prototype.asNeededBoolean = function() { return this.json['asNeededBoolean']; }; /** If set to true or if specified as a CodeableConcept, indicates that the medication is only taken when needed within the specified schedule rather than at every scheduled dose. If a CodeableConcept is present, it indicates the pre-condition for taking the Medication. @returns {CodeableConcept} */ MedicationStatementDosageComponent.prototype.asNeededCodeableConcept = function() { if (this.json['asNeededCodeableConcept']) { return new CodeableConcept(this.json['asNeededCodeableConcept']); } }; /** A coded specification of the anatomic site where the medication first enters the body. @returns {CodeableConcept} */ MedicationStatementDosageComponent.prototype.site = function() { if (this.json['site']) { return new CodeableConcept(this.json['site']); } }; /** A code specifying the route or physiological path of administration of a therapeutic agent into or onto a subject. @returns {CodeableConcept} */ MedicationStatementDosageComponent.prototype.route = function() { if (this.json['route']) { return new CodeableConcept(this.json['route']); } }; /** A coded value indicating the method by which the medication is introduced into or onto the body. Most commonly used for injections. Examples: Slow Push; Deep IV. Terminologies used often pre-coordinate this term with the route and or form of administration. @returns {CodeableConcept} */ MedicationStatementDosageComponent.prototype.method = function() { if (this.json['method']) { return new CodeableConcept(this.json['method']); } }; /** The amount of therapeutic or other substance given at one administration event. @returns {Quantity} */ MedicationStatementDosageComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** Identifies the speed with which the substance is introduced into the subject. Typically the rate for an infusion. 200ml in 2 hours. @returns {Ratio} */ MedicationStatementDosageComponent.prototype.rate = function() { if (this.json['rate']) { return new Ratio(this.json['rate']); } }; /** The maximum total quantity of a therapeutic substance that may be administered to a subject over the period of time. E.g. 1000mg in 24 hours. @returns {Ratio} */ MedicationStatementDosageComponent.prototype.maxDosePerPeriod = function() { if (this.json['maxDosePerPeriod']) { return new Ratio(this.json['maxDosePerPeriod']); } }; return MedicationStatementDosageComponent; })(BackboneElement); /** A record of medication being taken by a patient, or that the medication has been given to a patient where the record is the result of a report from the patient or another clinician. @class MedicationStatement @exports MedicationStatement as MedicationStatement */ MedicationStatement = (function(superClass) { extend(MedicationStatement, superClass); function MedicationStatement(json) { this.json = json; MedicationStatement.__super__.constructor.call(this, this.json); } /** External identifier - FHIR will generate its own internal IDs (probably URLs) which do not need to be explicitly managed by the resource. The identifier here is one that would be used by another non-FHIR system - for example an automated medication pump would provide a record each time it operated; an administration while the patient was off the ward might be made with a different system and entered after the event. Particularly important if these records have to be updated. @returns {Array} an array of {@link Identifier} objects */ MedicationStatement.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The person or animal who is /was taking the medication. @returns {Reference} */ MedicationStatement.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** Set this to true if the record is saying that the medication was NOT taken. @returns {Array} an array of {@link boolean} objects */ MedicationStatement.prototype.wasNotGiven = function() { return this.json['wasNotGiven']; }; /** A code indicating why the medication was not taken. @returns {Array} an array of {@link CodeableConcept} objects */ MedicationStatement.prototype.reasonNotGiven = function() { var i, item, len, ref, results; if (this.json['reasonNotGiven']) { ref = this.json['reasonNotGiven']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The interval of time during which it is being asserted that the patient was taking the medication. @returns {Period} */ MedicationStatement.prototype.whenGiven = function() { if (this.json['whenGiven']) { return new Period(this.json['whenGiven']); } }; /** Identifies the medication being administered. This is either a link to a resource representing the details of the medication or a simple attribute carrying a code that identifies the medication from a known list of medications. @returns {Reference} */ MedicationStatement.prototype.medication = function() { if (this.json['medication']) { return new Reference(this.json['medication']); } }; /** An identifier or a link to a resource that identifies a device used in administering the medication to the patient. @returns {Array} an array of {@link Reference} objects */ MedicationStatement.prototype.device = function() { var i, item, len, ref, results; if (this.json['device']) { ref = this.json['device']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Indicates how the medication is/was used by the patient. @returns {Array} an array of {@link MedicationStatementDosageComponent} objects */ MedicationStatement.prototype.dosage = function() { var i, item, len, ref, results; if (this.json['dosage']) { ref = this.json['dosage']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MedicationStatementDosageComponent(item)); } return results; } }; return MedicationStatement; })(DomainResource); module.exports.MedicationStatement = MedicationStatement; }).call(this); },{"../cql-datatypes":117,"./core":173}],206:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, MessageDestinationComponent, MessageHeader, MessageHeaderResponseComponent, MessageSourceComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class MessageHeaderResponseComponent @exports MessageHeaderResponseComponent as MessageHeaderResponseComponent */ MessageHeaderResponseComponent = (function(superClass) { extend(MessageHeaderResponseComponent, superClass); function MessageHeaderResponseComponent(json) { this.json = json; MessageHeaderResponseComponent.__super__.constructor.call(this, this.json); } /** The id of the message that this message is a response to. @returns {Array} an array of {@link String} objects */ MessageHeaderResponseComponent.prototype.identifier = function() { return this.json['identifier']; }; /** Code that identifies the type of response to the message - whether it was successful or not, and whether it should be resent or not. @returns {Array} an array of {@link String} objects */ MessageHeaderResponseComponent.prototype.code = function() { return this.json['code']; }; /** Full details of any issues found in the message. @returns {Reference} */ MessageHeaderResponseComponent.prototype.details = function() { if (this.json['details']) { return new Reference(this.json['details']); } }; return MessageHeaderResponseComponent; })(BackboneElement); /** Embedded class @class MessageSourceComponent @exports MessageSourceComponent as MessageSourceComponent */ MessageSourceComponent = (function(superClass) { extend(MessageSourceComponent, superClass); function MessageSourceComponent(json) { this.json = json; MessageSourceComponent.__super__.constructor.call(this, this.json); } /** Human-readable name for the source system. @returns {Array} an array of {@link String} objects */ MessageSourceComponent.prototype.name = function() { return this.json['name']; }; /** May include configuration or other information useful in debugging. @returns {Array} an array of {@link String} objects */ MessageSourceComponent.prototype.software = function() { return this.json['software']; }; /** Can convey versions of multiple systems in situations where a message passes through multiple hands. @returns {Array} an array of {@link String} objects */ MessageSourceComponent.prototype.version = function() { return this.json['version']; }; /** An e-mail, phone, website or other contact point to use to resolve issues with message communications. @returns {ContactPoint} */ MessageSourceComponent.prototype.contact = function() { if (this.json['contact']) { return new ContactPoint(this.json['contact']); } }; /** Identifies the routing target to send acknowledgements to. @returns {Array} an array of {@link String} objects */ MessageSourceComponent.prototype.endpoint = function() { return this.json['endpoint']; }; return MessageSourceComponent; })(BackboneElement); /** Embedded class @class MessageDestinationComponent @exports MessageDestinationComponent as MessageDestinationComponent */ MessageDestinationComponent = (function(superClass) { extend(MessageDestinationComponent, superClass); function MessageDestinationComponent(json) { this.json = json; MessageDestinationComponent.__super__.constructor.call(this, this.json); } /** Human-readable name for the target system. @returns {Array} an array of {@link String} objects */ MessageDestinationComponent.prototype.name = function() { return this.json['name']; }; /** Identifies the target end system in situations where the initial message transmission is to an intermediary system. @returns {Reference} */ MessageDestinationComponent.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** Indicates where the message should be routed to. @returns {Array} an array of {@link String} objects */ MessageDestinationComponent.prototype.endpoint = function() { return this.json['endpoint']; }; return MessageDestinationComponent; })(BackboneElement); /** The header for a message exchange that is either requesting or responding to an action. The Reference(s) that are the subject of the action as well as other Information related to the action are typically transmitted in a bundle in which the MessageHeader resource instance is the first resource in the bundle. @class MessageHeader @exports MessageHeader as MessageHeader */ MessageHeader = (function(superClass) { extend(MessageHeader, superClass); function MessageHeader(json) { this.json = json; MessageHeader.__super__.constructor.call(this, this.json); } /** The identifier of this message. @returns {Array} an array of {@link String} objects */ MessageHeader.prototype.identifier = function() { return this.json['identifier']; }; /** The time that the message was sent. @returns {Array} an array of {@link Date} objects */ MessageHeader.prototype.timestamp = function() { if (this.json['timestamp']) { return DT.DateTime.parse(this.json['timestamp']); } }; /** Code that identifies the event this message represents and connects it with its definition. Events defined as part of the FHIR specification have the system value "http://hl7.org/fhir/message-type". @returns {Coding} */ MessageHeader.prototype.event = function() { if (this.json['event']) { return new Coding(this.json['event']); } }; /** Information about the message that this message is a response to. Only present if this message is a response. @returns {MessageHeaderResponseComponent} */ MessageHeader.prototype.response = function() { if (this.json['response']) { return new MessageHeaderResponseComponent(this.json['response']); } }; /** The source application from which this message originated. @returns {MessageSourceComponent} */ MessageHeader.prototype.source = function() { if (this.json['source']) { return new MessageSourceComponent(this.json['source']); } }; /** The destination application which the message is intended for. @returns {Array} an array of {@link MessageDestinationComponent} objects */ MessageHeader.prototype.destination = function() { var i, item, len, ref, results; if (this.json['destination']) { ref = this.json['destination']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MessageDestinationComponent(item)); } return results; } }; /** The person or device that performed the data entry leading to this message. Where there is more than one candidate, pick the most proximal to the message. Can provide other enterers in extensions. @returns {Reference} */ MessageHeader.prototype.enterer = function() { if (this.json['enterer']) { return new Reference(this.json['enterer']); } }; /** The logical author of the message - the person or device that decided the described event should happen. Where there is more than one candidate, pick the most proximal to the MessageHeader. Can provide other authors in extensions. @returns {Reference} */ MessageHeader.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** Allows data conveyed by a message to be addressed to a particular person or department when routing to a specific application isn't sufficient. @returns {Reference} */ MessageHeader.prototype.receiver = function() { if (this.json['receiver']) { return new Reference(this.json['receiver']); } }; /** The person or organization that accepts overall responsibility for the contents of the message. The implication is that the message event happened under the policies of the responsible party. @returns {Reference} */ MessageHeader.prototype.responsible = function() { if (this.json['responsible']) { return new Reference(this.json['responsible']); } }; /** Coded indication of the cause for the event - indicates a reason for the occurance of the event that is a focus of this message. @returns {CodeableConcept} */ MessageHeader.prototype.reason = function() { if (this.json['reason']) { return new CodeableConcept(this.json['reason']); } }; /** The actual data of the message - a reference to the root/focus class of the event. @returns {Array} an array of {@link Reference} objects */ MessageHeader.prototype.data = function() { var i, item, len, ref, results; if (this.json['data']) { ref = this.json['data']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return MessageHeader; })(DomainResource); module.exports.MessageHeader = MessageHeader; }).call(this); },{"../cql-datatypes":117,"./core":173}],207:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { module.exports = require('./core'); module.exports.Condition = require('./condition').Condition; module.exports.Supply = require('./supply').Supply; module.exports.ProcedureRequest = require('./procedurerequest').ProcedureRequest; module.exports.DeviceComponent = require('./devicecomponent').DeviceComponent; module.exports.Organization = require('./organization').Organization; module.exports.Readjudicate = require('./readjudicate').Readjudicate; module.exports.Group = require('./group').Group; module.exports.OralHealthClaim = require('./oralhealthclaim').OralHealthClaim; module.exports.ValueSet = require('./valueset').ValueSet; module.exports.Coverage = require('./coverage').Coverage; module.exports.ImmunizationRecommendation = require('./immunizationrecommendation').ImmunizationRecommendation; module.exports.Appointment = require('./appointment').Appointment; module.exports.MedicationDispense = require('./medicationdispense').MedicationDispense; module.exports.MedicationPrescription = require('./medicationprescription').MedicationPrescription; module.exports.Slot = require('./slot').Slot; module.exports.PaymentNotice = require('./paymentnotice').PaymentNotice; module.exports.Contraindication = require('./contraindication').Contraindication; module.exports.AppointmentResponse = require('./appointmentresponse').AppointmentResponse; module.exports.MedicationStatement = require('./medicationstatement').MedicationStatement; module.exports.Questionnaire = require('./questionnaire').Questionnaire; module.exports.Composition = require('./composition').Composition; module.exports.OperationOutcome = require('./operationoutcome').OperationOutcome; module.exports.Conformance = require('./conformance').Conformance; module.exports.NamingSystem = require('./namingsystem').NamingSystem; module.exports.Media = require('./media').Media; module.exports.Binary = require('./binary').Binary; module.exports.Other = require('./other').Other; module.exports.HealthcareService = require('./healthcareservice').HealthcareService; module.exports.Profile = require('./profile').Profile; module.exports.DocumentReference = require('./documentreference').DocumentReference; module.exports.Eligibility = require('./eligibility').Eligibility; module.exports.Immunization = require('./immunization').Immunization; module.exports.Bundle = require('./bundle').Bundle; module.exports.ExtensionDefinition = require('./extensiondefinition').ExtensionDefinition; module.exports.Subscription = require('./subscription').Subscription; module.exports.OrderResponse = require('./orderresponse').OrderResponse; module.exports.StatusResponse = require('./statusresponse').StatusResponse; module.exports.ConceptMap = require('./conceptmap').ConceptMap; module.exports.Reversal = require('./reversal').Reversal; module.exports.ImagingStudy = require('./imagingstudy').ImagingStudy; module.exports.Practitioner = require('./practitioner').Practitioner; module.exports.CarePlan = require('./careplan').CarePlan; module.exports.Provenance = require('./provenance').Provenance; module.exports.Device = require('./device').Device; module.exports.Query = require('./query').Query; module.exports.Order = require('./order').Order; module.exports.Procedure = require('./procedure').Procedure; module.exports.Substance = require('./substance').Substance; module.exports.DeviceUseRequest = require('./deviceuserequest').DeviceUseRequest; module.exports.DiagnosticReport = require('./diagnosticreport').DiagnosticReport; module.exports.Medication = require('./medication').Medication; module.exports.MessageHeader = require('./messageheader').MessageHeader; module.exports.DocumentManifest = require('./documentmanifest').DocumentManifest; module.exports.DataElement = require('./dataelement').DataElement; module.exports.Availability = require('./availability').Availability; module.exports.QuestionnaireAnswers = require('./questionnaireanswers').QuestionnaireAnswers; module.exports.MedicationAdministration = require('./medicationadministration').MedicationAdministration; module.exports.Encounter = require('./encounter').Encounter; module.exports.Enrollment = require('./enrollment').Enrollment; module.exports.PaymentReconciliation = require('./paymentreconciliation').PaymentReconciliation; module.exports.SecurityEvent = require('./securityevent').SecurityEvent; module.exports.PendedRequest = require('./pendedrequest').PendedRequest; module.exports.List = require('./list').List; module.exports.DeviceUseStatement = require('./deviceusestatement').DeviceUseStatement; module.exports.OperationDefinition = require('./operationdefinition').OperationDefinition; module.exports.ImagingObjectSelection = require('./imagingobjectselection').ImagingObjectSelection; module.exports.SearchParameter = require('./searchparameter').SearchParameter; module.exports.NutritionOrder = require('./nutritionorder').NutritionOrder; module.exports.ClaimResponse = require('./claimresponse').ClaimResponse; module.exports.ReferralRequest = require('./referralrequest').ReferralRequest; module.exports.CommunicationRequest = require('./communicationrequest').CommunicationRequest; module.exports.RiskAssessment = require('./riskassessment').RiskAssessment; module.exports.FamilyHistory = require('./familyhistory').FamilyHistory; module.exports.Location = require('./location').Location; module.exports.ExplanationOfBenefit = require('./explanationofbenefit').ExplanationOfBenefit; module.exports.AllergyIntolerance = require('./allergyintolerance').AllergyIntolerance; module.exports.Observation = require('./observation').Observation; module.exports.Contract = require('./contract').Contract; module.exports.SupportingDocumentation = require('./supportingdocumentation').SupportingDocumentation; module.exports.RelatedPerson = require('./relatedperson').RelatedPerson; module.exports.Basic = require('./basic').Basic; module.exports.Specimen = require('./specimen').Specimen; module.exports.Alert = require('./alert').Alert; module.exports.EnrollmentResponse = require('./enrollmentresponse').EnrollmentResponse; module.exports.Patient = require('./patient').Patient; module.exports.EligibilityResponse = require('./eligibilityresponse').EligibilityResponse; module.exports.StatusRequest = require('./statusrequest').StatusRequest; module.exports.DiagnosticOrder = require('./diagnosticorder').DiagnosticOrder; }).call(this); },{"./alert":156,"./allergyintolerance":157,"./appointment":158,"./appointmentresponse":159,"./availability":160,"./basic":161,"./binary":162,"./bundle":163,"./careplan":164,"./claimresponse":165,"./communicationrequest":166,"./composition":167,"./conceptmap":168,"./condition":169,"./conformance":170,"./contract":171,"./contraindication":172,"./core":173,"./coverage":174,"./dataelement":175,"./device":176,"./devicecomponent":177,"./deviceuserequest":178,"./deviceusestatement":179,"./diagnosticorder":180,"./diagnosticreport":181,"./documentmanifest":182,"./documentreference":183,"./eligibility":184,"./eligibilityresponse":185,"./encounter":186,"./enrollment":187,"./enrollmentresponse":188,"./explanationofbenefit":189,"./extensiondefinition":190,"./familyhistory":191,"./group":192,"./healthcareservice":193,"./imagingobjectselection":194,"./imagingstudy":195,"./immunization":196,"./immunizationrecommendation":197,"./list":198,"./location":199,"./media":200,"./medication":201,"./medicationadministration":202,"./medicationdispense":203,"./medicationprescription":204,"./medicationstatement":205,"./messageheader":206,"./namingsystem":208,"./nutritionorder":209,"./observation":210,"./operationdefinition":211,"./operationoutcome":212,"./oralhealthclaim":213,"./order":214,"./orderresponse":215,"./organization":216,"./other":217,"./patient":218,"./paymentnotice":219,"./paymentreconciliation":220,"./pendedrequest":221,"./practitioner":222,"./procedure":223,"./procedurerequest":224,"./profile":225,"./provenance":226,"./query":227,"./questionnaire":228,"./questionnaireanswers":229,"./readjudicate":230,"./referralrequest":231,"./relatedperson":232,"./reversal":233,"./riskassessment":234,"./searchparameter":235,"./securityevent":236,"./slot":237,"./specimen":238,"./statusrequest":239,"./statusresponse":240,"./subscription":241,"./substance":242,"./supply":243,"./supportingdocumentation":244,"./valueset":245}],208:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, NamingSystem, NamingSystemContactComponent, NamingSystemUniqueIdComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class NamingSystemUniqueIdComponent @exports NamingSystemUniqueIdComponent as NamingSystemUniqueIdComponent */ NamingSystemUniqueIdComponent = (function(superClass) { extend(NamingSystemUniqueIdComponent, superClass); function NamingSystemUniqueIdComponent(json) { this.json = json; NamingSystemUniqueIdComponent.__super__.constructor.call(this, this.json); } /** Identifies the unique identifier scheme used for this particular identifier. @returns {Array} an array of {@link String} objects */ NamingSystemUniqueIdComponent.prototype.type = function() { return this.json['type']; }; /** The string that should be sent over the wire to identify the code system or identifier system. @returns {Array} an array of {@link String} objects */ NamingSystemUniqueIdComponent.prototype.value = function() { return this.json['value']; }; /** Indicates whether this identifier is the "preferred" identifier of this type. @returns {Array} an array of {@link boolean} objects */ NamingSystemUniqueIdComponent.prototype.preferred = function() { return this.json['preferred']; }; /** Identifies the period of time over which this identifier is considered appropriate to refer to the namingsystem. Outside of this window, the identifier might be non-deterministic. @returns {Period} */ NamingSystemUniqueIdComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return NamingSystemUniqueIdComponent; })(BackboneElement); /** Embedded class @class NamingSystemContactComponent @exports NamingSystemContactComponent as NamingSystemContactComponent */ NamingSystemContactComponent = (function(superClass) { extend(NamingSystemContactComponent, superClass); function NamingSystemContactComponent(json) { this.json = json; NamingSystemContactComponent.__super__.constructor.call(this, this.json); } /** Names of the person who can be contacted. @returns {HumanName} */ NamingSystemContactComponent.prototype.name = function() { if (this.json['name']) { return new HumanName(this.json['name']); } }; /** Identifies the mechanism(s) by which they can be contacted. @returns {Array} an array of {@link ContactPoint} objects */ NamingSystemContactComponent.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; return NamingSystemContactComponent; })(BackboneElement); /** A curated namespace that issues unique symbols within that namespace for the identification of concepts, people, devices, etc. Represents a "System" used within the Identifier and Coding data types. @class NamingSystem @exports NamingSystem as NamingSystem */ NamingSystem = (function(superClass) { extend(NamingSystem, superClass); function NamingSystem(json) { this.json = json; NamingSystem.__super__.constructor.call(this, this.json); } /** Indicates the purpose for the namingsystem - what kinds of things does it make unique?. @returns {Array} an array of {@link String} objects */ NamingSystem.prototype.type = function() { return this.json['type']; }; /** The descriptive name of this particular identifier type or code system. @returns {Array} an array of {@link String} objects */ NamingSystem.prototype.name = function() { return this.json['name']; }; /** Indicates whether the namingsystem is "ready for use" or not. @returns {Array} an array of {@link String} objects */ NamingSystem.prototype.status = function() { return this.json['status']; }; /** If present, indicates that the identifier or code system is principally intended for use or applies to entities within the specified country. For example, the country associated with a national code system. @returns {Array} an array of {@link String} objects */ NamingSystem.prototype.country = function() { return this.json['country']; }; /** Categorizes a namingsystem for easier search by grouping related namingsystems. @returns {CodeableConcept} */ NamingSystem.prototype.category = function() { if (this.json['category']) { return new CodeableConcept(this.json['category']); } }; /** The name of the organization that is responsible for issuing identifiers or codes for this namespace and ensuring their non-collision. @returns {Array} an array of {@link String} objects */ NamingSystem.prototype.responsible = function() { return this.json['responsible']; }; /** Details about what the namespace identifies including scope, granularity, version labeling, etc. @returns {Array} an array of {@link String} objects */ NamingSystem.prototype.description = function() { return this.json['description']; }; /** Provides guidance on the use of the namespace, including the handling of formatting characters, use of upper vs. lower case, etc. @returns {Array} an array of {@link String} objects */ NamingSystem.prototype.usage = function() { return this.json['usage']; }; /** Indicates how the system may be identified when referenced in electronic exchange. @returns {Array} an array of {@link NamingSystemUniqueIdComponent} objects */ NamingSystem.prototype.uniqueId = function() { var i, item, len, ref, results; if (this.json['uniqueId']) { ref = this.json['uniqueId']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new NamingSystemUniqueIdComponent(item)); } return results; } }; /** The person who can be contacted about this system registration entry. @returns {NamingSystemContactComponent} */ NamingSystem.prototype.contact = function() { if (this.json['contact']) { return new NamingSystemContactComponent(this.json['contact']); } }; /** For namingsystems that are retired, indicates the namingsystem that should be used in their place (if any). @returns {Reference} */ NamingSystem.prototype.replacedBy = function() { if (this.json['replacedBy']) { return new Reference(this.json['replacedBy']); } }; return NamingSystem; })(DomainResource); module.exports.NamingSystem = NamingSystem; }).call(this); },{"../cql-datatypes":117,"./core":173}],209:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, NutritionOrder, NutritionOrderItemComponent, NutritionOrderItemEnteralFormulaComponent, NutritionOrderItemOralDietComponent, NutritionOrderItemOralDietNutrientsComponent, NutritionOrderItemOralDietTextureComponent, NutritionOrderItemSupplementComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class NutritionOrderItemOralDietNutrientsComponent @exports NutritionOrderItemOralDietNutrientsComponent as NutritionOrderItemOralDietNutrientsComponent */ NutritionOrderItemOralDietNutrientsComponent = (function(superClass) { extend(NutritionOrderItemOralDietNutrientsComponent, superClass); function NutritionOrderItemOralDietNutrientsComponent(json) { this.json = json; NutritionOrderItemOralDietNutrientsComponent.__super__.constructor.call(this, this.json); } /** Identifies the type of nutrient that is being modified such as cabohydrate or sodium. @returns {CodeableConcept} */ NutritionOrderItemOralDietNutrientsComponent.prototype.modifier = function() { if (this.json['modifier']) { return new CodeableConcept(this.json['modifier']); } }; /** The quantity or range of the specified nutrient to supply. @returns {Quantity} */ NutritionOrderItemOralDietNutrientsComponent.prototype.amountQuantity = function() { if (this.json['amountQuantity']) { return new Quantity(this.json['amountQuantity']); } }; /** The quantity or range of the specified nutrient to supply. @returns {Range} */ NutritionOrderItemOralDietNutrientsComponent.prototype.amountRange = function() { if (this.json['amountRange']) { return new Range(this.json['amountRange']); } }; return NutritionOrderItemOralDietNutrientsComponent; })(BackboneElement); /** Embedded class @class NutritionOrderItemOralDietTextureComponent @exports NutritionOrderItemOralDietTextureComponent as NutritionOrderItemOralDietTextureComponent */ NutritionOrderItemOralDietTextureComponent = (function(superClass) { extend(NutritionOrderItemOralDietTextureComponent, superClass); function NutritionOrderItemOralDietTextureComponent(json) { this.json = json; NutritionOrderItemOralDietTextureComponent.__super__.constructor.call(this, this.json); } /** Identifies any texture modifications (for solid foods) that should be made, e.g. easy to chew, chopped, ground, pureed. @returns {CodeableConcept} */ NutritionOrderItemOralDietTextureComponent.prototype.modifier = function() { if (this.json['modifier']) { return new CodeableConcept(this.json['modifier']); } }; /** Indicates what specific type of food (e.g., meats) the texture modification applies to or may apply to all foods in the diet. @returns {CodeableConcept} */ NutritionOrderItemOralDietTextureComponent.prototype.foodType = function() { if (this.json['foodType']) { return new CodeableConcept(this.json['foodType']); } }; return NutritionOrderItemOralDietTextureComponent; })(BackboneElement); /** Embedded class @class NutritionOrderItemOralDietComponent @exports NutritionOrderItemOralDietComponent as NutritionOrderItemOralDietComponent */ NutritionOrderItemOralDietComponent = (function(superClass) { extend(NutritionOrderItemOralDietComponent, superClass); function NutritionOrderItemOralDietComponent(json) { this.json = json; NutritionOrderItemOralDietComponent.__super__.constructor.call(this, this.json); } /** A set of one or more codes representing diets that describe what can be consumed orally (i.e., take via the mouth). @returns {Array} an array of {@link CodeableConcept} objects */ NutritionOrderItemOralDietComponent.prototype.code = function() { var i, item, len, ref, results; if (this.json['code']) { ref = this.json['code']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Class that defines the details of any nutrient modifications required for the oral diet. @returns {Array} an array of {@link NutritionOrderItemOralDietNutrientsComponent} objects */ NutritionOrderItemOralDietComponent.prototype.nutrients = function() { var i, item, len, ref, results; if (this.json['nutrients']) { ref = this.json['nutrients']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new NutritionOrderItemOralDietNutrientsComponent(item)); } return results; } }; /** Class that describes any texture modifications required for the patient to safely consume various types of solid foods. @returns {Array} an array of {@link NutritionOrderItemOralDietTextureComponent} objects */ NutritionOrderItemOralDietComponent.prototype.texture = function() { var i, item, len, ref, results; if (this.json['texture']) { ref = this.json['texture']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new NutritionOrderItemOralDietTextureComponent(item)); } return results; } }; /** Identifies the required consistency (e.g., honey-thick, nectar-thick, thin, thickened.) of liquids or fluids served to the patient. @returns {Array} an array of {@link CodeableConcept} objects */ NutritionOrderItemOralDietComponent.prototype.fluidConsistencyType = function() { var i, item, len, ref, results; if (this.json['fluidConsistencyType']) { ref = this.json['fluidConsistencyType']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** A descriptive name of the required diets that describe what can be consumed orally (i.e., take via the mouth). @returns {Array} an array of {@link String} objects */ NutritionOrderItemOralDietComponent.prototype.description = function() { return this.json['description']; }; return NutritionOrderItemOralDietComponent; })(BackboneElement); /** Embedded class @class NutritionOrderItemSupplementComponent @exports NutritionOrderItemSupplementComponent as NutritionOrderItemSupplementComponent */ NutritionOrderItemSupplementComponent = (function(superClass) { extend(NutritionOrderItemSupplementComponent, superClass); function NutritionOrderItemSupplementComponent(json) { this.json = json; NutritionOrderItemSupplementComponent.__super__.constructor.call(this, this.json); } /** Indicates the type of nutritional supplement product required such as high protein or pediatric clear liquid supplement. @returns {Array} an array of {@link CodeableConcept} objects */ NutritionOrderItemSupplementComponent.prototype.type = function() { var i, item, len, ref, results; if (this.json['type']) { ref = this.json['type']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The amount of the nutritional supplement product to provide to the patient. @returns {Quantity} */ NutritionOrderItemSupplementComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** The name of the nutritional supplement product to be provided to the patient. @returns {Array} an array of {@link String} objects */ NutritionOrderItemSupplementComponent.prototype.name = function() { return this.json['name']; }; return NutritionOrderItemSupplementComponent; })(BackboneElement); /** Embedded class @class NutritionOrderItemEnteralFormulaComponent @exports NutritionOrderItemEnteralFormulaComponent as NutritionOrderItemEnteralFormulaComponent */ NutritionOrderItemEnteralFormulaComponent = (function(superClass) { extend(NutritionOrderItemEnteralFormulaComponent, superClass); function NutritionOrderItemEnteralFormulaComponent(json) { this.json = json; NutritionOrderItemEnteralFormulaComponent.__super__.constructor.call(this, this.json); } /** Indicates the type of enteral or infant formula requested such as pediatric elemental formula or. @returns {CodeableConcept} */ NutritionOrderItemEnteralFormulaComponent.prototype.baseFormulaType = function() { if (this.json['baseFormulaType']) { return new CodeableConcept(this.json['baseFormulaType']); } }; /** Indicates the type of modular component such as protein, carbohydrate or fiber to be provided in addition to or mixed with the base formula. @returns {Array} an array of {@link CodeableConcept} objects */ NutritionOrderItemEnteralFormulaComponent.prototype.additiveType = function() { var i, item, len, ref, results; if (this.json['additiveType']) { ref = this.json['additiveType']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** TODO ***CARD AND TYPE ARE PLACEHOLDERS TO COMPLETE BUILD. Need to discuss***. @returns {Array} an array of {@link Quantity} objects */ NutritionOrderItemEnteralFormulaComponent.prototype.caloricDensity = function() { var i, item, len, ref, results; if (this.json['caloricDensity']) { ref = this.json['caloricDensity']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Quantity(item)); } return results; } }; /** ***CARD AND TYPE ARE PLACEHOLDERS TO COMPLETE BUILD. Need to discuss***administration details including rate (ml per hour), route of adminstration, total volume. @returns {Array} an array of {@link CodeableConcept} objects */ NutritionOrderItemEnteralFormulaComponent.prototype.routeofAdministration = function() { var i, item, len, ref, results; if (this.json['routeofAdministration']) { ref = this.json['routeofAdministration']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** TODO ***CARD AND TYPE ARE PLACEHOLDERS TO COMPLETE BUILD. Need to discuss***. @returns {Array} an array of {@link Quantity} objects */ NutritionOrderItemEnteralFormulaComponent.prototype.rate = function() { var i, item, len, ref, results; if (this.json['rate']) { ref = this.json['rate']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Quantity(item)); } return results; } }; /** TODO. @returns {Array} an array of {@link String} objects */ NutritionOrderItemEnteralFormulaComponent.prototype.baseFormulaName = function() { return this.json['baseFormulaName']; }; return NutritionOrderItemEnteralFormulaComponent; })(BackboneElement); /** Embedded class @class NutritionOrderItemComponent @exports NutritionOrderItemComponent as NutritionOrderItemComponent */ NutritionOrderItemComponent = (function(superClass) { extend(NutritionOrderItemComponent, superClass); function NutritionOrderItemComponent(json) { this.json = json; NutritionOrderItemComponent.__super__.constructor.call(this, this.json); } /** The frequency at which the diet, oral supplement or enteral formula should be given. @returns {Timing} */ NutritionOrderItemComponent.prototype.scheduledTiming = function() { if (this.json['scheduledTiming']) { return new Timing(this.json['scheduledTiming']); } }; /** The frequency at which the diet, oral supplement or enteral formula should be given. @returns {Period} */ NutritionOrderItemComponent.prototype.scheduledPeriod = function() { if (this.json['scheduledPeriod']) { return new Period(this.json['scheduledPeriod']); } }; /** Indicates whether the nutrition item is currently in effect for the patient. @returns {Array} an array of {@link boolean} objects */ NutritionOrderItemComponent.prototype.isInEffect = function() { return this.json['isInEffect']; }; /** Class that defines the components of an oral diet order for the patient. @returns {NutritionOrderItemOralDietComponent} */ NutritionOrderItemComponent.prototype.oralDiet = function() { if (this.json['oralDiet']) { return new NutritionOrderItemOralDietComponent(this.json['oralDiet']); } }; /** Class that defines the components of a supplement order for the patient. @returns {NutritionOrderItemSupplementComponent} */ NutritionOrderItemComponent.prototype.supplement = function() { if (this.json['supplement']) { return new NutritionOrderItemSupplementComponent(this.json['supplement']); } }; /** Class that defines the components of an enteral formula order for the patient. @returns {NutritionOrderItemEnteralFormulaComponent} */ NutritionOrderItemComponent.prototype.enteralFormula = function() { if (this.json['enteralFormula']) { return new NutritionOrderItemEnteralFormulaComponent(this.json['enteralFormula']); } }; return NutritionOrderItemComponent; })(BackboneElement); /** A request to supply a diet, formula feeding (enteral) or oral nutritional supplement to a patient/resident. @class NutritionOrder @exports NutritionOrder as NutritionOrder */ NutritionOrder = (function(superClass) { extend(NutritionOrder, superClass); function NutritionOrder(json) { this.json = json; NutritionOrder.__super__.constructor.call(this, this.json); } /** The person (patient) who needs the nutrition order for an oral diet, nutritional supplement and/or enteral or formula feeding. @returns {Reference} */ NutritionOrder.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The practitioner that holds legal responsibility for ordering the diet, nutritional supplement, or formula feedings. @returns {Reference} */ NutritionOrder.prototype.orderer = function() { if (this.json['orderer']) { return new Reference(this.json['orderer']); } }; /** Identifiers assigned to this order by the order sender or by the order receiver. @returns {Array} an array of {@link Identifier} objects */ NutritionOrder.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** An encounter that provides additional informaton about the healthcare context in which this request is made. @returns {Reference} */ NutritionOrder.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** The date and time that this nutrition order was requested. @returns {Array} an array of {@link Date} objects */ NutritionOrder.prototype.dateTime = function() { if (this.json['dateTime']) { return DT.DateTime.parse(this.json['dateTime']); } }; /** The ability to list substances that may cause allergies or intolerances which should be included in the nutrition order. @returns {Array} an array of {@link Reference} objects */ NutritionOrder.prototype.allergyIntolerance = function() { var i, item, len, ref, results; if (this.json['allergyIntolerance']) { ref = this.json['allergyIntolerance']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** This modifier is used to convey order-specific modifiers about the type of food that should be given. These can be derived from patient allergies, intolerances, or preferences such as Halal, Vegan or Kosher. This modifier applies to the entire nutrition order inclusive of the oral diet, nutritional supplements and enteral formula feedings. @returns {Array} an array of {@link CodeableConcept} objects */ NutritionOrder.prototype.foodPreferenceModifier = function() { var i, item, len, ref, results; if (this.json['foodPreferenceModifier']) { ref = this.json['foodPreferenceModifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** This modifier is used to convey order-specific modifiers about the type of food that should NOT be given. These can be derived from patient allergies, intolerances, or preferences such as No Red Meat, No Soy or No Wheat or Gluten-Free. This modifier applies to the entire nutrition order inclusive of the oral diet, nutritional supplements and enteral formula feedings. @returns {Array} an array of {@link CodeableConcept} objects */ NutritionOrder.prototype.excludeFoodModifier = function() { var i, item, len, ref, results; if (this.json['excludeFoodModifier']) { ref = this.json['excludeFoodModifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Different items that combine to make a complete description of the nutrition to be provided via oral diet, nutritional supplement and/or formula order. @returns {Array} an array of {@link NutritionOrderItemComponent} objects */ NutritionOrder.prototype.item = function() { var i, item, len, ref, results; if (this.json['item']) { ref = this.json['item']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new NutritionOrderItemComponent(item)); } return results; } }; /** The workflow status of the nutrition order request, e.g., Active, Inactive, Pending, Held, Canceled, Suspended. @returns {Array} an array of {@link String} objects */ NutritionOrder.prototype.status = function() { return this.json['status']; }; return NutritionOrder; })(DomainResource); module.exports.NutritionOrder = NutritionOrder; }).call(this); },{"../cql-datatypes":117,"./core":173}],210:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Observation, ObservationReferenceRangeComponent, ObservationRelatedComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ObservationReferenceRangeComponent @exports ObservationReferenceRangeComponent as ObservationReferenceRangeComponent */ ObservationReferenceRangeComponent = (function(superClass) { extend(ObservationReferenceRangeComponent, superClass); function ObservationReferenceRangeComponent(json) { this.json = json; ObservationReferenceRangeComponent.__super__.constructor.call(this, this.json); } /** The value of the low bound of the reference range. If this is omitted, the low bound of the reference range is assumed to be meaningless. E.g. <2.3. @returns {Quantity} */ ObservationReferenceRangeComponent.prototype.low = function() { if (this.json['low']) { return new Quantity(this.json['low']); } }; /** The value of the high bound of the reference range. If this is omitted, the high bound of the reference range is assumed to be meaningless. E.g. >5. @returns {Quantity} */ ObservationReferenceRangeComponent.prototype.high = function() { if (this.json['high']) { return new Quantity(this.json['high']); } }; /** Code for the meaning of the reference range. @returns {CodeableConcept} */ ObservationReferenceRangeComponent.prototype.meaning = function() { if (this.json['meaning']) { return new CodeableConcept(this.json['meaning']); } }; /** The age at which this reference range is applicable. This is a neonatal age (e.g. number of weeks at term) if the meaning says so. @returns {Range} */ ObservationReferenceRangeComponent.prototype.age = function() { if (this.json['age']) { return new Range(this.json['age']); } }; /** Text based reference range in an observation which may be used when a quantitative range is not appropriate for an observation. An example would be a reference value of "Negative" or a list or table of 'normals'. @returns {Array} an array of {@link String} objects */ ObservationReferenceRangeComponent.prototype.text = function() { return this.json['text']; }; return ObservationReferenceRangeComponent; })(BackboneElement); /** Embedded class @class ObservationRelatedComponent @exports ObservationRelatedComponent as ObservationRelatedComponent */ ObservationRelatedComponent = (function(superClass) { extend(ObservationRelatedComponent, superClass); function ObservationRelatedComponent(json) { this.json = json; ObservationRelatedComponent.__super__.constructor.call(this, this.json); } /** A code specifying the kind of relationship that exists with the target observation. @returns {Array} an array of {@link String} objects */ ObservationRelatedComponent.prototype.type = function() { return this.json['type']; }; /** A reference to the observation that is related to this observation. @returns {Reference} */ ObservationRelatedComponent.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; return ObservationRelatedComponent; })(BackboneElement); /** Measurements and simple assertions made about a patient, device or other subject. @class Observation @exports Observation as Observation */ Observation = (function(superClass) { extend(Observation, superClass); function Observation(json) { this.json = json; Observation.__super__.constructor.call(this, this.json); } /** Describes what was observed. Sometimes this is called the observation "code". @returns {CodeableConcept} */ Observation.prototype.name = function() { if (this.json['name']) { return new CodeableConcept(this.json['name']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {Quantity} */ Observation.prototype.valueQuantity = function() { if (this.json['valueQuantity']) { return new Quantity(this.json['valueQuantity']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {CodeableConcept} */ Observation.prototype.valueCodeableConcept = function() { if (this.json['valueCodeableConcept']) { return new CodeableConcept(this.json['valueCodeableConcept']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {Attachment} */ Observation.prototype.valueAttachment = function() { if (this.json['valueAttachment']) { return new Attachment(this.json['valueAttachment']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {Ratio} */ Observation.prototype.valueRatio = function() { if (this.json['valueRatio']) { return new Ratio(this.json['valueRatio']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {Array} an array of {@link Date} objects */ Observation.prototype.valueDateTime = function() { if (this.json['valueDateTime']) { return DT.DateTime.parse(this.json['valueDateTime']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {Period} */ Observation.prototype.valuePeriod = function() { if (this.json['valuePeriod']) { return new Period(this.json['valuePeriod']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {SampledData} */ Observation.prototype.valueSampledData = function() { if (this.json['valueSampledData']) { return new SampledData(this.json['valueSampledData']); } }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {Array} an array of {@link String} objects */ Observation.prototype.valueString = function() { return this.json['valueString']; }; /** The information determined as a result of making the observation, if the information has a simple value. @returns {time} */ Observation.prototype.valueTime = function() { if (this.json['valueTime']) { return new time(this.json['valueTime']); } }; /** Provides a reason why the expected value in the element Observation.value[x] is missing. @returns {Array} an array of {@link String} objects */ Observation.prototype.dataAbsentReason = function() { return this.json['dataAbsentReason']; }; /** The assessment made based on the result of the observation. @returns {CodeableConcept} */ Observation.prototype.interpretation = function() { if (this.json['interpretation']) { return new CodeableConcept(this.json['interpretation']); } }; /** May include statements about significant, unexpected or unreliable values, or information about the source of the value where this may be relevant to the interpretation of the result. @returns {Array} an array of {@link String} objects */ Observation.prototype.comments = function() { return this.json['comments']; }; /** The time or time-period the observed value is asserted as being true. For biological subjects - e.g. human patients - this is usually called the "physiologically relevant time". This is usually either the time of the procedure or of specimen collection, but very often the source of the date/time is not known, only the date/time itself. @returns {Array} an array of {@link Date} objects */ Observation.prototype.appliesDateTime = function() { if (this.json['appliesDateTime']) { return DT.DateTime.parse(this.json['appliesDateTime']); } }; /** The time or time-period the observed value is asserted as being true. For biological subjects - e.g. human patients - this is usually called the "physiologically relevant time". This is usually either the time of the procedure or of specimen collection, but very often the source of the date/time is not known, only the date/time itself. @returns {Period} */ Observation.prototype.appliesPeriod = function() { if (this.json['appliesPeriod']) { return new Period(this.json['appliesPeriod']); } }; /** The date and time this observation was made available. @returns {Array} an array of {@link Date} objects */ Observation.prototype.issued = function() { if (this.json['issued']) { return DT.DateTime.parse(this.json['issued']); } }; /** The status of the result value. @returns {Array} an array of {@link String} objects */ Observation.prototype.status = function() { return this.json['status']; }; /** An estimate of the degree to which quality issues have impacted on the value reported. @returns {Array} an array of {@link String} objects */ Observation.prototype.reliability = function() { return this.json['reliability']; }; /** Indicates the site on the subject's body where the observation was made ( i.e. the target site). @returns {CodeableConcept} */ Observation.prototype.bodySite = function() { if (this.json['bodySite']) { return new CodeableConcept(this.json['bodySite']); } }; /** Indicates the mechanism used to perform the observation. @returns {CodeableConcept} */ Observation.prototype.method = function() { if (this.json['method']) { return new CodeableConcept(this.json['method']); } }; /** A unique identifier for the simple observation. @returns {Identifier} */ Observation.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** The thing the observation is being made about. @returns {Reference} */ Observation.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The specimen that was used when this observation was made. @returns {Reference} */ Observation.prototype.specimen = function() { if (this.json['specimen']) { return new Reference(this.json['specimen']); } }; /** Who was responsible for asserting the observed value as "true". @returns {Array} an array of {@link Reference} objects */ Observation.prototype.performer = function() { var i, item, len, ref, results; if (this.json['performer']) { ref = this.json['performer']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The healthcare event ( e.g. a patient and healthcare provider interaction ) that relates to this observation. @returns {Reference} */ Observation.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** Guidance on how to interpret the value by comparison to a normal or recommended range. @returns {Array} an array of {@link ObservationReferenceRangeComponent} objects */ Observation.prototype.referenceRange = function() { var i, item, len, ref, results; if (this.json['referenceRange']) { ref = this.json['referenceRange']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ObservationReferenceRangeComponent(item)); } return results; } }; /** Related observations - either components, or previous observations, or statements of derivation. @returns {Array} an array of {@link ObservationRelatedComponent} objects */ Observation.prototype.related = function() { var i, item, len, ref, results; if (this.json['related']) { ref = this.json['related']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ObservationRelatedComponent(item)); } return results; } }; return Observation; })(DomainResource); module.exports.Observation = Observation; }).call(this); },{"../cql-datatypes":117,"./core":173}],211:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, OperationDefinition, OperationDefinitionParameterComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class OperationDefinitionParameterComponent @exports OperationDefinitionParameterComponent as OperationDefinitionParameterComponent */ OperationDefinitionParameterComponent = (function(superClass) { extend(OperationDefinitionParameterComponent, superClass); function OperationDefinitionParameterComponent(json) { this.json = json; OperationDefinitionParameterComponent.__super__.constructor.call(this, this.json); } /** The name of used to identify the parameter. @returns {Array} an array of {@link String} objects */ OperationDefinitionParameterComponent.prototype.name = function() { return this.json['name']; }; /** Whether this is an input or an output parameter. @returns {Array} an array of {@link String} objects */ OperationDefinitionParameterComponent.prototype.use = function() { return this.json['use']; }; /** The minimum number of times this parameter SHALL appear in the request or response. @returns {Array} an array of {@link Number} objects */ OperationDefinitionParameterComponent.prototype.min = function() { return this.json['min']; }; /** The maximum number of times this element is permitted to appear in the request or response. @returns {Array} an array of {@link String} objects */ OperationDefinitionParameterComponent.prototype.max = function() { return this.json['max']; }; /** Describes the meaning or use of this parameter. @returns {Array} an array of {@link String} objects */ OperationDefinitionParameterComponent.prototype.documentation = function() { return this.json['documentation']; }; /** The type for this parameter. @returns {Coding} */ OperationDefinitionParameterComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** A profile the specifies the rules that this parameter must conform to. @returns {Reference} */ OperationDefinitionParameterComponent.prototype.profile = function() { if (this.json['profile']) { return new Reference(this.json['profile']); } }; return OperationDefinitionParameterComponent; })(BackboneElement); /** A formal computable definition of an operation (on the RESTful interface) or a named query (using the search interaction). @class OperationDefinition @exports OperationDefinition as OperationDefinition */ OperationDefinition = (function(superClass) { extend(OperationDefinition, superClass); function OperationDefinition(json) { this.json = json; OperationDefinition.__super__.constructor.call(this, this.json); } /** The identifier that is used to identify this operation definition when it is referenced in a specification, model, design or an instance (should be globally unique OID, UUID, or URI). @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.identifier = function() { return this.json['identifier']; }; /** The identifier that is used to identify this version of the profile when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the profile author manually and the value should be a timestamp. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.version = function() { return this.json['version']; }; /** A free text natural language name identifying the Profile. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.title = function() { return this.json['title']; }; /** Details of the individual or organization who accepts responsibility for publishing the profile. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.publisher = function() { return this.json['publisher']; }; /** Contact details to assist a user in finding and communicating with the publisher. @returns {Array} an array of {@link ContactPoint} objects */ OperationDefinition.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** A free text natural language description of the profile and its use. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.description = function() { return this.json['description']; }; /** A set of terms from external terminologies that may be used to assist with indexing and searching of templates. @returns {Array} an array of {@link Coding} objects */ OperationDefinition.prototype.code = function() { var i, item, len, ref, results; if (this.json['code']) { ref = this.json['code']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** The status of the profile. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.status = function() { return this.json['status']; }; /** This profile was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. @returns {Array} an array of {@link boolean} objects */ OperationDefinition.prototype.experimental = function() { return this.json['experimental']; }; /** The date that this version of the profile was published. @returns {Array} an array of {@link Date} objects */ OperationDefinition.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Whether this is operation or named query. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.kind = function() { return this.json['kind']; }; /** The name used to invoke the operation. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.name = function() { return this.json['name']; }; /** Additional information about how to use this operation or named query. @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.notes = function() { return this.json['notes']; }; /** Indicates that this operation definition is a constraining profile on the base. @returns {Reference} */ OperationDefinition.prototype.base = function() { if (this.json['base']) { return new Reference(this.json['base']); } }; /** Indicates whether this operation or named query can be invoked at the system level (e.g. without needing to choose a resource type for the context). @returns {Array} an array of {@link boolean} objects */ OperationDefinition.prototype.system = function() { return this.json['system']; }; /** Indicates whether this operation or named query can be invoked at the resource type level for any given resource type level (e.g. without needing to choose a resource type for the context). @returns {Array} an array of {@link String} objects */ OperationDefinition.prototype.type = function() { return this.json['type']; }; /** Indicates whether this operation can be invoked on a particular instance of one of the given types. @returns {Array} an array of {@link boolean} objects */ OperationDefinition.prototype.instance = function() { return this.json['instance']; }; /** Parameters for the operation/query. @returns {Array} an array of {@link OperationDefinitionParameterComponent} objects */ OperationDefinition.prototype.parameter = function() { var i, item, len, ref, results; if (this.json['parameter']) { ref = this.json['parameter']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new OperationDefinitionParameterComponent(item)); } return results; } }; return OperationDefinition; })(DomainResource); module.exports.OperationDefinition = OperationDefinition; }).call(this); },{"../cql-datatypes":117,"./core":173}],212:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, OperationOutcome, OperationOutcomeIssueComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class OperationOutcomeIssueComponent @exports OperationOutcomeIssueComponent as OperationOutcomeIssueComponent */ OperationOutcomeIssueComponent = (function(superClass) { extend(OperationOutcomeIssueComponent, superClass); function OperationOutcomeIssueComponent(json) { this.json = json; OperationOutcomeIssueComponent.__super__.constructor.call(this, this.json); } /** Indicates whether the issue indicates a variation from successful processing. @returns {Array} an array of {@link String} objects */ OperationOutcomeIssueComponent.prototype.severity = function() { return this.json['severity']; }; /** A code indicating the type of error, warning or information message. @returns {Coding} */ OperationOutcomeIssueComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** Additional description of the issue. @returns {Array} an array of {@link String} objects */ OperationOutcomeIssueComponent.prototype.details = function() { return this.json['details']; }; /** A simple XPath limited to element names, repetition indicators and the default child access that identifies one of the elements in the resource that caused this issue to be raised. @returns {Array} an array of {@link String} objects */ OperationOutcomeIssueComponent.prototype.location = function() { return this.json['location']; }; return OperationOutcomeIssueComponent; })(BackboneElement); /** A collection of error, warning or information messages that result from a system action. @class OperationOutcome @exports OperationOutcome as OperationOutcome */ OperationOutcome = (function(superClass) { extend(OperationOutcome, superClass); function OperationOutcome(json) { this.json = json; OperationOutcome.__super__.constructor.call(this, this.json); } /** An error, warning or information message that results from a system action. @returns {Array} an array of {@link OperationOutcomeIssueComponent} objects */ OperationOutcome.prototype.issue = function() { var i, item, len, ref, results; if (this.json['issue']) { ref = this.json['issue']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new OperationOutcomeIssueComponent(item)); } return results; } }; return OperationOutcome; })(DomainResource); module.exports.OperationOutcome = OperationOutcome; }).call(this); },{"../cql-datatypes":117,"./core":173}],213:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, CoverageComponent, DT, DetailComponent, DiagnosisComponent, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, ItemsComponent, MissingTeethComponent, Narrative, OralHealthClaim, OrthodonticPlanComponent, Parameters, PayeeComponent, Period, ProsthesisComponent, Quantity, Range, Ratio, Reference, Resource, SampledData, SubDetailComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class PayeeComponent @exports PayeeComponent as PayeeComponent */ PayeeComponent = (function(superClass) { extend(PayeeComponent, superClass); function PayeeComponent(json) { this.json = json; PayeeComponent.__super__.constructor.call(this, this.json); } /** Party to be reimbursed: Subscriber, provider, other. @returns {Coding} */ PayeeComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The provider who is to be reimbursed for the claim (the party to whom any benefit is assigned). @returns {Reference} */ PayeeComponent.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization who is to be reimbursed for the claim (the party to whom any benefit is assigned). @returns {Reference} */ PayeeComponent.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The person other than the subscriber who is to be reimbursed for the claim (the party to whom any benefit is assigned). @returns {Reference} */ PayeeComponent.prototype.person = function() { if (this.json['person']) { return new Reference(this.json['person']); } }; return PayeeComponent; })(BackboneElement); /** Embedded class @class DiagnosisComponent @exports DiagnosisComponent as DiagnosisComponent */ DiagnosisComponent = (function(superClass) { extend(DiagnosisComponent, superClass); function DiagnosisComponent(json) { this.json = json; DiagnosisComponent.__super__.constructor.call(this, this.json); } /** Sequence of diagnosis. @returns {Array} an array of {@link Number} objects */ DiagnosisComponent.prototype.sequence = function() { return this.json['sequence']; }; /** The diagnosis. @returns {Coding} */ DiagnosisComponent.prototype.diagnosis = function() { if (this.json['diagnosis']) { return new Coding(this.json['diagnosis']); } }; return DiagnosisComponent; })(BackboneElement); /** Embedded class @class CoverageComponent @exports CoverageComponent as CoverageComponent */ CoverageComponent = (function(superClass) { extend(CoverageComponent, superClass); function CoverageComponent(json) { this.json = json; CoverageComponent.__super__.constructor.call(this, this.json); } /** A service line item. @returns {Array} an array of {@link Number} objects */ CoverageComponent.prototype.sequence = function() { return this.json['sequence']; }; /** The instance number of the Coverage which is the focus for adjudication, that is the Coverage to which the claim is to be adjudicated against. @returns {Array} an array of {@link boolean} objects */ CoverageComponent.prototype.focal = function() { return this.json['focal']; }; /** Reference to the program or plan identification, underwriter or payor. @returns {Reference} */ CoverageComponent.prototype.coverage = function() { if (this.json['coverage']) { return new Reference(this.json['coverage']); } }; /** The contract number of a business agrement which describes the terms and conditions. @returns {Array} an array of {@link String} objects */ CoverageComponent.prototype.businessArrangement = function() { return this.json['businessArrangement']; }; /** The relationship of the patient to the subscriber. @returns {Coding} */ CoverageComponent.prototype.relationship = function() { if (this.json['relationship']) { return new Coding(this.json['relationship']); } }; /** A list of references from the Insurer to which these services pertain. @returns {Array} an array of {@link String} objects */ CoverageComponent.prototype.preauthref = function() { return this.json['preauthref']; }; /** The Coverages adjudication details. @returns {Reference} */ CoverageComponent.prototype.claimResponse = function() { if (this.json['claimResponse']) { return new Reference(this.json['claimResponse']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ CoverageComponent.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; return CoverageComponent; })(BackboneElement); /** Embedded class @class MissingTeethComponent @exports MissingTeethComponent as MissingTeethComponent */ MissingTeethComponent = (function(superClass) { extend(MissingTeethComponent, superClass); function MissingTeethComponent(json) { this.json = json; MissingTeethComponent.__super__.constructor.call(this, this.json); } /** The code identifying which tooth is missing. @returns {Coding} */ MissingTeethComponent.prototype.tooth = function() { if (this.json['tooth']) { return new Coding(this.json['tooth']); } }; /** Missing reason may be: E-extraction, O-other. @returns {Coding} */ MissingTeethComponent.prototype.reason = function() { if (this.json['reason']) { return new Coding(this.json['reason']); } }; /** The date of the extraction either known from records or patient reported estimate. @returns {Array} an array of {@link Date} objects */ MissingTeethComponent.prototype.extractiondate = function() { if (this.json['extractiondate']) { return DT.DateTime.parse(this.json['extractiondate']); } }; return MissingTeethComponent; })(BackboneElement); /** Embedded class @class OrthodonticPlanComponent @exports OrthodonticPlanComponent as OrthodonticPlanComponent */ OrthodonticPlanComponent = (function(superClass) { extend(OrthodonticPlanComponent, superClass); function OrthodonticPlanComponent(json) { this.json = json; OrthodonticPlanComponent.__super__.constructor.call(this, this.json); } /** The intended start date for service. @returns {Array} an array of {@link Date} objects */ OrthodonticPlanComponent.prototype.start = function() { if (this.json['start']) { return DT.DateTime.parse(this.json['start']); } }; /** The estimated first examination fee. @returns {Money} */ OrthodonticPlanComponent.prototype.examFee = function() { if (this.json['examFee']) { return new Money(this.json['examFee']); } }; /** The estimated diagnostic fee. @returns {Money} */ OrthodonticPlanComponent.prototype.diagnosticFee = function() { if (this.json['diagnosticFee']) { return new Money(this.json['diagnosticFee']); } }; /** The estimated initial payment. @returns {Money} */ OrthodonticPlanComponent.prototype.initialPayment = function() { if (this.json['initialPayment']) { return new Money(this.json['initialPayment']); } }; /** The estimated treatment duration in months. @returns {Array} an array of {@link Number} objects */ OrthodonticPlanComponent.prototype.durationMonths = function() { return this.json['durationMonths']; }; /** The anticipated number of payments. @returns {Array} an array of {@link Number} objects */ OrthodonticPlanComponent.prototype.paymentCount = function() { return this.json['paymentCount']; }; /** The anticipated payment amount. @returns {Money} */ OrthodonticPlanComponent.prototype.periodicPayment = function() { if (this.json['periodicPayment']) { return new Money(this.json['periodicPayment']); } }; return OrthodonticPlanComponent; })(BackboneElement); /** Embedded class @class SubDetailComponent @exports SubDetailComponent as SubDetailComponent */ SubDetailComponent = (function(superClass) { extend(SubDetailComponent, superClass); function SubDetailComponent(json) { this.json = json; SubDetailComponent.__super__.constructor.call(this, this.json); } /** A service line number. @returns {Array} an array of {@link Number} objects */ SubDetailComponent.prototype.sequence = function() { return this.json['sequence']; }; /** The type of product or service. @returns {Coding} */ SubDetailComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The fee for an addtional service or product or charge. @returns {Coding} */ SubDetailComponent.prototype.service = function() { if (this.json['service']) { return new Coding(this.json['service']); } }; /** The number of repetitions of a service or product. @returns {Quantity} */ SubDetailComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** The fee for an addtional service or product or charge. @returns {Money} */ SubDetailComponent.prototype.unitPrice = function() { if (this.json['unitPrice']) { return new Money(this.json['unitPrice']); } }; /** A real number that represents a multiplier used in determining the overall value of services delivered and/or goods received. The concept of a Factor allows for a discount or surcharge multiplier to be applied to a monetary amount. @returns {Array} an array of {@link Number} objects */ SubDetailComponent.prototype.factor = function() { return this.json['factor']; }; /** An amount that expresses the weighting (based on difficulty, cost and/or resource intensiveness) associated with the good or service delivered. The concept of Points allows for assignment of point values for services and/or goods, such that a monetary amount can be assigned to each point. @returns {Array} an array of {@link Number} objects */ SubDetailComponent.prototype.points = function() { return this.json['points']; }; /** The quantity times the unit price for an addtional service or product or charge. For example, the formula: unit Quantity * unit Price (Cost per Point) * factor Number * points = net Amount. Quantity, factor and points are assumed to be 1 if not supplied. @returns {Money} */ SubDetailComponent.prototype.net = function() { if (this.json['net']) { return new Money(this.json['net']); } }; /** List of Unique Device Identifiers associated with this line item. @returns {Coding} */ SubDetailComponent.prototype.udi = function() { if (this.json['udi']) { return new Coding(this.json['udi']); } }; return SubDetailComponent; })(BackboneElement); /** Embedded class @class DetailComponent @exports DetailComponent as DetailComponent */ DetailComponent = (function(superClass) { extend(DetailComponent, superClass); function DetailComponent(json) { this.json = json; DetailComponent.__super__.constructor.call(this, this.json); } /** A service line number. @returns {Array} an array of {@link Number} objects */ DetailComponent.prototype.sequence = function() { return this.json['sequence']; }; /** The type of product or service. @returns {Coding} */ DetailComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** If a grouping item then 'GROUP' otherwise it is a node therefore a code to indicate the Professional Service or Product supplied. @returns {Coding} */ DetailComponent.prototype.service = function() { if (this.json['service']) { return new Coding(this.json['service']); } }; /** The number of repetitions of a service or product. @returns {Quantity} */ DetailComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** If the item is a node then this is the fee for the product or service, otherwise this is the total of the fees for the children of the group. @returns {Money} */ DetailComponent.prototype.unitPrice = function() { if (this.json['unitPrice']) { return new Money(this.json['unitPrice']); } }; /** A real number that represents a multiplier used in determining the overall value of services delivered and/or goods received. The concept of a Factor allows for a discount or surcharge multiplier to be applied to a monetary amount. @returns {Array} an array of {@link Number} objects */ DetailComponent.prototype.factor = function() { return this.json['factor']; }; /** An amount that expresses the weighting (based on difficulty, cost and/or resource intensiveness) associated with the good or service delivered. The concept of Points allows for assignment of point values for services and/or goods, such that a monetary amount can be assigned to each point. @returns {Array} an array of {@link Number} objects */ DetailComponent.prototype.points = function() { return this.json['points']; }; /** The quantity times the unit price for an addtional service or product or charge. For example, the formula: unit Quantity * unit Price (Cost per Point) * factor Number * points = net Amount. Quantity, factor and points are assumed to be 1 if not supplied. @returns {Money} */ DetailComponent.prototype.net = function() { if (this.json['net']) { return new Money(this.json['net']); } }; /** List of Unique Device Identifiers associated with this line item. @returns {Coding} */ DetailComponent.prototype.udi = function() { if (this.json['udi']) { return new Coding(this.json['udi']); } }; /** Third tier of goods and services. @returns {Array} an array of {@link SubDetailComponent} objects */ DetailComponent.prototype.subDetail = function() { var i, item, len, ref, results; if (this.json['subDetail']) { ref = this.json['subDetail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SubDetailComponent(item)); } return results; } }; return DetailComponent; })(BackboneElement); /** Embedded class @class ProsthesisComponent @exports ProsthesisComponent as ProsthesisComponent */ ProsthesisComponent = (function(superClass) { extend(ProsthesisComponent, superClass); function ProsthesisComponent(json) { this.json = json; ProsthesisComponent.__super__.constructor.call(this, this.json); } /** Is this the initial placement of a fixed prosthesis?. @returns {Array} an array of {@link boolean} objects */ ProsthesisComponent.prototype.initial = function() { return this.json['initial']; }; /** Date of the initial placement. @returns {Array} an array of {@link Date} objects */ ProsthesisComponent.prototype.priorDate = function() { if (this.json['priorDate']) { return DT.DateTime.parse(this.json['priorDate']); } }; /** Material of the prior denture or bridge prosthesis. (Oral). @returns {Coding} */ ProsthesisComponent.prototype.priorMaterial = function() { if (this.json['priorMaterial']) { return new Coding(this.json['priorMaterial']); } }; return ProsthesisComponent; })(BackboneElement); /** Embedded class @class ItemsComponent @exports ItemsComponent as ItemsComponent */ ItemsComponent = (function(superClass) { extend(ItemsComponent, superClass); function ItemsComponent(json) { this.json = json; ItemsComponent.__super__.constructor.call(this, this.json); } /** A service line number. @returns {Array} an array of {@link Number} objects */ ItemsComponent.prototype.sequence = function() { return this.json['sequence']; }; /** The type of product or service. @returns {Coding} */ ItemsComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ ItemsComponent.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** If a grouping item then 'GROUP' otherwise it is a node therefore a code to indicate the Professional Service or Product supplied. @returns {Coding} */ ItemsComponent.prototype.service = function() { if (this.json['service']) { return new Coding(this.json['service']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ ItemsComponent.prototype.serviceDate = function() { if (this.json['serviceDate']) { return DT.DateTime.parse(this.json['serviceDate']); } }; /** The number of repetitions of a service or product. @returns {Quantity} */ ItemsComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** If the item is a node then this is the fee for the product or service, otherwise this is the total of the fees for the children of the group. @returns {Money} */ ItemsComponent.prototype.unitPrice = function() { if (this.json['unitPrice']) { return new Money(this.json['unitPrice']); } }; /** A real number that represents a multiplier used in determining the overall value of services delivered and/or goods received. The concept of a Factor allows for a discount or surcharge multiplier to be applied to a monetary amount. @returns {Array} an array of {@link Number} objects */ ItemsComponent.prototype.factor = function() { return this.json['factor']; }; /** An amount that expresses the weighting (based on difficulty, cost and/or resource intensiveness) associated with the good or service delivered. The concept of Points allows for assignment of point values for services and/or goods, such that a monetary amount can be assigned to each point. @returns {Array} an array of {@link Number} objects */ ItemsComponent.prototype.points = function() { return this.json['points']; }; /** The quantity times the unit price for an addtional service or product or charge. For example, the formula: unit Quantity * unit Price (Cost per Point) * factor Number * points = net Amount. Quantity, factor and points are assumed to be 1 if not supplied. @returns {Money} */ ItemsComponent.prototype.net = function() { if (this.json['net']) { return new Money(this.json['net']); } }; /** List of Unique Device Identifiers associated with this line item. @returns {Coding} */ ItemsComponent.prototype.udi = function() { if (this.json['udi']) { return new Coding(this.json['udi']); } }; /** Physical service site on the patient (limb, tooth, etc). @returns {Coding} */ ItemsComponent.prototype.bodySite = function() { if (this.json['bodySite']) { return new Coding(this.json['bodySite']); } }; /** A region or surface of the site, eg. limb region or tooth surface(s). @returns {Array} an array of {@link Coding} objects */ ItemsComponent.prototype.subsite = function() { var i, item, len, ref, results; if (this.json['subsite']) { ref = this.json['subsite']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Item typification or modifiers codes, eg for Oral whether the treatment is cosmetic or associated with TMJ, or an appliance was lost or stolen. @returns {Array} an array of {@link Coding} objects */ ItemsComponent.prototype.modifier = function() { var i, item, len, ref, results; if (this.json['modifier']) { ref = this.json['modifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Second tier of goods and services. @returns {Array} an array of {@link DetailComponent} objects */ ItemsComponent.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DetailComponent(item)); } return results; } }; /** The materials and placement date of prior fixed prosthesis. @returns {ProsthesisComponent} */ ItemsComponent.prototype.prosthesis = function() { if (this.json['prosthesis']) { return new ProsthesisComponent(this.json['prosthesis']); } }; return ItemsComponent; })(BackboneElement); /** A provider issued list of services and products provided, or to be provided, to a patient which is provided to an insurer for payment recovery. @class OralHealthClaim @exports OralHealthClaim as OralHealthClaim */ OralHealthClaim = (function(superClass) { extend(OralHealthClaim, superClass); function OralHealthClaim(json) { this.json = json; OralHealthClaim.__super__.constructor.call(this, this.json); } /** The business identifier for the instance: invoice number, claim number, pre-determination or pre-authorization number. @returns {Array} an array of {@link Identifier} objects */ OralHealthClaim.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the specification on which this instance relies. @returns {Coding} */ OralHealthClaim.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The version of the specification from which the original instance was created. @returns {Coding} */ OralHealthClaim.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ OralHealthClaim.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Insurer Identifier, typical BIN number (6 digit). @returns {Reference} */ OralHealthClaim.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The provider which is responsible for the bill, claim pre-determination, pre-authorization. @returns {Reference} */ OralHealthClaim.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the bill, claim pre-determination, pre-authorization. @returns {Reference} */ OralHealthClaim.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Complete (Bill or Claim), Proposed (Pre-Authorization), Exploratory (Pre-determination). @returns {Array} an array of {@link String} objects */ OralHealthClaim.prototype.use = function() { return this.json['use']; }; /** Immediate (STAT), best effort (NORMAL), deferred (DEFER). @returns {Coding} */ OralHealthClaim.prototype.priority = function() { if (this.json['priority']) { return new Coding(this.json['priority']); } }; /** In the case of a Pre-Determination/Pre-Authorization the provider may request that funds in the amount of the expected Benefit be reserved ('Patient' or 'Provider') to pay for the Benefits determined on the subsequent claim(s). 'None' explicitly indicates no funds reserving is requested. @returns {Coding} */ OralHealthClaim.prototype.fundsReserve = function() { if (this.json['fundsReserve']) { return new Coding(this.json['fundsReserve']); } }; /** Person who created the invoice/claim/pre-determination or pre-authorization. @returns {Reference} */ OralHealthClaim.prototype.enterer = function() { if (this.json['enterer']) { return new Reference(this.json['enterer']); } }; /** Facility where the services were provided. @returns {Reference} */ OralHealthClaim.prototype.facility = function() { if (this.json['facility']) { return new Reference(this.json['facility']); } }; /** Theparty to be reimbused for the services. @returns {PayeeComponent} */ OralHealthClaim.prototype.payee = function() { if (this.json['payee']) { return new PayeeComponent(this.json['payee']); } }; /** The referral resource which lists the date, practitioner, reason and other supporting information. @returns {Reference} */ OralHealthClaim.prototype.referral = function() { if (this.json['referral']) { return new Reference(this.json['referral']); } }; /** Ordered list of patient diagnosis for which care is sought. @returns {Array} an array of {@link DiagnosisComponent} objects */ OralHealthClaim.prototype.diagnosis = function() { var i, item, len, ref, results; if (this.json['diagnosis']) { ref = this.json['diagnosis']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DiagnosisComponent(item)); } return results; } }; /** List of patient conditions for which care is sought. @returns {Array} an array of {@link Coding} objects */ OralHealthClaim.prototype.condition = function() { var i, item, len, ref, results; if (this.json['condition']) { ref = this.json['condition']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Patient Resource. @returns {Reference} */ OralHealthClaim.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** Financial instrument by which payment information for health care. @returns {Array} an array of {@link CoverageComponent} objects */ OralHealthClaim.prototype.coverage = function() { var i, item, len, ref, results; if (this.json['coverage']) { ref = this.json['coverage']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CoverageComponent(item)); } return results; } }; /** Factors which may influence the applicability of coverage. @returns {Array} an array of {@link Coding} objects */ OralHealthClaim.prototype.exception = function() { var i, item, len, ref, results; if (this.json['exception']) { ref = this.json['exception']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Name of school for over-aged dependants. @returns {Array} an array of {@link String} objects */ OralHealthClaim.prototype.school = function() { return this.json['school']; }; /** Date of an accident which these services are addessing. @returns {Array} an array of {@link Date} objects */ OralHealthClaim.prototype.accident = function() { if (this.json['accident']) { return DT.DateTime.parse(this.json['accident']); } }; /** Type of accident: work, auto, etc. @returns {Coding} */ OralHealthClaim.prototype.accidentType = function() { if (this.json['accidentType']) { return new Coding(this.json['accidentType']); } }; /** A list of intervention and exception codes which may influence the adjudication of the claim. @returns {Array} an array of {@link Coding} objects */ OralHealthClaim.prototype.interventionException = function() { var i, item, len, ref, results; if (this.json['interventionException']) { ref = this.json['interventionException']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** A list of teeth which would be expected but are not found due to having been previously extracted or for other reasons. @returns {Array} an array of {@link MissingTeethComponent} objects */ OralHealthClaim.prototype.missingteeth = function() { var i, item, len, ref, results; if (this.json['missingteeth']) { ref = this.json['missingteeth']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new MissingTeethComponent(item)); } return results; } }; /** The highlevel detail sof an Orthodonic Treatment Plan. @returns {OrthodonticPlanComponent} */ OralHealthClaim.prototype.orthoPlan = function() { if (this.json['orthoPlan']) { return new OrthodonticPlanComponent(this.json['orthoPlan']); } }; /** First tier of goods and services. @returns {Array} an array of {@link ItemsComponent} objects */ OralHealthClaim.prototype.item = function() { var i, item, len, ref, results; if (this.json['item']) { ref = this.json['item']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ItemsComponent(item)); } return results; } }; /** Code to indicate that Xrays, images, emails, documents, models or attachments are being sent in support of this submission. @returns {Array} an array of {@link Coding} objects */ OralHealthClaim.prototype.additionalMaterials = function() { var i, item, len, ref, results; if (this.json['additionalMaterials']) { ref = this.json['additionalMaterials']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; return OralHealthClaim; })(DomainResource); module.exports.OralHealthClaim = OralHealthClaim; }).call(this); },{"../cql-datatypes":117,"./core":173}],214:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Order, OrderWhenComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class OrderWhenComponent @exports OrderWhenComponent as OrderWhenComponent */ OrderWhenComponent = (function(superClass) { extend(OrderWhenComponent, superClass); function OrderWhenComponent(json) { this.json = json; OrderWhenComponent.__super__.constructor.call(this, this.json); } /** Code specifies when request should be done. The code may simply be a priority code. @returns {CodeableConcept} */ OrderWhenComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** A formal schedule. @returns {Timing} */ OrderWhenComponent.prototype.schedule = function() { if (this.json['schedule']) { return new Timing(this.json['schedule']); } }; return OrderWhenComponent; })(BackboneElement); /** A request to perform an action. @class Order @exports Order as Order */ Order = (function(superClass) { extend(Order, superClass); function Order(json) { this.json = json; Order.__super__.constructor.call(this, this.json); } /** Identifiers assigned to this order by the orderer or by the receiver. @returns {Array} an array of {@link Identifier} objects */ Order.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** When the order was made. @returns {Array} an array of {@link Date} objects */ Order.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Patient this order is about. @returns {Reference} */ Order.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Who initiated the order. @returns {Reference} */ Order.prototype.source = function() { if (this.json['source']) { return new Reference(this.json['source']); } }; /** Who is intended to fulfill the order. @returns {Reference} */ Order.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** Text - why the order was made. @returns {CodeableConcept} */ Order.prototype.reasonCodeableConcept = function() { if (this.json['reasonCodeableConcept']) { return new CodeableConcept(this.json['reasonCodeableConcept']); } }; /** Text - why the order was made. @returns {Reference} */ Order.prototype.reasonReference = function() { if (this.json['reasonReference']) { return new Reference(this.json['reasonReference']); } }; /** If required by policy. @returns {Reference} */ Order.prototype.authority = function() { if (this.json['authority']) { return new Reference(this.json['authority']); } }; /** When order should be fulfilled. @returns {OrderWhenComponent} */ Order.prototype.when = function() { if (this.json['when']) { return new OrderWhenComponent(this.json['when']); } }; /** What action is being ordered. @returns {Array} an array of {@link Reference} objects */ Order.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return Order; })(DomainResource); module.exports.Order = Order; }).call(this); },{"../cql-datatypes":117,"./core":173}],215:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, OrderResponse, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A response to an order. @class OrderResponse @exports OrderResponse as OrderResponse */ OrderResponse = (function(superClass) { extend(OrderResponse, superClass); function OrderResponse(json) { this.json = json; OrderResponse.__super__.constructor.call(this, this.json); } /** Identifiers assigned to this order. The identifiers are usually assigned by the system responding to the order, but they may be provided or added to by other systems. @returns {Array} an array of {@link Identifier} objects */ OrderResponse.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** A reference to the order that this is in response to. @returns {Reference} */ OrderResponse.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** The date and time at which this order response was made (created/posted). @returns {Array} an array of {@link Date} objects */ OrderResponse.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The person, organization, or device credited with making the response. @returns {Reference} */ OrderResponse.prototype.who = function() { if (this.json['who']) { return new Reference(this.json['who']); } }; /** A reference to an authority policy that is the reason for the response. Usually this is used when the order is rejected, to provide a reason for rejection. @returns {CodeableConcept} */ OrderResponse.prototype.authorityCodeableConcept = function() { if (this.json['authorityCodeableConcept']) { return new CodeableConcept(this.json['authorityCodeableConcept']); } }; /** A reference to an authority policy that is the reason for the response. Usually this is used when the order is rejected, to provide a reason for rejection. @returns {Reference} */ OrderResponse.prototype.authorityReference = function() { if (this.json['authorityReference']) { return new Reference(this.json['authorityReference']); } }; /** What this response says about the status of the original order. @returns {Array} an array of {@link String} objects */ OrderResponse.prototype.code = function() { return this.json['code']; }; /** Additional description about the response - e.g. a text description provided by a human user when making decisions about the order. @returns {Array} an array of {@link String} objects */ OrderResponse.prototype.description = function() { return this.json['description']; }; /** Links to resources that provide details of the outcome of performing the order. E.g. Diagnostic Reports in a response that is made to an order that referenced a diagnostic order. @returns {Array} an array of {@link Reference} objects */ OrderResponse.prototype.fulfillment = function() { var i, item, len, ref, results; if (this.json['fulfillment']) { ref = this.json['fulfillment']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return OrderResponse; })(DomainResource); module.exports.OrderResponse = OrderResponse; }).call(this); },{"../cql-datatypes":117,"./core":173}],216:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Organization, OrganizationContactComponent, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class OrganizationContactComponent @exports OrganizationContactComponent as OrganizationContactComponent */ OrganizationContactComponent = (function(superClass) { extend(OrganizationContactComponent, superClass); function OrganizationContactComponent(json) { this.json = json; OrganizationContactComponent.__super__.constructor.call(this, this.json); } /** Indicates a purpose for which the contact can be reached. @returns {CodeableConcept} */ OrganizationContactComponent.prototype.purpose = function() { if (this.json['purpose']) { return new CodeableConcept(this.json['purpose']); } }; /** A name associated with the contact. @returns {HumanName} */ OrganizationContactComponent.prototype.name = function() { if (this.json['name']) { return new HumanName(this.json['name']); } }; /** A contact detail (e.g. a telephone number or an email address) by which the party may be contacted. @returns {Array} an array of {@link ContactPoint} objects */ OrganizationContactComponent.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** Visiting or postal addresses for the contact. @returns {Address} */ OrganizationContactComponent.prototype.address = function() { if (this.json['address']) { return new Address(this.json['address']); } }; /** Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. @returns {Array} an array of {@link String} objects */ OrganizationContactComponent.prototype.gender = function() { return this.json['gender']; }; return OrganizationContactComponent; })(BackboneElement); /** A formally or informally recognized grouping of people or organizations formed for the purpose of achieving some form of collective action. Includes companies, institutions, corporations, departments, community groups, healthcare practice groups, etc. @class Organization @exports Organization as Organization */ Organization = (function(superClass) { extend(Organization, superClass); function Organization(json) { this.json = json; Organization.__super__.constructor.call(this, this.json); } /** Identifier for the organization that is used to identify the organization across multiple disparate systems. @returns {Array} an array of {@link Identifier} objects */ Organization.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** A name associated with the organization. @returns {Array} an array of {@link String} objects */ Organization.prototype.name = function() { return this.json['name']; }; /** The kind of organization that this is. @returns {CodeableConcept} */ Organization.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** A contact detail for the organization. @returns {Array} an array of {@link ContactPoint} objects */ Organization.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** An address for the organization. @returns {Array} an array of {@link Address} objects */ Organization.prototype.address = function() { var i, item, len, ref, results; if (this.json['address']) { ref = this.json['address']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Address(item)); } return results; } }; /** The organization of which this organization forms a part. @returns {Reference} */ Organization.prototype.partOf = function() { if (this.json['partOf']) { return new Reference(this.json['partOf']); } }; /** Contact for the organization for a certain purpose. @returns {Array} an array of {@link OrganizationContactComponent} objects */ Organization.prototype.contact = function() { var i, item, len, ref, results; if (this.json['contact']) { ref = this.json['contact']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new OrganizationContactComponent(item)); } return results; } }; /** Location(s) the organization uses to provide services. @returns {Array} an array of {@link Reference} objects */ Organization.prototype.location = function() { var i, item, len, ref, results; if (this.json['location']) { ref = this.json['location']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Whether the organization's record is still in active use. @returns {Array} an array of {@link boolean} objects */ Organization.prototype.active = function() { return this.json['active']; }; return Organization; })(DomainResource); module.exports.Organization = Organization; }).call(this); },{"../cql-datatypes":117,"./core":173}],217:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Other, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Other is a conformant for handling resource concepts not yet defined for FHIR or outside HL7's scope of interest. @class Other @exports Other as Other */ Other = (function(superClass) { extend(Other, superClass); function Other(json) { this.json = json; Other.__super__.constructor.call(this, this.json); } /** Identifier assigned to the resource for business purposes, outside the context of FHIR. @returns {Array} an array of {@link Identifier} objects */ Other.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Identifies the 'type' of resource - equivalent to the resource name for other resources. @returns {CodeableConcept} */ Other.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** Identifies the patient, practitioner, device or any other resource that is the "focus" of this resoruce. @returns {Reference} */ Other.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Indicates who was responsible for creating the resource instance. @returns {Reference} */ Other.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** Identifies when the resource was first created. @returns {Array} an array of {@link Date} objects */ Other.prototype.created = function() { if (this.json['created']) { return DT.DateTime.parse(this.json['created']); } }; return Other; })(DomainResource); module.exports.Other = Other; }).call(this); },{"../cql-datatypes":117,"./core":173}],218:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, AnimalComponent, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Patient, PatientLinkComponent, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ContactComponent @exports ContactComponent as ContactComponent */ ContactComponent = (function(superClass) { extend(ContactComponent, superClass); function ContactComponent(json) { this.json = json; ContactComponent.__super__.constructor.call(this, this.json); } /** The nature of the relationship between the patient and the contact person. @returns {Array} an array of {@link CodeableConcept} objects */ ContactComponent.prototype.relationship = function() { var i, item, len, ref, results; if (this.json['relationship']) { ref = this.json['relationship']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** A name associated with the person. @returns {HumanName} */ ContactComponent.prototype.name = function() { if (this.json['name']) { return new HumanName(this.json['name']); } }; /** A contact detail for the person, e.g. a telephone number or an email address. @returns {Array} an array of {@link ContactPoint} objects */ ContactComponent.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** Address for the contact person. @returns {Address} */ ContactComponent.prototype.address = function() { if (this.json['address']) { return new Address(this.json['address']); } }; /** Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. @returns {Array} an array of {@link String} objects */ ContactComponent.prototype.gender = function() { return this.json['gender']; }; /** Organization on behalf of which the contact is acting or for which the contact is working. @returns {Reference} */ ContactComponent.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The period during which this person or organisation is valid to be contacted relating to this patient. @returns {Period} */ ContactComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return ContactComponent; })(BackboneElement); /** Embedded class @class AnimalComponent @exports AnimalComponent as AnimalComponent */ AnimalComponent = (function(superClass) { extend(AnimalComponent, superClass); function AnimalComponent(json) { this.json = json; AnimalComponent.__super__.constructor.call(this, this.json); } /** Identifies the high level categorization of the kind of animal. @returns {CodeableConcept} */ AnimalComponent.prototype.species = function() { if (this.json['species']) { return new CodeableConcept(this.json['species']); } }; /** Identifies the detailed categorization of the kind of animal. @returns {CodeableConcept} */ AnimalComponent.prototype.breed = function() { if (this.json['breed']) { return new CodeableConcept(this.json['breed']); } }; /** Indicates the current state of the animal's reproductive organs. @returns {CodeableConcept} */ AnimalComponent.prototype.genderStatus = function() { if (this.json['genderStatus']) { return new CodeableConcept(this.json['genderStatus']); } }; return AnimalComponent; })(BackboneElement); /** Embedded class @class PatientLinkComponent @exports PatientLinkComponent as PatientLinkComponent */ PatientLinkComponent = (function(superClass) { extend(PatientLinkComponent, superClass); function PatientLinkComponent(json) { this.json = json; PatientLinkComponent.__super__.constructor.call(this, this.json); } /** The other patient resource that the link refers to. @returns {Reference} */ PatientLinkComponent.prototype.other = function() { if (this.json['other']) { return new Reference(this.json['other']); } }; /** The type of link between this patient resource and another patient resource. @returns {Array} an array of {@link String} objects */ PatientLinkComponent.prototype.type = function() { return this.json['type']; }; return PatientLinkComponent; })(BackboneElement); /** Demographics and other administrative information about a person or animal receiving care or other health-related services. @class Patient @exports Patient as Patient */ Patient = (function(superClass) { extend(Patient, superClass); function Patient(json) { this.json = json; Patient.__super__.constructor.call(this, this.json); } /** An identifier that applies to this person as a patient. @returns {Array} an array of {@link Identifier} objects */ Patient.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** A name associated with the individual. @returns {Array} an array of {@link HumanName} objects */ Patient.prototype.name = function() { var i, item, len, ref, results; if (this.json['name']) { ref = this.json['name']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new HumanName(item)); } return results; } }; /** A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted. @returns {Array} an array of {@link ContactPoint} objects */ Patient.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes. @returns {Array} an array of {@link String} objects */ Patient.prototype.gender = function() { return this.json['gender']; }; /** The date and time of birth for the individual. @returns {Array} an array of {@link Date} objects */ Patient.prototype.birthDate = function() { if (this.json['birthDate']) { return DT.DateTime.parse(this.json['birthDate']); } }; /** Indicates if the individual is deceased or not. @returns {Array} an array of {@link boolean} objects */ Patient.prototype.deceasedBoolean = function() { return this.json['deceasedBoolean']; }; /** Indicates if the individual is deceased or not. @returns {Array} an array of {@link Date} objects */ Patient.prototype.deceasedDateTime = function() { if (this.json['deceasedDateTime']) { return DT.DateTime.parse(this.json['deceasedDateTime']); } }; /** Addresses for the individual. @returns {Array} an array of {@link Address} objects */ Patient.prototype.address = function() { var i, item, len, ref, results; if (this.json['address']) { ref = this.json['address']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Address(item)); } return results; } }; /** This field contains a patient's most recent marital (civil) status. @returns {CodeableConcept} */ Patient.prototype.maritalStatus = function() { if (this.json['maritalStatus']) { return new CodeableConcept(this.json['maritalStatus']); } }; /** Indicates whether the patient is part of a multiple or indicates the actual birth order. @returns {Array} an array of {@link boolean} objects */ Patient.prototype.multipleBirthBoolean = function() { return this.json['multipleBirthBoolean']; }; /** Indicates whether the patient is part of a multiple or indicates the actual birth order. @returns {Array} an array of {@link Number} objects */ Patient.prototype.multipleBirthInteger = function() { return this.json['multipleBirthInteger']; }; /** Image of the person. @returns {Array} an array of {@link Attachment} objects */ Patient.prototype.photo = function() { var i, item, len, ref, results; if (this.json['photo']) { ref = this.json['photo']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Attachment(item)); } return results; } }; /** A contact party (e.g. guardian, partner, friend) for the patient. @returns {Array} an array of {@link ContactComponent} objects */ Patient.prototype.contact = function() { var i, item, len, ref, results; if (this.json['contact']) { ref = this.json['contact']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactComponent(item)); } return results; } }; /** This element has a value if the patient is an animal. @returns {AnimalComponent} */ Patient.prototype.animal = function() { if (this.json['animal']) { return new AnimalComponent(this.json['animal']); } }; /** Languages which may be used to communicate with the patient about his or her health. @returns {Array} an array of {@link CodeableConcept} objects */ Patient.prototype.communication = function() { var i, item, len, ref, results; if (this.json['communication']) { ref = this.json['communication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Patient's nominated care provider. @returns {Array} an array of {@link Reference} objects */ Patient.prototype.careProvider = function() { var i, item, len, ref, results; if (this.json['careProvider']) { ref = this.json['careProvider']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Organization that is the custodian of the patient record. @returns {Reference} */ Patient.prototype.managingOrganization = function() { if (this.json['managingOrganization']) { return new Reference(this.json['managingOrganization']); } }; /** Link to another patient resource that concerns the same actual person. @returns {Array} an array of {@link PatientLinkComponent} objects */ Patient.prototype.link = function() { var i, item, len, ref, results; if (this.json['link']) { ref = this.json['link']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new PatientLinkComponent(item)); } return results; } }; /** Whether this patient record is in active use. @returns {Array} an array of {@link boolean} objects */ Patient.prototype.active = function() { return this.json['active']; }; return Patient; })(DomainResource); module.exports.Patient = Patient; }).call(this); },{"../cql-datatypes":117,"./core":173}],219:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, PaymentNotice, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides the request and response details for the request for which the payment status is being reported. @class PaymentNotice @exports PaymentNotice as PaymentNotice */ PaymentNotice = (function(superClass) { extend(PaymentNotice, superClass); function PaymentNotice(json) { this.json = json; PaymentNotice.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ PaymentNotice.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ PaymentNotice.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ PaymentNotice.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ PaymentNotice.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who is target of the request. @returns {Reference} */ PaymentNotice.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ PaymentNotice.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ PaymentNotice.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Reference of resource to reverse. @returns {Reference} */ PaymentNotice.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Reference of response to resource to reverse. @returns {Reference} */ PaymentNotice.prototype.response = function() { if (this.json['response']) { return new Reference(this.json['response']); } }; /** The payment status, typically paid: payment sent, cleared: payment received. @returns {Coding} */ PaymentNotice.prototype.paymentStatus = function() { if (this.json['paymentStatus']) { return new Coding(this.json['paymentStatus']); } }; return PaymentNotice; })(DomainResource); module.exports.PaymentNotice = PaymentNotice; }).call(this); },{"../cql-datatypes":117,"./core":173}],220:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DetailsComponent, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, NotesComponent, Parameters, PaymentReconciliation, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class DetailsComponent @exports DetailsComponent as DetailsComponent */ DetailsComponent = (function(superClass) { extend(DetailsComponent, superClass); function DetailsComponent(json) { this.json = json; DetailsComponent.__super__.constructor.call(this, this.json); } /** Code to indicate the nature of the payment, adjustment, funds advance, etc. @returns {Coding} */ DetailsComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The claim or financial resource. @returns {Reference} */ DetailsComponent.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** The claim response resource. @returns {Reference} */ DetailsComponent.prototype.responce = function() { if (this.json['responce']) { return new Reference(this.json['responce']); } }; /** The Organization which submitted the invoice or financial transaction. @returns {Reference} */ DetailsComponent.prototype.submitter = function() { if (this.json['submitter']) { return new Reference(this.json['submitter']); } }; /** The organization which is receiving the payment. @returns {Reference} */ DetailsComponent.prototype.payee = function() { if (this.json['payee']) { return new Reference(this.json['payee']); } }; /** The date of the invoice or financial resource. @returns {Array} an array of {@link Date} objects */ DetailsComponent.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Amount paid for this detail. @returns {Money} */ DetailsComponent.prototype.amount = function() { if (this.json['amount']) { return new Money(this.json['amount']); } }; return DetailsComponent; })(BackboneElement); /** Embedded class @class NotesComponent @exports NotesComponent as NotesComponent */ NotesComponent = (function(superClass) { extend(NotesComponent, superClass); function NotesComponent(json) { this.json = json; NotesComponent.__super__.constructor.call(this, this.json); } /** The note purpose: Print/Display. @returns {Coding} */ NotesComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The note text. @returns {Array} an array of {@link String} objects */ NotesComponent.prototype.text = function() { return this.json['text']; }; return NotesComponent; })(BackboneElement); /** This resource provides payment details supporting a bulk payment, or the errors in, processing a ReconciliationRequest resource. @class PaymentReconciliation @exports PaymentReconciliation as PaymentReconciliation */ PaymentReconciliation = (function(superClass) { extend(PaymentReconciliation, superClass); function PaymentReconciliation(json) { this.json = json; PaymentReconciliation.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ PaymentReconciliation.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Original request resource referrence. @returns {Reference} */ PaymentReconciliation.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Transaction status: error, complete. @returns {Array} an array of {@link String} objects */ PaymentReconciliation.prototype.outcome = function() { return this.json['outcome']; }; /** A description of the status of the adjudication. @returns {Array} an array of {@link String} objects */ PaymentReconciliation.prototype.disposition = function() { return this.json['disposition']; }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ PaymentReconciliation.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ PaymentReconciliation.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ PaymentReconciliation.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who produced this adjudicated response. @returns {Reference} */ PaymentReconciliation.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ PaymentReconciliation.prototype.requestProvider = function() { if (this.json['requestProvider']) { return new Reference(this.json['requestProvider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ PaymentReconciliation.prototype.requestOrganization = function() { if (this.json['requestOrganization']) { return new Reference(this.json['requestOrganization']); } }; /** List of individual settlement amounts and the corresponding transaction. @returns {Array} an array of {@link DetailsComponent} objects */ PaymentReconciliation.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new DetailsComponent(item)); } return results; } }; /** The form to be used for printing the content. @returns {Coding} */ PaymentReconciliation.prototype.form = function() { if (this.json['form']) { return new Coding(this.json['form']); } }; /** Total payment amount. @returns {Money} */ PaymentReconciliation.prototype.total = function() { if (this.json['total']) { return new Money(this.json['total']); } }; /** List of errors detected in the request. @returns {Array} an array of {@link Coding} objects */ PaymentReconciliation.prototype.error = function() { var i, item, len, ref, results; if (this.json['error']) { ref = this.json['error']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Suite of notes. @returns {Array} an array of {@link NotesComponent} objects */ PaymentReconciliation.prototype.note = function() { var i, item, len, ref, results; if (this.json['note']) { ref = this.json['note']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new NotesComponent(item)); } return results; } }; return PaymentReconciliation; })(DomainResource); module.exports.PaymentReconciliation = PaymentReconciliation; }).call(this); },{"../cql-datatypes":117,"./core":173}],221:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, PendedRequest, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides the request and response details for the resource for which the stsatus is to be checked. @class PendedRequest @exports PendedRequest as PendedRequest */ PendedRequest = (function(superClass) { extend(PendedRequest, superClass); function PendedRequest(json) { this.json = json; PendedRequest.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ PendedRequest.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ PendedRequest.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ PendedRequest.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ PendedRequest.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who is target of the request. @returns {Reference} */ PendedRequest.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ PendedRequest.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ PendedRequest.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Reference of resource to reverse. @returns {Reference} */ PendedRequest.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Names of resource types to include. @returns {Array} an array of {@link String} objects */ PendedRequest.prototype.include = function() { return this.json['include']; }; /** Names of resource types to exclude. @returns {Array} an array of {@link String} objects */ PendedRequest.prototype.exclude = function() { return this.json['exclude']; }; /** A period of time during which the fulfilling resources would have been created. @returns {Period} */ PendedRequest.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; return PendedRequest; })(DomainResource); module.exports.PendedRequest = PendedRequest; }).call(this); },{"../cql-datatypes":117,"./core":173}],222:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Practitioner, PractitionerQualificationComponent, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class PractitionerQualificationComponent @exports PractitionerQualificationComponent as PractitionerQualificationComponent */ PractitionerQualificationComponent = (function(superClass) { extend(PractitionerQualificationComponent, superClass); function PractitionerQualificationComponent(json) { this.json = json; PractitionerQualificationComponent.__super__.constructor.call(this, this.json); } /** An identifier that applies to this person's qualification in this role. @returns {Array} an array of {@link Identifier} objects */ PractitionerQualificationComponent.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Coded representation of the qualification. @returns {CodeableConcept} */ PractitionerQualificationComponent.prototype.code = function() { if (this.json['code']) { return new CodeableConcept(this.json['code']); } }; /** Period during which the qualification is valid. @returns {Period} */ PractitionerQualificationComponent.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** Organization that regulates and issues the qualification. @returns {Reference} */ PractitionerQualificationComponent.prototype.issuer = function() { if (this.json['issuer']) { return new Reference(this.json['issuer']); } }; return PractitionerQualificationComponent; })(BackboneElement); /** A person who is directly or indirectly involved in the provisioning of healthcare. @class Practitioner @exports Practitioner as Practitioner */ Practitioner = (function(superClass) { extend(Practitioner, superClass); function Practitioner(json) { this.json = json; Practitioner.__super__.constructor.call(this, this.json); } /** An identifier that applies to this person in this role. @returns {Array} an array of {@link Identifier} objects */ Practitioner.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** A name associated with the person. @returns {HumanName} */ Practitioner.prototype.name = function() { if (this.json['name']) { return new HumanName(this.json['name']); } }; /** A contact detail for the practitioner, e.g. a telephone number or an email address. @returns {Array} an array of {@link ContactPoint} objects */ Practitioner.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** The postal address where the practitioner can be found or visited or to which mail can be delivered. @returns {Array} an array of {@link Address} objects */ Practitioner.prototype.address = function() { var i, item, len, ref, results; if (this.json['address']) { ref = this.json['address']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Address(item)); } return results; } }; /** Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. @returns {Array} an array of {@link String} objects */ Practitioner.prototype.gender = function() { return this.json['gender']; }; /** The date and time of birth for the practitioner. @returns {Array} an array of {@link Date} objects */ Practitioner.prototype.birthDate = function() { if (this.json['birthDate']) { return DT.DateTime.parse(this.json['birthDate']); } }; /** Image of the person. @returns {Array} an array of {@link Attachment} objects */ Practitioner.prototype.photo = function() { var i, item, len, ref, results; if (this.json['photo']) { ref = this.json['photo']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Attachment(item)); } return results; } }; /** The organization that the practitioner represents. @returns {Reference} */ Practitioner.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Roles which this practitioner is authorized to perform for the organization. @returns {Array} an array of {@link CodeableConcept} objects */ Practitioner.prototype.role = function() { var i, item, len, ref, results; if (this.json['role']) { ref = this.json['role']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Specific specialty of the practitioner. @returns {Array} an array of {@link CodeableConcept} objects */ Practitioner.prototype.specialty = function() { var i, item, len, ref, results; if (this.json['specialty']) { ref = this.json['specialty']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The period during which the person is authorized to act as a practitioner in these role(s) for the organization. @returns {Period} */ Practitioner.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** The location(s) at which this practitioner provides care. @returns {Array} an array of {@link Reference} objects */ Practitioner.prototype.location = function() { var i, item, len, ref, results; if (this.json['location']) { ref = this.json['location']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Qualifications obtained by training and certification. @returns {Array} an array of {@link PractitionerQualificationComponent} objects */ Practitioner.prototype.qualification = function() { var i, item, len, ref, results; if (this.json['qualification']) { ref = this.json['qualification']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new PractitionerQualificationComponent(item)); } return results; } }; /** A language the practitioner is able to use in patient communication. @returns {Array} an array of {@link CodeableConcept} objects */ Practitioner.prototype.communication = function() { var i, item, len, ref, results; if (this.json['communication']) { ref = this.json['communication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; return Practitioner; })(DomainResource); module.exports.Practitioner = Practitioner; }).call(this); },{"../cql-datatypes":117,"./core":173}],223:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Procedure, ProcedurePerformerComponent, ProcedureRelatedItemComponent, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ProcedurePerformerComponent @exports ProcedurePerformerComponent as ProcedurePerformerComponent */ ProcedurePerformerComponent = (function(superClass) { extend(ProcedurePerformerComponent, superClass); function ProcedurePerformerComponent(json) { this.json = json; ProcedurePerformerComponent.__super__.constructor.call(this, this.json); } /** The practitioner who was involved in the procedure. @returns {Reference} */ ProcedurePerformerComponent.prototype.person = function() { if (this.json['person']) { return new Reference(this.json['person']); } }; /** E.g. surgeon, anaethetist, endoscopist. @returns {CodeableConcept} */ ProcedurePerformerComponent.prototype.role = function() { if (this.json['role']) { return new CodeableConcept(this.json['role']); } }; return ProcedurePerformerComponent; })(BackboneElement); /** Embedded class @class ProcedureRelatedItemComponent @exports ProcedureRelatedItemComponent as ProcedureRelatedItemComponent */ ProcedureRelatedItemComponent = (function(superClass) { extend(ProcedureRelatedItemComponent, superClass); function ProcedureRelatedItemComponent(json) { this.json = json; ProcedureRelatedItemComponent.__super__.constructor.call(this, this.json); } /** The nature of the relationship. @returns {Array} an array of {@link String} objects */ ProcedureRelatedItemComponent.prototype.type = function() { return this.json['type']; }; /** The related item - e.g. a procedure. @returns {Reference} */ ProcedureRelatedItemComponent.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; return ProcedureRelatedItemComponent; })(BackboneElement); /** An action that is performed on a patient. This can be a physical 'thing' like an operation, or less invasive like counseling or hypnotherapy. @class Procedure @exports Procedure as Procedure */ Procedure = (function(superClass) { extend(Procedure, superClass); function Procedure(json) { this.json = json; Procedure.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this procedure that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ Procedure.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The person on whom the procedure was performed. @returns {Reference} */ Procedure.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The specific procedure that is performed. Use text if the exact nature of the procedure can't be coded. @returns {CodeableConcept} */ Procedure.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Detailed and structured anatomical location information. Multiple locations are allowed - e.g. multiple punch biopsies of a lesion. @returns {Array} an array of {@link CodeableConcept} objects */ Procedure.prototype.bodySite = function() { var i, item, len, ref, results; if (this.json['bodySite']) { ref = this.json['bodySite']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The reason why the procedure was performed. This may be due to a Condition, may be coded entity of some type, or may simply be present as text. @returns {Array} an array of {@link CodeableConcept} objects */ Procedure.prototype.indication = function() { var i, item, len, ref, results; if (this.json['indication']) { ref = this.json['indication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Limited to 'real' people rather than equipment. @returns {Array} an array of {@link ProcedurePerformerComponent} objects */ Procedure.prototype.performer = function() { var i, item, len, ref, results; if (this.json['performer']) { ref = this.json['performer']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ProcedurePerformerComponent(item)); } return results; } }; /** The dates over which the procedure was performed. Allows a period to support complex procedures that span more than one date, and also allows for the length of the procedure to be captured. @returns {Period} */ Procedure.prototype.date = function() { if (this.json['date']) { return new Period(this.json['date']); } }; /** The encounter during which the procedure was performed. @returns {Reference} */ Procedure.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** What was the outcome of the procedure - did it resolve reasons why the procedure was performed?. @returns {Array} an array of {@link String} objects */ Procedure.prototype.outcome = function() { return this.json['outcome']; }; /** This could be a histology result. There could potentially be multiple reports - e.g. if this was a procedure that made multiple biopsies. @returns {Array} an array of {@link Reference} objects */ Procedure.prototype.report = function() { var i, item, len, ref, results; if (this.json['report']) { ref = this.json['report']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Any complications that occurred during the procedure, or in the immediate post-operative period. These are generally tracked separately from the notes, which typically will describe the procedure itself rather than any 'post procedure' issues. @returns {Array} an array of {@link CodeableConcept} objects */ Procedure.prototype.complication = function() { var i, item, len, ref, results; if (this.json['complication']) { ref = this.json['complication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** If the procedure required specific follow up - e.g. removal of sutures. The followup may be represented as a simple note, or potentially could be more complex in which case the CarePlan resource can be used. @returns {Array} an array of {@link String} objects */ Procedure.prototype.followUp = function() { return this.json['followUp']; }; /** Procedures may be related to other items such as procedures or medications. For example treating wound dehiscence following a previous procedure. @returns {Array} an array of {@link ProcedureRelatedItemComponent} objects */ Procedure.prototype.relatedItem = function() { var i, item, len, ref, results; if (this.json['relatedItem']) { ref = this.json['relatedItem']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ProcedureRelatedItemComponent(item)); } return results; } }; /** Any other notes about the procedure - e.g. the operative notes. @returns {Array} an array of {@link String} objects */ Procedure.prototype.notes = function() { return this.json['notes']; }; return Procedure; })(DomainResource); module.exports.Procedure = Procedure; }).call(this); },{"../cql-datatypes":117,"./core":173}],224:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, ProcedureRequest, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A request for a procedure to be performed. May be a proposal or an order. @class ProcedureRequest @exports ProcedureRequest as ProcedureRequest */ ProcedureRequest = (function(superClass) { extend(ProcedureRequest, superClass); function ProcedureRequest(json) { this.json = json; ProcedureRequest.__super__.constructor.call(this, this.json); } /** Identifiers assigned to this order by the order or by the receiver. @returns {Array} an array of {@link Identifier} objects */ ProcedureRequest.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The patient who will receive the procedure. @returns {Reference} */ ProcedureRequest.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The specific procedure that is ordered. Use text if the exact nature of the procedure can't be coded. @returns {CodeableConcept} */ ProcedureRequest.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The site where the procedure is to be performed. @returns {Array} an array of {@link CodeableConcept} objects */ ProcedureRequest.prototype.bodySite = function() { var i, item, len, ref, results; if (this.json['bodySite']) { ref = this.json['bodySite']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The reason why the procedure is proposed or ordered. This procedure request may be motivated by a Condition for instance. @returns {Array} an array of {@link CodeableConcept} objects */ ProcedureRequest.prototype.indication = function() { var i, item, len, ref, results; if (this.json['indication']) { ref = this.json['indication']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** The timing schedule for the proposed or ordered procedure. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Array} an array of {@link Date} objects */ ProcedureRequest.prototype.timingDateTime = function() { if (this.json['timingDateTime']) { return DT.DateTime.parse(this.json['timingDateTime']); } }; /** The timing schedule for the proposed or ordered procedure. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Period} */ ProcedureRequest.prototype.timingPeriod = function() { if (this.json['timingPeriod']) { return new Period(this.json['timingPeriod']); } }; /** The timing schedule for the proposed or ordered procedure. The Schedule data type allows many different expressions, for example. "Every 8 hours"; "Three times a day"; "1/2 an hour before breakfast for 10 days from 23-Dec 2011:"; "15 Oct 2013, 17 Oct 2013 and 1 Nov 2013". @returns {Timing} */ ProcedureRequest.prototype.timingTiming = function() { if (this.json['timingTiming']) { return new Timing(this.json['timingTiming']); } }; /** The encounter within which the procedure proposal or request was created. @returns {Reference} */ ProcedureRequest.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** E.g. surgeon, anaethetist, endoscopist. @returns {Reference} */ ProcedureRequest.prototype.performer = function() { if (this.json['performer']) { return new Reference(this.json['performer']); } }; /** The status of the order. @returns {Array} an array of {@link String} objects */ ProcedureRequest.prototype.status = function() { return this.json['status']; }; /** The status of the order. @returns {Array} an array of {@link String} objects */ ProcedureRequest.prototype.mode = function() { return this.json['mode']; }; /** Any other notes associated with this proposal or order - e.g., provider instructions. @returns {Array} an array of {@link String} objects */ ProcedureRequest.prototype.notes = function() { return this.json['notes']; }; /** If a CodeableConcept is present, it indicates the pre-condition for performing the procedure. @returns {Array} an array of {@link boolean} objects */ ProcedureRequest.prototype.asNeededBoolean = function() { return this.json['asNeededBoolean']; }; /** If a CodeableConcept is present, it indicates the pre-condition for performing the procedure. @returns {CodeableConcept} */ ProcedureRequest.prototype.asNeededCodeableConcept = function() { if (this.json['asNeededCodeableConcept']) { return new CodeableConcept(this.json['asNeededCodeableConcept']); } }; /** The time when the request was made. @returns {Array} an array of {@link Date} objects */ ProcedureRequest.prototype.orderedOn = function() { if (this.json['orderedOn']) { return DT.DateTime.parse(this.json['orderedOn']); } }; /** The healthcare professional responsible for proposing or ordering the procedure. @returns {Reference} */ ProcedureRequest.prototype.orderer = function() { if (this.json['orderer']) { return new Reference(this.json['orderer']); } }; /** The clinical priority associated with this order. @returns {Array} an array of {@link String} objects */ ProcedureRequest.prototype.priority = function() { return this.json['priority']; }; return ProcedureRequest; })(DomainResource); module.exports.ProcedureRequest = ProcedureRequest; }).call(this); },{"../cql-datatypes":117,"./core":173}],225:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ConstraintComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Profile, ProfileMappingComponent, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ProfileMappingComponent @exports ProfileMappingComponent as ProfileMappingComponent */ ProfileMappingComponent = (function(superClass) { extend(ProfileMappingComponent, superClass); function ProfileMappingComponent(json) { this.json = json; ProfileMappingComponent.__super__.constructor.call(this, this.json); } /** An Internal id that is used to identify this mapping set when specific mappings are made. @returns {Array} an array of {@link String} objects */ ProfileMappingComponent.prototype.identity = function() { return this.json['identity']; }; /** A URI that identifies the specification that this mapping is expressed to. @returns {Array} an array of {@link String} objects */ ProfileMappingComponent.prototype.uri = function() { return this.json['uri']; }; /** A name for the specification that is being mapped to. @returns {Array} an array of {@link String} objects */ ProfileMappingComponent.prototype.name = function() { return this.json['name']; }; /** Comments about this mapping, including version notes, issues, scope limitations, and other important notes for usage. @returns {Array} an array of {@link String} objects */ ProfileMappingComponent.prototype.comments = function() { return this.json['comments']; }; return ProfileMappingComponent; })(BackboneElement); /** Embedded class @class ConstraintComponent @exports ConstraintComponent as ConstraintComponent */ ConstraintComponent = (function(superClass) { extend(ConstraintComponent, superClass); function ConstraintComponent(json) { this.json = json; ConstraintComponent.__super__.constructor.call(this, this.json); } /** Captures constraints on each element within the resource. @returns {Array} an array of {@link ElementDefinition} objects */ ConstraintComponent.prototype.element = function() { var i, item, len, ref, results; if (this.json['element']) { ref = this.json['element']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ElementDefinition(item)); } return results; } }; return ConstraintComponent; })(BackboneElement); /** A Resource Profile - a statement of use of one or more FHIR Resources. It may include constraints on Resources and Data Types, Terminology Binding Statements and Extension Definitions. @class Profile @exports Profile as Profile */ Profile = (function(superClass) { extend(Profile, superClass); function Profile(json) { this.json = json; Profile.__super__.constructor.call(this, this.json); } /** The URL at which this profile is (or will be) published, and which is used to reference this profile in extension urls and tag values in operational FHIR systems. @returns {Array} an array of {@link String} objects */ Profile.prototype.url = function() { return this.json['url']; }; /** Formal identifier that is used to identify this profile when it is represented in other formats, or referenced in a specification, model, design or an instance (should be globally unique OID, UUID, or URI), (if it's not possible to use the literal URI). @returns {Array} an array of {@link Identifier} objects */ Profile.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The identifier that is used to identify this version of the profile when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the profile author manually. @returns {Array} an array of {@link String} objects */ Profile.prototype.version = function() { return this.json['version']; }; /** A free text natural language name identifying the Profile. @returns {Array} an array of {@link String} objects */ Profile.prototype.name = function() { return this.json['name']; }; /** Details of the individual or organization who accepts responsibility for publishing the profile. @returns {Array} an array of {@link String} objects */ Profile.prototype.publisher = function() { return this.json['publisher']; }; /** Contact details to assist a user in finding and communicating with the publisher. @returns {Array} an array of {@link ContactPoint} objects */ Profile.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** A free text natural language description of the profile and its use. @returns {Array} an array of {@link String} objects */ Profile.prototype.description = function() { return this.json['description']; }; /** A set of terms from external terminologies that may be used to assist with indexing and searching of templates. @returns {Array} an array of {@link Coding} objects */ Profile.prototype.code = function() { var i, item, len, ref, results; if (this.json['code']) { ref = this.json['code']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** The status of the profile. @returns {Array} an array of {@link String} objects */ Profile.prototype.status = function() { return this.json['status']; }; /** This profile was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. @returns {Array} an array of {@link boolean} objects */ Profile.prototype.experimental = function() { return this.json['experimental']; }; /** The date that this version of the profile was published. @returns {Array} an array of {@link Date} objects */ Profile.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Scope and Usage that this profile was created to meet. @returns {Array} an array of {@link String} objects */ Profile.prototype.requirements = function() { return this.json['requirements']; }; /** The version of the FHIR specification on which this profile is based - this is the formal version of the specification, without the revision number, e.g. [publication].[major].[minor], which is 0.3.0 for this version. @returns {Array} an array of {@link String} objects */ Profile.prototype.fhirVersion = function() { return this.json['fhirVersion']; }; /** An external specification that the content is mapped to. @returns {Array} an array of {@link ProfileMappingComponent} objects */ Profile.prototype.mapping = function() { var i, item, len, ref, results; if (this.json['mapping']) { ref = this.json['mapping']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ProfileMappingComponent(item)); } return results; } }; /** The Resource or Data type being described. @returns {Array} an array of {@link String} objects */ Profile.prototype.type = function() { return this.json['type']; }; /** The structure that is the base on which this set of constraints is derived from. @returns {Array} an array of {@link String} objects */ Profile.prototype.base = function() { return this.json['base']; }; /** A snapshot view is expressed in a stand alone form that can be used and interpreted without considering the base profile. @returns {ConstraintComponent} */ Profile.prototype.snapshot = function() { if (this.json['snapshot']) { return new ConstraintComponent(this.json['snapshot']); } }; /** A differential view is expressed relative to the base profile - a statement of differences that it applies. @returns {ConstraintComponent} */ Profile.prototype.differential = function() { if (this.json['differential']) { return new ConstraintComponent(this.json['differential']); } }; return Profile; })(DomainResource); module.exports.Profile = Profile; }).call(this); },{"../cql-datatypes":117,"./core":173}],226:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Provenance, ProvenanceAgentComponent, ProvenanceEntityComponent, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ProvenanceAgentComponent @exports ProvenanceAgentComponent as ProvenanceAgentComponent */ ProvenanceAgentComponent = (function(superClass) { extend(ProvenanceAgentComponent, superClass); function ProvenanceAgentComponent(json) { this.json = json; ProvenanceAgentComponent.__super__.constructor.call(this, this.json); } /** The role that the participant played. @returns {Coding} */ ProvenanceAgentComponent.prototype.role = function() { if (this.json['role']) { return new Coding(this.json['role']); } }; /** The type of the participant. @returns {Coding} */ ProvenanceAgentComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** Identity of participant. May be a logical or physical uri and maybe absolute or relative. @returns {Array} an array of {@link String} objects */ ProvenanceAgentComponent.prototype.reference = function() { return this.json['reference']; }; /** Human-readable description of the participant. @returns {Array} an array of {@link String} objects */ ProvenanceAgentComponent.prototype.display = function() { return this.json['display']; }; return ProvenanceAgentComponent; })(BackboneElement); /** Embedded class @class ProvenanceEntityComponent @exports ProvenanceEntityComponent as ProvenanceEntityComponent */ ProvenanceEntityComponent = (function(superClass) { extend(ProvenanceEntityComponent, superClass); function ProvenanceEntityComponent(json) { this.json = json; ProvenanceEntityComponent.__super__.constructor.call(this, this.json); } /** How the entity was used during the activity. @returns {Array} an array of {@link String} objects */ ProvenanceEntityComponent.prototype.role = function() { return this.json['role']; }; /** The type of the entity. If the entity is a resource, then this is a resource type. @returns {Coding} */ ProvenanceEntityComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** Identity of participant. May be a logical or physical uri and maybe absolute or relative. @returns {Array} an array of {@link String} objects */ ProvenanceEntityComponent.prototype.reference = function() { return this.json['reference']; }; /** Human-readable description of the entity. @returns {Array} an array of {@link String} objects */ ProvenanceEntityComponent.prototype.display = function() { return this.json['display']; }; /** The entity is attributed to an agent to express the agent's responsibility for that entity, possibly along with other agents. This description can be understood as shorthand for saying that the agent was responsible for the activity which generated the entity. @returns {ProvenanceAgentComponent} */ ProvenanceEntityComponent.prototype.agent = function() { if (this.json['agent']) { return new ProvenanceAgentComponent(this.json['agent']); } }; return ProvenanceEntityComponent; })(BackboneElement); /** Provenance information that describes the activity that led to the creation of a set of resources. This information can be used to help determine their reliability or trace where the information in them came from. The focus of the provenance resource is record keeping, audit and traceability, and not explicit statements of clinical significance. @class Provenance @exports Provenance as Provenance */ Provenance = (function(superClass) { extend(Provenance, superClass); function Provenance(json) { this.json = json; Provenance.__super__.constructor.call(this, this.json); } /** The Reference(s) that were generated by the activity described in this resource. A provenance can point to more than one target if multiple resources were created/updated by the same activity. @returns {Array} an array of {@link Reference} objects */ Provenance.prototype.target = function() { var i, item, len, ref, results; if (this.json['target']) { ref = this.json['target']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The period during which the activity occurred. @returns {Period} */ Provenance.prototype.period = function() { if (this.json['period']) { return new Period(this.json['period']); } }; /** The instant of time at which the activity was recorded. @returns {Array} an array of {@link Date} objects */ Provenance.prototype.recorded = function() { if (this.json['recorded']) { return DT.DateTime.parse(this.json['recorded']); } }; /** The reason that the activity was taking place. @returns {CodeableConcept} */ Provenance.prototype.reason = function() { if (this.json['reason']) { return new CodeableConcept(this.json['reason']); } }; /** Where the activity occurred, if relevant. @returns {Reference} */ Provenance.prototype.location = function() { if (this.json['location']) { return new Reference(this.json['location']); } }; /** Policy or plan the activity was defined by. Typically, a single activity may have multiple applicable policy documents, such as patient consent, guarantor funding, etc. @returns {Array} an array of {@link String} objects */ Provenance.prototype.policy = function() { return this.json['policy']; }; /** An agent takes a role in an activity such that the agent can be assigned some degree of responsibility for the activity taking place. An agent can be a person, a piece of software, an inanimate object, an organization, or other entities that may be ascribed responsibility. @returns {Array} an array of {@link ProvenanceAgentComponent} objects */ Provenance.prototype.agent = function() { var i, item, len, ref, results; if (this.json['agent']) { ref = this.json['agent']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ProvenanceAgentComponent(item)); } return results; } }; /** An entity used in this activity. @returns {Array} an array of {@link ProvenanceEntityComponent} objects */ Provenance.prototype.entity = function() { var i, item, len, ref, results; if (this.json['entity']) { ref = this.json['entity']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ProvenanceEntityComponent(item)); } return results; } }; /** A digital signature on the target Reference(s). The signature should match a Provenance.agent.reference in the provenance resource. The signature is only added to support checking cryptographic integrity of the resource, and not to represent workflow and clinical aspects of the signing process, or to support non-repudiation. @returns {Array} an array of {@link String} objects */ Provenance.prototype.integritySignature = function() { return this.json['integritySignature']; }; return Provenance; })(DomainResource); module.exports.Provenance = Provenance; }).call(this); },{"../cql-datatypes":117,"./core":173}],227:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Query, QueryResponseComponent, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class QueryResponseComponent @exports QueryResponseComponent as QueryResponseComponent */ QueryResponseComponent = (function(superClass) { extend(QueryResponseComponent, superClass); function QueryResponseComponent(json) { this.json = json; QueryResponseComponent.__super__.constructor.call(this, this.json); } /** Links response to source query. @returns {Array} an array of {@link String} objects */ QueryResponseComponent.prototype.identifier = function() { return this.json['identifier']; }; /** Outcome of processing the query. @returns {Array} an array of {@link String} objects */ QueryResponseComponent.prototype.outcome = function() { return this.json['outcome']; }; /** Total number of matching records. @returns {Array} an array of {@link Number} objects */ QueryResponseComponent.prototype.total = function() { return this.json['total']; }; /** Parameters server used. @returns {Array} an array of {@link Extension} objects */ QueryResponseComponent.prototype.parameter = function() { var i, item, len, ref, results; if (this.json['parameter']) { ref = this.json['parameter']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; /** To get first page (if paged). @returns {Array} an array of {@link Extension} objects */ QueryResponseComponent.prototype.first = function() { var i, item, len, ref, results; if (this.json['first']) { ref = this.json['first']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; /** To get previous page (if paged). @returns {Array} an array of {@link Extension} objects */ QueryResponseComponent.prototype.previous = function() { var i, item, len, ref, results; if (this.json['previous']) { ref = this.json['previous']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; /** To get next page (if paged). @returns {Array} an array of {@link Extension} objects */ QueryResponseComponent.prototype.next = function() { var i, item, len, ref, results; if (this.json['next']) { ref = this.json['next']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; /** To get last page (if paged). @returns {Array} an array of {@link Extension} objects */ QueryResponseComponent.prototype.last = function() { var i, item, len, ref, results; if (this.json['last']) { ref = this.json['last']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; /** Resources that are the results of the search. @returns {Array} an array of {@link Reference} objects */ QueryResponseComponent.prototype.reference = function() { var i, item, len, ref, results; if (this.json['reference']) { ref = this.json['reference']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return QueryResponseComponent; })(BackboneElement); /** A description of a query with a set of parameters. @class Query @exports Query as Query */ Query = (function(superClass) { extend(Query, superClass); function Query(json) { this.json = json; Query.__super__.constructor.call(this, this.json); } /** Links query and its response(s). @returns {Array} an array of {@link String} objects */ Query.prototype.identifier = function() { return this.json['identifier']; }; /** Set of query parameters with values. @returns {Array} an array of {@link Extension} objects */ Query.prototype.parameter = function() { var i, item, len, ref, results; if (this.json['parameter']) { ref = this.json['parameter']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Extension(item)); } return results; } }; /** If this is a response to a query. @returns {QueryResponseComponent} */ Query.prototype.response = function() { if (this.json['response']) { return new QueryResponseComponent(this.json['response']); } }; return Query; })(DomainResource); module.exports.Query = Query; }).call(this); },{"../cql-datatypes":117,"./core":173}],228:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, GroupComponent, HumanName, Identifier, Narrative, Parameters, Period, Quantity, QuestionComponent, Questionnaire, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class QuestionComponent @exports QuestionComponent as QuestionComponent */ QuestionComponent = (function(superClass) { extend(QuestionComponent, superClass); function QuestionComponent(json) { this.json = json; QuestionComponent.__super__.constructor.call(this, this.json); } /** An identifier that is unique within the questionnaire allowing linkage to the equivalent group in a [[[QuestionnaireAnswers]]] resource. @returns {Array} an array of {@link String} objects */ QuestionComponent.prototype.linkId = function() { return this.json['linkId']; }; /** Identifies a how this question is known in a particular terminology such as LOINC. @returns {Array} an array of {@link Coding} objects */ QuestionComponent.prototype.concept = function() { var i, item, len, ref, results; if (this.json['concept']) { ref = this.json['concept']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Text of the question as it is shown to the user. @returns {Array} an array of {@link String} objects */ QuestionComponent.prototype.text = function() { return this.json['text']; }; /** The expected format of the answer, e.g. the type of input (string, integer) or whether a (multiple) choice is expected. @returns {Array} an array of {@link String} objects */ QuestionComponent.prototype.type = function() { return this.json['type']; }; /** If true, indicates that the group must be present and have required questions within it answered. If false, the group may be skipped when answering the questionnaire. @returns {Array} an array of {@link boolean} objects */ QuestionComponent.prototype.required = function() { return this.json['required']; }; /** Whether the group may occur multiple times in the instance, containing multiple sets of answers. @returns {Array} an array of {@link boolean} objects */ QuestionComponent.prototype.repeats = function() { return this.json['repeats']; }; /** Reference to a valueset containing the possible options. @returns {Reference} */ QuestionComponent.prototype.options = function() { if (this.json['options']) { return new Reference(this.json['options']); } }; /** Nested group, containing nested question for this question. The order of groups within the question is relevant. @returns {Array} an array of {@link GroupComponent} objects */ QuestionComponent.prototype.group = function() { var i, item, len, ref, results; if (this.json['group']) { ref = this.json['group']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new GroupComponent(item)); } return results; } }; return QuestionComponent; })(BackboneElement); /** Embedded class @class GroupComponent @exports GroupComponent as GroupComponent */ GroupComponent = (function(superClass) { extend(GroupComponent, superClass); function GroupComponent(json) { this.json = json; GroupComponent.__super__.constructor.call(this, this.json); } /** A identifier that is unique within the questionnaire allowing linkage to the equivalent group in a QuestionnaireAnswers resource. @returns {Array} an array of {@link String} objects */ GroupComponent.prototype.linkId = function() { return this.json['linkId']; }; /** The human-readable name for this section of the questionnaire. @returns {Array} an array of {@link String} objects */ GroupComponent.prototype.title = function() { return this.json['title']; }; /** Identifies a how this group of questions is known in a particular terminology such as LOINC. @returns {Array} an array of {@link Coding} objects */ GroupComponent.prototype.concept = function() { var i, item, len, ref, results; if (this.json['concept']) { ref = this.json['concept']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; /** Additional text for the group, used for display purposes. @returns {Array} an array of {@link String} objects */ GroupComponent.prototype.text = function() { return this.json['text']; }; /** If true, indicates that the group must be present and have required questions within it answered. If false, the group may be skipped when answering the questionnaire. @returns {Array} an array of {@link boolean} objects */ GroupComponent.prototype.required = function() { return this.json['required']; }; /** Whether the group may occur multiple times in the instance, containing multiple sets of answers. @returns {Array} an array of {@link boolean} objects */ GroupComponent.prototype.repeats = function() { return this.json['repeats']; }; /** A sub-group within a group. The ordering of groups within this group is relevant. @returns {Array} an array of {@link GroupComponent} objects */ GroupComponent.prototype.group = function() { var i, item, len, ref, results; if (this.json['group']) { ref = this.json['group']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new GroupComponent(item)); } return results; } }; /** Set of questions within this group. The order of questions within the group is relevant. @returns {Array} an array of {@link QuestionComponent} objects */ GroupComponent.prototype.question = function() { var i, item, len, ref, results; if (this.json['question']) { ref = this.json['question']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new QuestionComponent(item)); } return results; } }; return GroupComponent; })(BackboneElement); /** A structured set of questions intended to guide the collection of answers. The questions are ordered and grouped into coherent subsets, corresponding to the structure of the grouping of the underlying questions. @class Questionnaire @exports Questionnaire as Questionnaire */ Questionnaire = (function(superClass) { extend(Questionnaire, superClass); function Questionnaire(json) { this.json = json; Questionnaire.__super__.constructor.call(this, this.json); } /** This records identifiers associated with this question set that are defined by business processed and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate (e.g. in CDA documents, or in written / printed documentation). @returns {Array} an array of {@link Identifier} objects */ Questionnaire.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version number assigned by the publisher for business reasons. It may remain the same when the resource is updated. @returns {Array} an array of {@link String} objects */ Questionnaire.prototype.version = function() { return this.json['version']; }; /** The lifecycle status of the questionnaire as a whole. @returns {Array} an array of {@link String} objects */ Questionnaire.prototype.status = function() { return this.json['status']; }; /** The date that this questionnaire was last changed. @returns {Array} an array of {@link Date} objects */ Questionnaire.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** Organization responsible for developing and maintaining the questionnaire. @returns {Array} an array of {@link String} objects */ Questionnaire.prototype.publisher = function() { return this.json['publisher']; }; /** A collection of related questions (or further groupings of questions). @returns {GroupComponent} */ Questionnaire.prototype.group = function() { if (this.json['group']) { return new GroupComponent(this.json['group']); } }; return Questionnaire; })(DomainResource); module.exports.Questionnaire = Questionnaire; }).call(this); },{"../cql-datatypes":117,"./core":173}],229:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, GroupComponent, HumanName, Identifier, Narrative, Parameters, Period, Quantity, QuestionAnswerComponent, QuestionComponent, QuestionnaireAnswers, Range, Ratio, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class QuestionAnswerComponent @exports QuestionAnswerComponent as QuestionAnswerComponent */ QuestionAnswerComponent = (function(superClass) { extend(QuestionAnswerComponent, superClass); function QuestionAnswerComponent(json) { this.json = json; QuestionAnswerComponent.__super__.constructor.call(this, this.json); } /** Single-valued answer to the question. @returns {Array} an array of {@link boolean} objects */ QuestionAnswerComponent.prototype.valueBoolean = function() { return this.json['valueBoolean']; }; /** Single-valued answer to the question. @returns {Array} an array of {@link Number} objects */ QuestionAnswerComponent.prototype.valueDecimal = function() { return this.json['valueDecimal']; }; /** Single-valued answer to the question. @returns {Array} an array of {@link Number} objects */ QuestionAnswerComponent.prototype.valueInteger = function() { return this.json['valueInteger']; }; /** Single-valued answer to the question. @returns {Array} an array of {@link Date} objects */ QuestionAnswerComponent.prototype.valueDate = function() { if (this.json['valueDate']) { return DT.DateTime.parse(this.json['valueDate']); } }; /** Single-valued answer to the question. @returns {Array} an array of {@link Date} objects */ QuestionAnswerComponent.prototype.valueDateTime = function() { if (this.json['valueDateTime']) { return DT.DateTime.parse(this.json['valueDateTime']); } }; /** Single-valued answer to the question. @returns {Array} an array of {@link Date} objects */ QuestionAnswerComponent.prototype.valueInstant = function() { if (this.json['valueInstant']) { return DT.DateTime.parse(this.json['valueInstant']); } }; /** Single-valued answer to the question. @returns {time} */ QuestionAnswerComponent.prototype.valueTime = function() { if (this.json['valueTime']) { return new time(this.json['valueTime']); } }; /** Single-valued answer to the question. @returns {Array} an array of {@link String} objects */ QuestionAnswerComponent.prototype.valueString = function() { return this.json['valueString']; }; /** Single-valued answer to the question. @returns {Attachment} */ QuestionAnswerComponent.prototype.valueAttachment = function() { if (this.json['valueAttachment']) { return new Attachment(this.json['valueAttachment']); } }; /** Single-valued answer to the question. @returns {Coding} */ QuestionAnswerComponent.prototype.valueCoding = function() { if (this.json['valueCoding']) { return new Coding(this.json['valueCoding']); } }; /** Single-valued answer to the question. @returns {Quantity} */ QuestionAnswerComponent.prototype.valueQuantity = function() { if (this.json['valueQuantity']) { return new Quantity(this.json['valueQuantity']); } }; /** Single-valued answer to the question. @returns {Reference} */ QuestionAnswerComponent.prototype.valueReference = function() { if (this.json['valueReference']) { return new Reference(this.json['valueReference']); } }; return QuestionAnswerComponent; })(BackboneElement); /** Embedded class @class QuestionComponent @exports QuestionComponent as QuestionComponent */ QuestionComponent = (function(superClass) { extend(QuestionComponent, superClass); function QuestionComponent(json) { this.json = json; QuestionComponent.__super__.constructor.call(this, this.json); } /** Identifies the question from the Questionnaire that corresponds to this question in the QuestionnaireAnswers resource. @returns {Array} an array of {@link String} objects */ QuestionComponent.prototype.linkId = function() { return this.json['linkId']; }; /** Text of the question as it is shown to the user. @returns {Array} an array of {@link String} objects */ QuestionComponent.prototype.text = function() { return this.json['text']; }; /** The respondent's answer(s) to the question. @returns {Array} an array of {@link QuestionAnswerComponent} objects */ QuestionComponent.prototype.answer = function() { var i, item, len, ref, results; if (this.json['answer']) { ref = this.json['answer']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new QuestionAnswerComponent(item)); } return results; } }; /** Nested group, containing nested question for this question. The order of groups within the question is relevant. @returns {Array} an array of {@link GroupComponent} objects */ QuestionComponent.prototype.group = function() { var i, item, len, ref, results; if (this.json['group']) { ref = this.json['group']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new GroupComponent(item)); } return results; } }; return QuestionComponent; })(BackboneElement); /** Embedded class @class GroupComponent @exports GroupComponent as GroupComponent */ GroupComponent = (function(superClass) { extend(GroupComponent, superClass); function GroupComponent(json) { this.json = json; GroupComponent.__super__.constructor.call(this, this.json); } /** Identifies the group from the Questionnaire that corresponds to this group in the QuestionnaireAnswers resource. @returns {Array} an array of {@link String} objects */ GroupComponent.prototype.linkId = function() { return this.json['linkId']; }; /** Text that is displayed above the contents of the group. @returns {Array} an array of {@link String} objects */ GroupComponent.prototype.title = function() { return this.json['title']; }; /** Additional text for the group, used for display purposes. @returns {Array} an array of {@link String} objects */ GroupComponent.prototype.text = function() { return this.json['text']; }; /** More specific subject this section's answers are about, details the subject given in QuestionnaireAnswers. @returns {Reference} */ GroupComponent.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** A sub-group within a group. The ordering of groups within this group is relevant. @returns {Array} an array of {@link GroupComponent} objects */ GroupComponent.prototype.group = function() { var i, item, len, ref, results; if (this.json['group']) { ref = this.json['group']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new GroupComponent(item)); } return results; } }; /** Set of questions within this group. The order of questions within the group is relevant. @returns {Array} an array of {@link QuestionComponent} objects */ GroupComponent.prototype.question = function() { var i, item, len, ref, results; if (this.json['question']) { ref = this.json['question']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new QuestionComponent(item)); } return results; } }; return GroupComponent; })(BackboneElement); /** A structured set of questions and their answers. The questions are ordered and grouped into coherent subsets, corresponding to the structure of the grouping of the underlying questions. @class QuestionnaireAnswers @exports QuestionnaireAnswers as QuestionnaireAnswers */ QuestionnaireAnswers = (function(superClass) { extend(QuestionnaireAnswers, superClass); function QuestionnaireAnswers(json) { this.json = json; QuestionnaireAnswers.__super__.constructor.call(this, this.json); } /** A business identifier assigned to a particular completed (or partially completed) questionnaire. @returns {Identifier} */ QuestionnaireAnswers.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** Indicates the Questionnaire resource that defines the form for which answers are being provided. @returns {Reference} */ QuestionnaireAnswers.prototype.questionnaire = function() { if (this.json['questionnaire']) { return new Reference(this.json['questionnaire']); } }; /** The lifecycle status of the questionnaire answers as a whole. @returns {Array} an array of {@link String} objects */ QuestionnaireAnswers.prototype.status = function() { return this.json['status']; }; /** The subject of the questionnaire answers. This could be a patient, organization, practitioner, device, etc. This is who/what the answers apply to, but is not necessarily the source of information. @returns {Reference} */ QuestionnaireAnswers.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Person who received the answers to the questions in the QuestionnaireAnswers and recorded them in the system. @returns {Reference} */ QuestionnaireAnswers.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** The date and/or time that this version of the questionnaire answers was authored. @returns {Array} an array of {@link Date} objects */ QuestionnaireAnswers.prototype.authored = function() { if (this.json['authored']) { return DT.DateTime.parse(this.json['authored']); } }; /** The person who answered the questions about the subject. Only used when this is not the subject him/herself. @returns {Reference} */ QuestionnaireAnswers.prototype.source = function() { if (this.json['source']) { return new Reference(this.json['source']); } }; /** Encounter during which this set of questionnaire answers were collected. When there were multiple encounters, this is the one considered most relevant to the context of the answers. @returns {Reference} */ QuestionnaireAnswers.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** A group of questions to a possibly similarly grouped set of questions in the questionnaire answers. @returns {GroupComponent} */ QuestionnaireAnswers.prototype.group = function() { if (this.json['group']) { return new GroupComponent(this.json['group']); } }; return QuestionnaireAnswers; })(DomainResource); module.exports.QuestionnaireAnswers = QuestionnaireAnswers; }).call(this); },{"../cql-datatypes":117,"./core":173}],230:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, ItemsComponent, Narrative, Parameters, Period, Quantity, Range, Ratio, Readjudicate, Reference, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ItemsComponent @exports ItemsComponent as ItemsComponent */ ItemsComponent = (function(superClass) { extend(ItemsComponent, superClass); function ItemsComponent(json) { this.json = json; ItemsComponent.__super__.constructor.call(this, this.json); } /** A service line number. @returns {Array} an array of {@link Number} objects */ ItemsComponent.prototype.sequenceLinkId = function() { return this.json['sequenceLinkId']; }; return ItemsComponent; })(BackboneElement); /** This resource provides the request and line items details for the claim which is to be readjudicated. @class Readjudicate @exports Readjudicate as Readjudicate */ Readjudicate = (function(superClass) { extend(Readjudicate, superClass); function Readjudicate(json) { this.json = json; Readjudicate.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ Readjudicate.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ Readjudicate.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ Readjudicate.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ Readjudicate.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who is target of the request. @returns {Reference} */ Readjudicate.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ Readjudicate.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ Readjudicate.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Reference of resource to reverse. @returns {Reference} */ Readjudicate.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Reference of response to resource to reverse. @returns {Reference} */ Readjudicate.prototype.response = function() { if (this.json['response']) { return new Reference(this.json['response']); } }; /** A reference to supply which authenticated the process. @returns {Array} an array of {@link String} objects */ Readjudicate.prototype.reference = function() { return this.json['reference']; }; /** List of top level items to be readjudicated, if none specified then the entire submission is readjudicated. @returns {Array} an array of {@link ItemsComponent} objects */ Readjudicate.prototype.item = function() { var i, item, len, ref, results; if (this.json['item']) { ref = this.json['item']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ItemsComponent(item)); } return results; } }; return Readjudicate; })(DomainResource); module.exports.Readjudicate = Readjudicate; }).call(this); },{"../cql-datatypes":117,"./core":173}],231:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, ReferralRequest, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Used to record and send details about a request for referral service or transfer of a patient to the care of another provider or provider organisation. @class ReferralRequest @exports ReferralRequest as ReferralRequest */ ReferralRequest = (function(superClass) { extend(ReferralRequest, superClass); function ReferralRequest(json) { this.json = json; ReferralRequest.__super__.constructor.call(this, this.json); } /** The workflow status of the referral or transfer of care request. @returns {Array} an array of {@link String} objects */ ReferralRequest.prototype.status = function() { return this.json['status']; }; /** Business Id that uniquely identifies the referral/care transfer request instance. @returns {Array} an array of {@link Identifier} objects */ ReferralRequest.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** An indication of the type of referral (or where applicable the type of transfer of care) request. @returns {CodeableConcept} */ ReferralRequest.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Indication of the clinical domain or discipline to which the referral or transfer of care request is sent. @returns {CodeableConcept} */ ReferralRequest.prototype.specialty = function() { if (this.json['specialty']) { return new CodeableConcept(this.json['specialty']); } }; /** An indication of the urgency of referral (or where applicable the type of transfer of care) request. @returns {CodeableConcept} */ ReferralRequest.prototype.priority = function() { if (this.json['priority']) { return new CodeableConcept(this.json['priority']); } }; /** The patient who is the subject of a referral or transfer of care request. @returns {Reference} */ ReferralRequest.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The healthcare provider or provider organization who/which initaited the referral/transfer of care request. Can also be Patient (a self referral). @returns {Reference} */ ReferralRequest.prototype.requester = function() { if (this.json['requester']) { return new Reference(this.json['requester']); } }; /** The healthcare provider(s) or provider organization(s) who/which is to receive the referral/transfer of care request. @returns {Array} an array of {@link Reference} objects */ ReferralRequest.prototype.recipient = function() { var i, item, len, ref, results; if (this.json['recipient']) { ref = this.json['recipient']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The encounter at which the request for referral or transfer of care is initiated. @returns {Reference} */ ReferralRequest.prototype.encounter = function() { if (this.json['encounter']) { return new Reference(this.json['encounter']); } }; /** Date/DateTime the request for referral or transfer of care is sent by the author. @returns {Array} an array of {@link Date} objects */ ReferralRequest.prototype.dateSent = function() { if (this.json['dateSent']) { return DT.DateTime.parse(this.json['dateSent']); } }; /** Description of clinical condition indicating why referral/transfer of care is requested. @returns {CodeableConcept} */ ReferralRequest.prototype.reason = function() { if (this.json['reason']) { return new CodeableConcept(this.json['reason']); } }; /** The reason gives a short description of why the referral is being made, the description expands on this to support a more complete clinical summary. @returns {Array} an array of {@link String} objects */ ReferralRequest.prototype.description = function() { return this.json['description']; }; /** The service(s) that is/are requested to be provided to the patient. @returns {Array} an array of {@link CodeableConcept} objects */ ReferralRequest.prototype.serviceRequested = function() { var i, item, len, ref, results; if (this.json['serviceRequested']) { ref = this.json['serviceRequested']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Any additional (administrative, financial or clinical) information required to support request for referral or transfer of care. @returns {Array} an array of {@link Reference} objects */ ReferralRequest.prototype.supportingInformation = function() { var i, item, len, ref, results; if (this.json['supportingInformation']) { ref = this.json['supportingInformation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** The period of time within which the services identified in the referral/transfer of care is specified or required to occur. @returns {Period} */ ReferralRequest.prototype.fulfillmentTime = function() { if (this.json['fulfillmentTime']) { return new Period(this.json['fulfillmentTime']); } }; return ReferralRequest; })(DomainResource); module.exports.ReferralRequest = ReferralRequest; }).call(this); },{"../cql-datatypes":117,"./core":173}],232:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, RelatedPerson, Resource, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Information about a person that is involved in the care for a patient, but who is not the target of healthcare, nor has a formal responsibility in the care process. @class RelatedPerson @exports RelatedPerson as RelatedPerson */ RelatedPerson = (function(superClass) { extend(RelatedPerson, superClass); function RelatedPerson(json) { this.json = json; RelatedPerson.__super__.constructor.call(this, this.json); } /** Identifier for a person within a particular scope. @returns {Array} an array of {@link Identifier} objects */ RelatedPerson.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The patient this person is related to. @returns {Reference} */ RelatedPerson.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** The nature of the relationship between a patient and the related person. @returns {CodeableConcept} */ RelatedPerson.prototype.relationship = function() { if (this.json['relationship']) { return new CodeableConcept(this.json['relationship']); } }; /** A name associated with the person. @returns {HumanName} */ RelatedPerson.prototype.name = function() { if (this.json['name']) { return new HumanName(this.json['name']); } }; /** A contact detail for the person, e.g. a telephone number or an email address. @returns {Array} an array of {@link ContactPoint} objects */ RelatedPerson.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. @returns {Array} an array of {@link String} objects */ RelatedPerson.prototype.gender = function() { return this.json['gender']; }; /** Address where the related person can be contacted or visited. @returns {Address} */ RelatedPerson.prototype.address = function() { if (this.json['address']) { return new Address(this.json['address']); } }; /** Image of the person. @returns {Array} an array of {@link Attachment} objects */ RelatedPerson.prototype.photo = function() { var i, item, len, ref, results; if (this.json['photo']) { ref = this.json['photo']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Attachment(item)); } return results; } }; return RelatedPerson; })(DomainResource); module.exports.RelatedPerson = RelatedPerson; }).call(this); },{"../cql-datatypes":117,"./core":173}],233:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, PayeeComponent, Period, Quantity, Range, Ratio, Reference, Resource, Reversal, ReversalCoverageComponent, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class PayeeComponent @exports PayeeComponent as PayeeComponent */ PayeeComponent = (function(superClass) { extend(PayeeComponent, superClass); function PayeeComponent(json) { this.json = json; PayeeComponent.__super__.constructor.call(this, this.json); } /** Party to be reimbursed: Subscriber, provider, other. @returns {Coding} */ PayeeComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The provider who is to be reimbursed for the claim (the party to whom any benefit is assigned). @returns {Reference} */ PayeeComponent.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization who is to be reimbursed for the claim (the party to whom any benefit is assigned). @returns {Reference} */ PayeeComponent.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The person other than the subscriber who is to be reimbursed for the claim (the party to whom any benefit is assigned). @returns {Reference} */ PayeeComponent.prototype.person = function() { if (this.json['person']) { return new Reference(this.json['person']); } }; return PayeeComponent; })(BackboneElement); /** Embedded class @class ReversalCoverageComponent @exports ReversalCoverageComponent as ReversalCoverageComponent */ ReversalCoverageComponent = (function(superClass) { extend(ReversalCoverageComponent, superClass); function ReversalCoverageComponent(json) { this.json = json; ReversalCoverageComponent.__super__.constructor.call(this, this.json); } /** A service line item. @returns {Array} an array of {@link Number} objects */ ReversalCoverageComponent.prototype.sequence = function() { return this.json['sequence']; }; /** The instance number of the Coverage which is the focus for adjudication, that is the Coverage to which the claim is to be adjudicated against. @returns {Array} an array of {@link boolean} objects */ ReversalCoverageComponent.prototype.focal = function() { return this.json['focal']; }; /** Reference to the program or plan identification, underwriter or payor. @returns {Reference} */ ReversalCoverageComponent.prototype.coverage = function() { if (this.json['coverage']) { return new Reference(this.json['coverage']); } }; /** The contract number of a business agreement which describes the terms and conditions. @returns {Array} an array of {@link String} objects */ ReversalCoverageComponent.prototype.businessArrangement = function() { return this.json['businessArrangement']; }; /** The relationship of the patient to the subscriber. @returns {Coding} */ ReversalCoverageComponent.prototype.relationship = function() { if (this.json['relationship']) { return new Coding(this.json['relationship']); } }; return ReversalCoverageComponent; })(BackboneElement); /** This resource provides the request and response details for the request for which all actions are to be reversed or terminated. @class Reversal @exports Reversal as Reversal */ Reversal = (function(superClass) { extend(Reversal, superClass); function Reversal(json) { this.json = json; Reversal.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ Reversal.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ Reversal.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ Reversal.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ Reversal.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who is target of the request. @returns {Reference} */ Reversal.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ Reversal.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ Reversal.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Reference of resource to reverse. @returns {Reference} */ Reversal.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Reference of response to resource to reverse. @returns {Reference} */ Reversal.prototype.response = function() { if (this.json['response']) { return new Reference(this.json['response']); } }; /** Payee information suypplied for matching purposes. @returns {PayeeComponent} */ Reversal.prototype.payee = function() { if (this.json['payee']) { return new PayeeComponent(this.json['payee']); } }; /** Financial instrument by which payment information for health care. @returns {ReversalCoverageComponent} */ Reversal.prototype.coverage = function() { if (this.json['coverage']) { return new ReversalCoverageComponent(this.json['coverage']); } }; /** If true remove all history excluding audit. @returns {Array} an array of {@link boolean} objects */ Reversal.prototype.nullify = function() { return this.json['nullify']; }; return Reversal; })(DomainResource); module.exports.Reversal = Reversal; }).call(this); },{"../cql-datatypes":117,"./core":173}],234:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, RiskAssessment, RiskAssessmentPredictionComponent, SampledData, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class RiskAssessmentPredictionComponent @exports RiskAssessmentPredictionComponent as RiskAssessmentPredictionComponent */ RiskAssessmentPredictionComponent = (function(superClass) { extend(RiskAssessmentPredictionComponent, superClass); function RiskAssessmentPredictionComponent(json) { this.json = json; RiskAssessmentPredictionComponent.__super__.constructor.call(this, this.json); } /** One of the potential outcomes for the patient (e.g. remission, death, a particular condition). @returns {CodeableConcept} */ RiskAssessmentPredictionComponent.prototype.outcome = function() { if (this.json['outcome']) { return new CodeableConcept(this.json['outcome']); } }; /** How likely is the outcome (in the specified timeframe). @returns {Array} an array of {@link Number} objects */ RiskAssessmentPredictionComponent.prototype.probabilityDecimal = function() { return this.json['probabilityDecimal']; }; /** How likely is the outcome (in the specified timeframe). @returns {Range} */ RiskAssessmentPredictionComponent.prototype.probabilityRange = function() { if (this.json['probabilityRange']) { return new Range(this.json['probabilityRange']); } }; /** How likely is the outcome (in the specified timeframe). @returns {CodeableConcept} */ RiskAssessmentPredictionComponent.prototype.probabilityCodeableConcept = function() { if (this.json['probabilityCodeableConcept']) { return new CodeableConcept(this.json['probabilityCodeableConcept']); } }; /** Indicates the risk for this particular subject (with their specific characteristics) divided by the risk of the population in general. (Numbers greater than 1 = higher risk than the population, numbers less than 1 = lower risk.). @returns {Array} an array of {@link Number} objects */ RiskAssessmentPredictionComponent.prototype.relativeRisk = function() { return this.json['relativeRisk']; }; /** Indicates the period of time or age range of the subject to which the specified probability applies. @returns {Period} */ RiskAssessmentPredictionComponent.prototype.whenPeriod = function() { if (this.json['whenPeriod']) { return new Period(this.json['whenPeriod']); } }; /** Indicates the period of time or age range of the subject to which the specified probability applies. @returns {Range} */ RiskAssessmentPredictionComponent.prototype.whenRange = function() { if (this.json['whenRange']) { return new Range(this.json['whenRange']); } }; /** Additional information explaining the basis for the prediction. @returns {Array} an array of {@link String} objects */ RiskAssessmentPredictionComponent.prototype.rationale = function() { return this.json['rationale']; }; return RiskAssessmentPredictionComponent; })(BackboneElement); /** An assessment of the likely outcome(s) for a patient or other subject as well as the likelihood of each outcome. @class RiskAssessment @exports RiskAssessment as RiskAssessment */ RiskAssessment = (function(superClass) { extend(RiskAssessment, superClass); function RiskAssessment(json) { this.json = json; RiskAssessment.__super__.constructor.call(this, this.json); } /** The patient or group the risk assessment applies to. @returns {Reference} */ RiskAssessment.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The date (and possibly time) the risk assessment was performed. @returns {Array} an array of {@link Date} objects */ RiskAssessment.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** For assessments or prognosis specific to a particular condition, indicates the condition being assessed. @returns {Reference} */ RiskAssessment.prototype.condition = function() { if (this.json['condition']) { return new Reference(this.json['condition']); } }; /** The provider or software application that performed the assessment. @returns {Reference} */ RiskAssessment.prototype.performer = function() { if (this.json['performer']) { return new Reference(this.json['performer']); } }; /** Business identifier assigned to the risk assessment. @returns {Identifier} */ RiskAssessment.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** The algorithm, processs or mechanism used to evaluate the risk. @returns {CodeableConcept} */ RiskAssessment.prototype.method = function() { if (this.json['method']) { return new CodeableConcept(this.json['method']); } }; /** Indicates the source data considered as part of the assessment (FamilyHistory, Observations, Procedures, Conditions, etc.). @returns {Array} an array of {@link Reference} objects */ RiskAssessment.prototype.basis = function() { var i, item, len, ref, results; if (this.json['basis']) { ref = this.json['basis']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; /** Describes the expected outcome for the subject. @returns {Array} an array of {@link RiskAssessmentPredictionComponent} objects */ RiskAssessment.prototype.prediction = function() { var i, item, len, ref, results; if (this.json['prediction']) { ref = this.json['prediction']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new RiskAssessmentPredictionComponent(item)); } return results; } }; /** A description of the steps that might be taken to reduce the identified risk(s). @returns {Array} an array of {@link String} objects */ RiskAssessment.prototype.mitigation = function() { return this.json['mitigation']; }; return RiskAssessment; })(DomainResource); module.exports.RiskAssessment = RiskAssessment; }).call(this); },{"../cql-datatypes":117,"./core":173}],235:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, SearchParameter, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** A Search Parameter that defines a named search item that can be used to search/filter on a resource. @class SearchParameter @exports SearchParameter as SearchParameter */ SearchParameter = (function(superClass) { extend(SearchParameter, superClass); function SearchParameter(json) { this.json = json; SearchParameter.__super__.constructor.call(this, this.json); } /** The URL at which this search parameter is (or will be) published, and which is used to reference this profile in conformance statements. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.url = function() { return this.json['url']; }; /** The name of the standard or custom search parameter. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.name = function() { return this.json['name']; }; /** Details of the individual or organization who accepts responsibility for publishing the search parameter. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.publisher = function() { return this.json['publisher']; }; /** Contact details to assist a user in finding and communicating with the publisher. @returns {Array} an array of {@link ContactPoint} objects */ SearchParameter.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** The Scope and Usage that this search parameter was created to meet. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.requirements = function() { return this.json['requirements']; }; /** The base resource type that this search parameter refers to. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.base = function() { return this.json['base']; }; /** The type of value a search parameter refers to, and how the content is interpreted. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.type = function() { return this.json['type']; }; /** A description of the search parameters and how it used. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.description = function() { return this.json['description']; }; /** An XPath expression that returns a set of elements for the search parameter. @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.xpath = function() { return this.json['xpath']; }; /** Types of resource (if a resource is referenced). @returns {Array} an array of {@link String} objects */ SearchParameter.prototype.target = function() { return this.json['target']; }; return SearchParameter; })(DomainResource); module.exports.SearchParameter = SearchParameter; }).call(this); },{"../cql-datatypes":117,"./core":173}],236:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, SecurityEvent, SecurityEventEventComponent, SecurityEventObjectComponent, SecurityEventObjectDetailComponent, SecurityEventParticipantComponent, SecurityEventParticipantNetworkComponent, SecurityEventSourceComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class SecurityEventEventComponent @exports SecurityEventEventComponent as SecurityEventEventComponent */ SecurityEventEventComponent = (function(superClass) { extend(SecurityEventEventComponent, superClass); function SecurityEventEventComponent(json) { this.json = json; SecurityEventEventComponent.__super__.constructor.call(this, this.json); } /** Identifier for a family of the event. @returns {CodeableConcept} */ SecurityEventEventComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Identifier for the category of event. @returns {Array} an array of {@link CodeableConcept} objects */ SecurityEventEventComponent.prototype.subtype = function() { var i, item, len, ref, results; if (this.json['subtype']) { ref = this.json['subtype']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Indicator for type of action performed during the event that generated the audit. @returns {Array} an array of {@link String} objects */ SecurityEventEventComponent.prototype.action = function() { return this.json['action']; }; /** The time when the event occurred on the source. @returns {Array} an array of {@link Date} objects */ SecurityEventEventComponent.prototype.dateTime = function() { if (this.json['dateTime']) { return DT.DateTime.parse(this.json['dateTime']); } }; /** Indicates whether the event succeeded or failed. @returns {Array} an array of {@link String} objects */ SecurityEventEventComponent.prototype.outcome = function() { return this.json['outcome']; }; /** A free text description of the outcome of the event. @returns {Array} an array of {@link String} objects */ SecurityEventEventComponent.prototype.outcomeDesc = function() { return this.json['outcomeDesc']; }; return SecurityEventEventComponent; })(BackboneElement); /** Embedded class @class SecurityEventParticipantNetworkComponent @exports SecurityEventParticipantNetworkComponent as SecurityEventParticipantNetworkComponent */ SecurityEventParticipantNetworkComponent = (function(superClass) { extend(SecurityEventParticipantNetworkComponent, superClass); function SecurityEventParticipantNetworkComponent(json) { this.json = json; SecurityEventParticipantNetworkComponent.__super__.constructor.call(this, this.json); } /** An identifier for the network access point of the user device for the audit event. @returns {Array} an array of {@link String} objects */ SecurityEventParticipantNetworkComponent.prototype.identifier = function() { return this.json['identifier']; }; /** An identifier for the type of network access point that originated the audit event. @returns {Array} an array of {@link String} objects */ SecurityEventParticipantNetworkComponent.prototype.type = function() { return this.json['type']; }; return SecurityEventParticipantNetworkComponent; })(BackboneElement); /** Embedded class @class SecurityEventParticipantComponent @exports SecurityEventParticipantComponent as SecurityEventParticipantComponent */ SecurityEventParticipantComponent = (function(superClass) { extend(SecurityEventParticipantComponent, superClass); function SecurityEventParticipantComponent(json) { this.json = json; SecurityEventParticipantComponent.__super__.constructor.call(this, this.json); } /** Specification of the role(s) the user plays when performing the event. Usually the codes used in this element are local codes defined by the role-based access control security system used in the local context. @returns {Array} an array of {@link CodeableConcept} objects */ SecurityEventParticipantComponent.prototype.role = function() { var i, item, len, ref, results; if (this.json['role']) { ref = this.json['role']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new CodeableConcept(item)); } return results; } }; /** Direct reference to a resource that identifies the participant. @returns {Reference} */ SecurityEventParticipantComponent.prototype.reference = function() { if (this.json['reference']) { return new Reference(this.json['reference']); } }; /** Unique identifier for the user actively participating in the event. @returns {Array} an array of {@link String} objects */ SecurityEventParticipantComponent.prototype.userId = function() { return this.json['userId']; }; /** Alternative Participant Identifier. For a human, this should be a user identifier text string from authentication system. This identifier would be one known to a common authentication system (e.g., single sign-on), if available. @returns {Array} an array of {@link String} objects */ SecurityEventParticipantComponent.prototype.altId = function() { return this.json['altId']; }; /** Human-meaningful name for the user. @returns {Array} an array of {@link String} objects */ SecurityEventParticipantComponent.prototype.name = function() { return this.json['name']; }; /** Indicator that the user is or is not the requestor, or initiator, for the event being audited. @returns {Array} an array of {@link boolean} objects */ SecurityEventParticipantComponent.prototype.requestor = function() { return this.json['requestor']; }; /** Type of media involved. Used when the event is about exporting/importing onto media. @returns {Coding} */ SecurityEventParticipantComponent.prototype.media = function() { if (this.json['media']) { return new Coding(this.json['media']); } }; /** Logical network location for application activity, if the activity has a network location. @returns {SecurityEventParticipantNetworkComponent} */ SecurityEventParticipantComponent.prototype.network = function() { if (this.json['network']) { return new SecurityEventParticipantNetworkComponent(this.json['network']); } }; return SecurityEventParticipantComponent; })(BackboneElement); /** Embedded class @class SecurityEventSourceComponent @exports SecurityEventSourceComponent as SecurityEventSourceComponent */ SecurityEventSourceComponent = (function(superClass) { extend(SecurityEventSourceComponent, superClass); function SecurityEventSourceComponent(json) { this.json = json; SecurityEventSourceComponent.__super__.constructor.call(this, this.json); } /** Logical source location within the healthcare enterprise network. @returns {Array} an array of {@link String} objects */ SecurityEventSourceComponent.prototype.site = function() { return this.json['site']; }; /** Identifier of the source where the event originated. @returns {Array} an array of {@link String} objects */ SecurityEventSourceComponent.prototype.identifier = function() { return this.json['identifier']; }; /** Code specifying the type of source where event originated. @returns {Array} an array of {@link Coding} objects */ SecurityEventSourceComponent.prototype.type = function() { var i, item, len, ref, results; if (this.json['type']) { ref = this.json['type']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; return SecurityEventSourceComponent; })(BackboneElement); /** Embedded class @class SecurityEventObjectDetailComponent @exports SecurityEventObjectDetailComponent as SecurityEventObjectDetailComponent */ SecurityEventObjectDetailComponent = (function(superClass) { extend(SecurityEventObjectDetailComponent, superClass); function SecurityEventObjectDetailComponent(json) { this.json = json; SecurityEventObjectDetailComponent.__super__.constructor.call(this, this.json); } /** Name of the property. @returns {Array} an array of {@link String} objects */ SecurityEventObjectDetailComponent.prototype.type = function() { return this.json['type']; }; /** Property value. @returns {Array} an array of {@link } objects */ SecurityEventObjectDetailComponent.prototype.value = function() { return this.json['value']; }; return SecurityEventObjectDetailComponent; })(BackboneElement); /** Embedded class @class SecurityEventObjectComponent @exports SecurityEventObjectComponent as SecurityEventObjectComponent */ SecurityEventObjectComponent = (function(superClass) { extend(SecurityEventObjectComponent, superClass); function SecurityEventObjectComponent(json) { this.json = json; SecurityEventObjectComponent.__super__.constructor.call(this, this.json); } /** Identifies a specific instance of the participant object. The reference should always be version specific. @returns {Identifier} */ SecurityEventObjectComponent.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** Identifies a specific instance of the participant object. The reference should always be version specific. @returns {Reference} */ SecurityEventObjectComponent.prototype.reference = function() { if (this.json['reference']) { return new Reference(this.json['reference']); } }; /** Object type being audited. @returns {Array} an array of {@link String} objects */ SecurityEventObjectComponent.prototype.type = function() { return this.json['type']; }; /** Code representing the functional application role of Participant Object being audited. @returns {Array} an array of {@link String} objects */ SecurityEventObjectComponent.prototype.role = function() { return this.json['role']; }; /** Identifier for the data life-cycle stage for the participant object. @returns {Array} an array of {@link String} objects */ SecurityEventObjectComponent.prototype.lifecycle = function() { return this.json['lifecycle']; }; /** Denotes policy-defined sensitivity for the Participant Object ID such as VIP, HIV status, mental health status or similar topics. @returns {CodeableConcept} */ SecurityEventObjectComponent.prototype.sensitivity = function() { if (this.json['sensitivity']) { return new CodeableConcept(this.json['sensitivity']); } }; /** An instance-specific descriptor of the Participant Object ID audited, such as a person's name. @returns {Array} an array of {@link String} objects */ SecurityEventObjectComponent.prototype.name = function() { return this.json['name']; }; /** Text that describes the object in more detail. @returns {Array} an array of {@link String} objects */ SecurityEventObjectComponent.prototype.description = function() { return this.json['description']; }; /** The actual query for a query-type participant object. @returns {Array} an array of {@link } objects */ SecurityEventObjectComponent.prototype.query = function() { return this.json['query']; }; /** Additional Information about the Object. @returns {Array} an array of {@link SecurityEventObjectDetailComponent} objects */ SecurityEventObjectComponent.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SecurityEventObjectDetailComponent(item)); } return results; } }; return SecurityEventObjectComponent; })(BackboneElement); /** A record of an event made for purposes of maintaining a security log. Typical uses include detection of intrusion attempts and monitoring for inappropriate usage. @class SecurityEvent @exports SecurityEvent as SecurityEvent */ SecurityEvent = (function(superClass) { extend(SecurityEvent, superClass); function SecurityEvent(json) { this.json = json; SecurityEvent.__super__.constructor.call(this, this.json); } /** Identifies the name, action type, time, and disposition of the audited event. @returns {SecurityEventEventComponent} */ SecurityEvent.prototype.event = function() { if (this.json['event']) { return new SecurityEventEventComponent(this.json['event']); } }; /** A person, a hardware device or software process. @returns {Array} an array of {@link SecurityEventParticipantComponent} objects */ SecurityEvent.prototype.participant = function() { var i, item, len, ref, results; if (this.json['participant']) { ref = this.json['participant']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SecurityEventParticipantComponent(item)); } return results; } }; /** Application systems and processes. @returns {SecurityEventSourceComponent} */ SecurityEvent.prototype.source = function() { if (this.json['source']) { return new SecurityEventSourceComponent(this.json['source']); } }; /** Specific instances of data or objects that have been accessed. @returns {Array} an array of {@link SecurityEventObjectComponent} objects */ SecurityEvent.prototype.object = function() { var i, item, len, ref, results; if (this.json['object']) { ref = this.json['object']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SecurityEventObjectComponent(item)); } return results; } }; return SecurityEvent; })(DomainResource); module.exports.SecurityEvent = SecurityEvent; }).call(this); },{"../cql-datatypes":117,"./core":173}],237:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Slot, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** (informative) A slot of time on a schedule that may be available for booking appointments. @class Slot @exports Slot as Slot */ Slot = (function(superClass) { extend(Slot, superClass); function Slot(json) { this.json = json; Slot.__super__.constructor.call(this, this.json); } /** External Ids for this item. @returns {Array} an array of {@link Identifier} objects */ Slot.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The type of appointments that can be booked into this slot (ideally this would be an identifiable service - which is at a location, rather than the location itself). If provided then this overrides the value provided on the availability resource. @returns {CodeableConcept} */ Slot.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The availability resource that this slot defines an interval of status information. @returns {Reference} */ Slot.prototype.availability = function() { if (this.json['availability']) { return new Reference(this.json['availability']); } }; /** BUSY | FREE | BUSY-UNAVAILABLE | BUSY-TENTATIVE. @returns {Array} an array of {@link String} objects */ Slot.prototype.freeBusyType = function() { return this.json['freeBusyType']; }; /** Date/Time that the slot is to begin. @returns {Array} an array of {@link Date} objects */ Slot.prototype.start = function() { if (this.json['start']) { return DT.DateTime.parse(this.json['start']); } }; /** Date/Time that the slot is to conclude. @returns {Array} an array of {@link Date} objects */ Slot.prototype.end = function() { if (this.json['end']) { return DT.DateTime.parse(this.json['end']); } }; /** This slot has already been overbooked, appointments are unlikely to be accepted for this time. @returns {Array} an array of {@link boolean} objects */ Slot.prototype.overbooked = function() { return this.json['overbooked']; }; /** Comments on the slot to describe any extended information. Such as custom constraints on the slot. @returns {Array} an array of {@link String} objects */ Slot.prototype.comment = function() { return this.json['comment']; }; /** When this slot was created, or last revised. @returns {Array} an array of {@link Date} objects */ Slot.prototype.lastModified = function() { if (this.json['lastModified']) { return DT.DateTime.parse(this.json['lastModified']); } }; return Slot; })(DomainResource); module.exports.Slot = Slot; }).call(this); },{"../cql-datatypes":117,"./core":173}],238:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Specimen, SpecimenCollectionComponent, SpecimenContainerComponent, SpecimenSourceComponent, SpecimenTreatmentComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class SpecimenSourceComponent @exports SpecimenSourceComponent as SpecimenSourceComponent */ SpecimenSourceComponent = (function(superClass) { extend(SpecimenSourceComponent, superClass); function SpecimenSourceComponent(json) { this.json = json; SpecimenSourceComponent.__super__.constructor.call(this, this.json); } /** Whether this relationship is to a parent or to a child. @returns {Array} an array of {@link String} objects */ SpecimenSourceComponent.prototype.relationship = function() { return this.json['relationship']; }; /** The specimen resource that is the target of this relationship. @returns {Array} an array of {@link Reference} objects */ SpecimenSourceComponent.prototype.target = function() { var i, item, len, ref, results; if (this.json['target']) { ref = this.json['target']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return SpecimenSourceComponent; })(BackboneElement); /** Embedded class @class SpecimenCollectionComponent @exports SpecimenCollectionComponent as SpecimenCollectionComponent */ SpecimenCollectionComponent = (function(superClass) { extend(SpecimenCollectionComponent, superClass); function SpecimenCollectionComponent(json) { this.json = json; SpecimenCollectionComponent.__super__.constructor.call(this, this.json); } /** Person who collected the specimen. @returns {Reference} */ SpecimenCollectionComponent.prototype.collector = function() { if (this.json['collector']) { return new Reference(this.json['collector']); } }; /** To communicate any details or issues encountered during the specimen collection procedure. @returns {Array} an array of {@link String} objects */ SpecimenCollectionComponent.prototype.comment = function() { return this.json['comment']; }; /** Time when specimen was collected from subject - the physiologically relevant time. @returns {Array} an array of {@link Date} objects */ SpecimenCollectionComponent.prototype.collectedDateTime = function() { if (this.json['collectedDateTime']) { return DT.DateTime.parse(this.json['collectedDateTime']); } }; /** Time when specimen was collected from subject - the physiologically relevant time. @returns {Period} */ SpecimenCollectionComponent.prototype.collectedPeriod = function() { if (this.json['collectedPeriod']) { return new Period(this.json['collectedPeriod']); } }; /** The quantity of specimen collected; for instance the volume of a blood sample, or the physical measurement of an anatomic pathology sample. @returns {Quantity} */ SpecimenCollectionComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** A coded value specifying the technique that is used to perform the procedure. @returns {CodeableConcept} */ SpecimenCollectionComponent.prototype.method = function() { if (this.json['method']) { return new CodeableConcept(this.json['method']); } }; /** Anatomical location from which the specimen should be collected (if subject is a patient). This element is not used for environmental specimens. @returns {CodeableConcept} */ SpecimenCollectionComponent.prototype.sourceSite = function() { if (this.json['sourceSite']) { return new CodeableConcept(this.json['sourceSite']); } }; return SpecimenCollectionComponent; })(BackboneElement); /** Embedded class @class SpecimenTreatmentComponent @exports SpecimenTreatmentComponent as SpecimenTreatmentComponent */ SpecimenTreatmentComponent = (function(superClass) { extend(SpecimenTreatmentComponent, superClass); function SpecimenTreatmentComponent(json) { this.json = json; SpecimenTreatmentComponent.__super__.constructor.call(this, this.json); } /** Textual description of procedure. @returns {Array} an array of {@link String} objects */ SpecimenTreatmentComponent.prototype.description = function() { return this.json['description']; }; /** A coded value specifying the procedure used to process the specimen. @returns {CodeableConcept} */ SpecimenTreatmentComponent.prototype.procedure = function() { if (this.json['procedure']) { return new CodeableConcept(this.json['procedure']); } }; /** Material used in the processing step. @returns {Array} an array of {@link Reference} objects */ SpecimenTreatmentComponent.prototype.additive = function() { var i, item, len, ref, results; if (this.json['additive']) { ref = this.json['additive']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return SpecimenTreatmentComponent; })(BackboneElement); /** Embedded class @class SpecimenContainerComponent @exports SpecimenContainerComponent as SpecimenContainerComponent */ SpecimenContainerComponent = (function(superClass) { extend(SpecimenContainerComponent, superClass); function SpecimenContainerComponent(json) { this.json = json; SpecimenContainerComponent.__super__.constructor.call(this, this.json); } /** Id for container. There may be multiple; a manufacturer's bar code, lab assigned identifier, etc. The container ID may differ from the specimen id in some circumstances. @returns {Array} an array of {@link Identifier} objects */ SpecimenContainerComponent.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Textual description of the container. @returns {Array} an array of {@link String} objects */ SpecimenContainerComponent.prototype.description = function() { return this.json['description']; }; /** The type of container associated with the specimen (e.g. slide, aliquot, etc). @returns {CodeableConcept} */ SpecimenContainerComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The capacity (volume or other measure) the container may contain. @returns {Quantity} */ SpecimenContainerComponent.prototype.capacity = function() { if (this.json['capacity']) { return new Quantity(this.json['capacity']); } }; /** The quantity of specimen in the container; may be volume, dimensions, or other appropriate measurements, depending on the specimen type. @returns {Quantity} */ SpecimenContainerComponent.prototype.specimenQuantity = function() { if (this.json['specimenQuantity']) { return new Quantity(this.json['specimenQuantity']); } }; /** Introduced substance to preserve, maintain or enhance the specimen. examples: Formalin, Citrate, EDTA. @returns {CodeableConcept} */ SpecimenContainerComponent.prototype.additiveCodeableConcept = function() { if (this.json['additiveCodeableConcept']) { return new CodeableConcept(this.json['additiveCodeableConcept']); } }; /** Introduced substance to preserve, maintain or enhance the specimen. examples: Formalin, Citrate, EDTA. @returns {Reference} */ SpecimenContainerComponent.prototype.additiveReference = function() { if (this.json['additiveReference']) { return new Reference(this.json['additiveReference']); } }; return SpecimenContainerComponent; })(BackboneElement); /** Sample for analysis. @class Specimen @exports Specimen as Specimen */ Specimen = (function(superClass) { extend(Specimen, superClass); function Specimen(json) { this.json = json; Specimen.__super__.constructor.call(this, this.json); } /** Id for specimen. @returns {Array} an array of {@link Identifier} objects */ Specimen.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Kind of material that forms the specimen. @returns {CodeableConcept} */ Specimen.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** Parent specimen from which the focal specimen was a component. @returns {Array} an array of {@link SpecimenSourceComponent} objects */ Specimen.prototype.source = function() { var i, item, len, ref, results; if (this.json['source']) { ref = this.json['source']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SpecimenSourceComponent(item)); } return results; } }; /** Where the specimen came from. This may be the patient(s) or from the environment or a device. @returns {Reference} */ Specimen.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** The identifier assigned by the lab when accessioning specimen(s). This is not necessarily the same as the specimen identifier, depending on local lab procedures. @returns {Identifier} */ Specimen.prototype.accessionIdentifier = function() { if (this.json['accessionIdentifier']) { return new Identifier(this.json['accessionIdentifier']); } }; /** Time when specimen was received for processing or testing. @returns {Array} an array of {@link Date} objects */ Specimen.prototype.receivedTime = function() { if (this.json['receivedTime']) { return DT.DateTime.parse(this.json['receivedTime']); } }; /** Details concerning the specimen collection. @returns {SpecimenCollectionComponent} */ Specimen.prototype.collection = function() { if (this.json['collection']) { return new SpecimenCollectionComponent(this.json['collection']); } }; /** Details concerning treatment and processing steps for the specimen. @returns {Array} an array of {@link SpecimenTreatmentComponent} objects */ Specimen.prototype.treatment = function() { var i, item, len, ref, results; if (this.json['treatment']) { ref = this.json['treatment']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SpecimenTreatmentComponent(item)); } return results; } }; /** The container holding the specimen. The recursive nature of containers; i.e. blood in tube in tray in rack is not addressed here. @returns {Array} an array of {@link SpecimenContainerComponent} objects */ Specimen.prototype.container = function() { var i, item, len, ref, results; if (this.json['container']) { ref = this.json['container']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SpecimenContainerComponent(item)); } return results; } }; return Specimen; })(DomainResource); module.exports.Specimen = Specimen; }).call(this); },{"../cql-datatypes":117,"./core":173}],239:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, StatusRequest, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** This resource provides the request and response details for the resource for which the stsatus is to be checked. @class StatusRequest @exports StatusRequest as StatusRequest */ StatusRequest = (function(superClass) { extend(StatusRequest, superClass); function StatusRequest(json) { this.json = json; StatusRequest.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ StatusRequest.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ StatusRequest.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ StatusRequest.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ StatusRequest.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who is target of the request. @returns {Reference} */ StatusRequest.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ StatusRequest.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ StatusRequest.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Reference of resource to reverse. @returns {Reference} */ StatusRequest.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Reference of response to resource to reverse. @returns {Reference} */ StatusRequest.prototype.response = function() { if (this.json['response']) { return new Reference(this.json['response']); } }; return StatusRequest; })(DomainResource); module.exports.StatusRequest = StatusRequest; }).call(this); },{"../cql-datatypes":117,"./core":173}],240:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, StatusResponse, StatusResponseNotesComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class StatusResponseNotesComponent @exports StatusResponseNotesComponent as StatusResponseNotesComponent */ StatusResponseNotesComponent = (function(superClass) { extend(StatusResponseNotesComponent, superClass); function StatusResponseNotesComponent(json) { this.json = json; StatusResponseNotesComponent.__super__.constructor.call(this, this.json); } /** The note purpose: Print/Display. @returns {Coding} */ StatusResponseNotesComponent.prototype.type = function() { if (this.json['type']) { return new Coding(this.json['type']); } }; /** The note text. @returns {Array} an array of {@link String} objects */ StatusResponseNotesComponent.prototype.text = function() { return this.json['text']; }; return StatusResponseNotesComponent; })(BackboneElement); /** This resource provides processing status, errors and notes from the processing of a resource. @class StatusResponse @exports StatusResponse as StatusResponse */ StatusResponse = (function(superClass) { extend(StatusResponse, superClass); function StatusResponse(json) { this.json = json; StatusResponse.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ StatusResponse.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** Original request resource referrence. @returns {Reference} */ StatusResponse.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Transaction status: error, complete, held. @returns {Coding} */ StatusResponse.prototype.outcome = function() { if (this.json['outcome']) { return new Coding(this.json['outcome']); } }; /** A description of the status of the adjudication or processing. @returns {Array} an array of {@link String} objects */ StatusResponse.prototype.disposition = function() { return this.json['disposition']; }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ StatusResponse.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ StatusResponse.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when the enclosed suite of services were performed or completed. @returns {Array} an array of {@link Date} objects */ StatusResponse.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer who produced this adjudicated response. @returns {Reference} */ StatusResponse.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ StatusResponse.prototype.requestProvider = function() { if (this.json['requestProvider']) { return new Reference(this.json['requestProvider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ StatusResponse.prototype.requestOrganization = function() { if (this.json['requestOrganization']) { return new Reference(this.json['requestOrganization']); } }; /** The form to be used for printing the content. @returns {Coding} */ StatusResponse.prototype.form = function() { if (this.json['form']) { return new Coding(this.json['form']); } }; /** Suite of processing note or additional requirements is the processing has been held. @returns {Array} an array of {@link StatusResponseNotesComponent} objects */ StatusResponse.prototype.notes = function() { var i, item, len, ref, results; if (this.json['notes']) { ref = this.json['notes']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new StatusResponseNotesComponent(item)); } return results; } }; /** Processing errors. @returns {Array} an array of {@link Coding} objects */ StatusResponse.prototype.error = function() { var i, item, len, ref, results; if (this.json['error']) { ref = this.json['error']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Coding(item)); } return results; } }; return StatusResponse; })(DomainResource); module.exports.StatusResponse = StatusResponse; }).call(this); },{"../cql-datatypes":117,"./core":173}],241:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Subscription, SubscriptionChannelComponent, SubscriptionTagComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class SubscriptionChannelComponent @exports SubscriptionChannelComponent as SubscriptionChannelComponent */ SubscriptionChannelComponent = (function(superClass) { extend(SubscriptionChannelComponent, superClass); function SubscriptionChannelComponent(json) { this.json = json; SubscriptionChannelComponent.__super__.constructor.call(this, this.json); } /** Todo. @returns {Array} an array of {@link String} objects */ SubscriptionChannelComponent.prototype.type = function() { return this.json['type']; }; /** Todo. @returns {Array} an array of {@link String} objects */ SubscriptionChannelComponent.prototype.url = function() { return this.json['url']; }; /** ToDo. @returns {Array} an array of {@link String} objects */ SubscriptionChannelComponent.prototype.payload = function() { return this.json['payload']; }; /** Usage depends on the channel type. @returns {Array} an array of {@link String} objects */ SubscriptionChannelComponent.prototype.header = function() { return this.json['header']; }; return SubscriptionChannelComponent; })(BackboneElement); /** Embedded class @class SubscriptionTagComponent @exports SubscriptionTagComponent as SubscriptionTagComponent */ SubscriptionTagComponent = (function(superClass) { extend(SubscriptionTagComponent, superClass); function SubscriptionTagComponent(json) { this.json = json; SubscriptionTagComponent.__super__.constructor.call(this, this.json); } /** Todo. @returns {Array} an array of {@link String} objects */ SubscriptionTagComponent.prototype.term = function() { return this.json['term']; }; /** Todo. @returns {Array} an array of {@link String} objects */ SubscriptionTagComponent.prototype.scheme = function() { return this.json['scheme']; }; /** Todo. @returns {Array} an array of {@link String} objects */ SubscriptionTagComponent.prototype.description = function() { return this.json['description']; }; return SubscriptionTagComponent; })(BackboneElement); /** Todo. @class Subscription @exports Subscription as Subscription */ Subscription = (function(superClass) { extend(Subscription, superClass); function Subscription(json) { this.json = json; Subscription.__super__.constructor.call(this, this.json); } /** Todo. @returns {Array} an array of {@link String} objects */ Subscription.prototype.criteria = function() { return this.json['criteria']; }; /** Todo. @returns {Array} an array of {@link ContactPoint} objects */ Subscription.prototype.contact = function() { var i, item, len, ref, results; if (this.json['contact']) { ref = this.json['contact']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** Todo. @returns {Array} an array of {@link String} objects */ Subscription.prototype.reason = function() { return this.json['reason']; }; /** Todo. @returns {Array} an array of {@link String} objects */ Subscription.prototype.status = function() { return this.json['status']; }; /** Todo. @returns {Array} an array of {@link String} objects */ Subscription.prototype.error = function() { return this.json['error']; }; /** Todo. @returns {SubscriptionChannelComponent} */ Subscription.prototype.channel = function() { if (this.json['channel']) { return new SubscriptionChannelComponent(this.json['channel']); } }; /** Todo. @returns {Array} an array of {@link Date} objects */ Subscription.prototype.end = function() { if (this.json['end']) { return DT.DateTime.parse(this.json['end']); } }; /** Todo. @returns {Array} an array of {@link SubscriptionTagComponent} objects */ Subscription.prototype.tag = function() { var i, item, len, ref, results; if (this.json['tag']) { ref = this.json['tag']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SubscriptionTagComponent(item)); } return results; } }; return Subscription; })(DomainResource); module.exports.Subscription = Subscription; }).call(this); },{"../cql-datatypes":117,"./core":173}],242:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Substance, SubstanceIngredientComponent, SubstanceInstanceComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class SubstanceInstanceComponent @exports SubstanceInstanceComponent as SubstanceInstanceComponent */ SubstanceInstanceComponent = (function(superClass) { extend(SubstanceInstanceComponent, superClass); function SubstanceInstanceComponent(json) { this.json = json; SubstanceInstanceComponent.__super__.constructor.call(this, this.json); } /** Identifier associated with the package/container (usually a label affixed directly). @returns {Identifier} */ SubstanceInstanceComponent.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** When the substance is no longer valid to use. For some substances, a single arbitrary date is used for expiry. @returns {Array} an array of {@link Date} objects */ SubstanceInstanceComponent.prototype.expiry = function() { if (this.json['expiry']) { return DT.DateTime.parse(this.json['expiry']); } }; /** The amount of the substance. @returns {Quantity} */ SubstanceInstanceComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; return SubstanceInstanceComponent; })(BackboneElement); /** Embedded class @class SubstanceIngredientComponent @exports SubstanceIngredientComponent as SubstanceIngredientComponent */ SubstanceIngredientComponent = (function(superClass) { extend(SubstanceIngredientComponent, superClass); function SubstanceIngredientComponent(json) { this.json = json; SubstanceIngredientComponent.__super__.constructor.call(this, this.json); } /** The amount of the ingredient in the substance - a concentration ratio. @returns {Ratio} */ SubstanceIngredientComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Ratio(this.json['quantity']); } }; /** Another substance that is a component of this substance. @returns {Reference} */ SubstanceIngredientComponent.prototype.substance = function() { if (this.json['substance']) { return new Reference(this.json['substance']); } }; return SubstanceIngredientComponent; })(BackboneElement); /** A homogeneous material with a definite composition. @class Substance @exports Substance as Substance */ Substance = (function(superClass) { extend(Substance, superClass); function Substance(json) { this.json = json; Substance.__super__.constructor.call(this, this.json); } /** A code (or set of codes) that identify this substance. @returns {CodeableConcept} */ Substance.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** A description of the substance - its appearance, handling requirements, and other usage notes. @returns {Array} an array of {@link String} objects */ Substance.prototype.description = function() { return this.json['description']; }; /** Substance may be used to describe a kind of substance, or a specific package/container of the substance: an instance. @returns {SubstanceInstanceComponent} */ Substance.prototype.instance = function() { if (this.json['instance']) { return new SubstanceInstanceComponent(this.json['instance']); } }; /** A substance can be composed of other substances. @returns {Array} an array of {@link SubstanceIngredientComponent} objects */ Substance.prototype.ingredient = function() { var i, item, len, ref, results; if (this.json['ingredient']) { ref = this.json['ingredient']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SubstanceIngredientComponent(item)); } return results; } }; return Substance; })(DomainResource); module.exports.Substance = Substance; }).call(this); },{"../cql-datatypes":117,"./core":173}],243:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Supply, SupplyDispenseComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class SupplyDispenseComponent @exports SupplyDispenseComponent as SupplyDispenseComponent */ SupplyDispenseComponent = (function(superClass) { extend(SupplyDispenseComponent, superClass); function SupplyDispenseComponent(json) { this.json = json; SupplyDispenseComponent.__super__.constructor.call(this, this.json); } /** Identifier assigned by the dispensing facility when the dispense occurs. @returns {Identifier} */ SupplyDispenseComponent.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** A code specifying the state of the dispense event. @returns {Array} an array of {@link String} objects */ SupplyDispenseComponent.prototype.status = function() { return this.json['status']; }; /** Indicates the type of dispensing event that is performed. Examples include: Trial Fill, Completion of Trial, Partial Fill, Emergency Fill, Samples, etc. @returns {CodeableConcept} */ SupplyDispenseComponent.prototype.type = function() { if (this.json['type']) { return new CodeableConcept(this.json['type']); } }; /** The amount of supply that has been dispensed. Includes unit of measure. @returns {Quantity} */ SupplyDispenseComponent.prototype.quantity = function() { if (this.json['quantity']) { return new Quantity(this.json['quantity']); } }; /** Identifies the medication or substance or device being dispensed. This is either a link to a resource representing the details of the item or a simple attribute carrying a code that identifies the item from a known list. @returns {Reference} */ SupplyDispenseComponent.prototype.suppliedItem = function() { if (this.json['suppliedItem']) { return new Reference(this.json['suppliedItem']); } }; /** The individual responsible for dispensing the medication, supplier or device. @returns {Reference} */ SupplyDispenseComponent.prototype.supplier = function() { if (this.json['supplier']) { return new Reference(this.json['supplier']); } }; /** The time the dispense event occurred. @returns {Period} */ SupplyDispenseComponent.prototype.whenPrepared = function() { if (this.json['whenPrepared']) { return new Period(this.json['whenPrepared']); } }; /** The time the dispensed item was sent or handed to the patient (or agent). @returns {Period} */ SupplyDispenseComponent.prototype.whenHandedOver = function() { if (this.json['whenHandedOver']) { return new Period(this.json['whenHandedOver']); } }; /** Identification of the facility/location where the Supply was shipped to, as part of the dispense event. @returns {Reference} */ SupplyDispenseComponent.prototype.destination = function() { if (this.json['destination']) { return new Reference(this.json['destination']); } }; /** Identifies the person who picked up the Supply. @returns {Array} an array of {@link Reference} objects */ SupplyDispenseComponent.prototype.receiver = function() { var i, item, len, ref, results; if (this.json['receiver']) { ref = this.json['receiver']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Reference(item)); } return results; } }; return SupplyDispenseComponent; })(BackboneElement); /** A supply - a request for something, and provision of what is supplied. @class Supply @exports Supply as Supply */ Supply = (function(superClass) { extend(Supply, superClass); function Supply(json) { this.json = json; Supply.__super__.constructor.call(this, this.json); } /** Category of supply, e.g. central, non-stock, etc. This is used to support work flows associated with the supply process. @returns {CodeableConcept} */ Supply.prototype.kind = function() { if (this.json['kind']) { return new CodeableConcept(this.json['kind']); } }; /** Unique identifier for this supply request. @returns {Identifier} */ Supply.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** Status of the supply request. @returns {Array} an array of {@link String} objects */ Supply.prototype.status = function() { return this.json['status']; }; /** The item that is requested to be supplied. @returns {Reference} */ Supply.prototype.orderedItem = function() { if (this.json['orderedItem']) { return new Reference(this.json['orderedItem']); } }; /** A link to a resource representing the person whom the ordered item is for. @returns {Reference} */ Supply.prototype.patient = function() { if (this.json['patient']) { return new Reference(this.json['patient']); } }; /** Indicates the details of the dispense event such as the days supply and quantity of a supply dispensed. @returns {Array} an array of {@link SupplyDispenseComponent} objects */ Supply.prototype.dispense = function() { var i, item, len, ref, results; if (this.json['dispense']) { ref = this.json['dispense']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SupplyDispenseComponent(item)); } return results; } }; return Supply; })(DomainResource); module.exports.Supply = Supply; }).call(this); },{"../cql-datatypes":117,"./core":173}],244:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, SupportingDocumentation, SupportingDocumentationDetailComponent, Timing, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class SupportingDocumentationDetailComponent @exports SupportingDocumentationDetailComponent as SupportingDocumentationDetailComponent */ SupportingDocumentationDetailComponent = (function(superClass) { extend(SupportingDocumentationDetailComponent, superClass); function SupportingDocumentationDetailComponent(json) { this.json = json; SupportingDocumentationDetailComponent.__super__.constructor.call(this, this.json); } /** A link Id for the response to reference. @returns {Array} an array of {@link Number} objects */ SupportingDocumentationDetailComponent.prototype.linkId = function() { return this.json['linkId']; }; /** The attached content. @returns {Reference} */ SupportingDocumentationDetailComponent.prototype.contentReference = function() { if (this.json['contentReference']) { return new Reference(this.json['contentReference']); } }; /** The attached content. @returns {Attachment} */ SupportingDocumentationDetailComponent.prototype.contentAttachment = function() { if (this.json['contentAttachment']) { return new Attachment(this.json['contentAttachment']); } }; /** The date and optionally time when the material was created. @returns {Array} an array of {@link Date} objects */ SupportingDocumentationDetailComponent.prototype.dateTime = function() { if (this.json['dateTime']) { return DT.DateTime.parse(this.json['dateTime']); } }; return SupportingDocumentationDetailComponent; })(BackboneElement); /** This resource provides the supporting information for a process, for example clinical or financial information related to a claim or pre-authorization. @class SupportingDocumentation @exports SupportingDocumentation as SupportingDocumentation */ SupportingDocumentation = (function(superClass) { extend(SupportingDocumentation, superClass); function SupportingDocumentation(json) { this.json = json; SupportingDocumentation.__super__.constructor.call(this, this.json); } /** The Response Business Identifier. @returns {Array} an array of {@link Identifier} objects */ SupportingDocumentation.prototype.identifier = function() { var i, item, len, ref, results; if (this.json['identifier']) { ref = this.json['identifier']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new Identifier(item)); } return results; } }; /** The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources. @returns {Coding} */ SupportingDocumentation.prototype.ruleset = function() { if (this.json['ruleset']) { return new Coding(this.json['ruleset']); } }; /** The style (standard) and version of the original material which was converted into this resource. @returns {Coding} */ SupportingDocumentation.prototype.originalRuleset = function() { if (this.json['originalRuleset']) { return new Coding(this.json['originalRuleset']); } }; /** The date when this resource was created. @returns {Array} an array of {@link Date} objects */ SupportingDocumentation.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** The Insurer, organization or Provider who is target of the submission. @returns {Reference} */ SupportingDocumentation.prototype.target = function() { if (this.json['target']) { return new Reference(this.json['target']); } }; /** The practitioner who is responsible for the services rendered to the patient. @returns {Reference} */ SupportingDocumentation.prototype.provider = function() { if (this.json['provider']) { return new Reference(this.json['provider']); } }; /** The organization which is responsible for the services rendered to the patient. @returns {Reference} */ SupportingDocumentation.prototype.organization = function() { if (this.json['organization']) { return new Reference(this.json['organization']); } }; /** Original request identifer. @returns {Reference} */ SupportingDocumentation.prototype.request = function() { if (this.json['request']) { return new Reference(this.json['request']); } }; /** Original response identifer. @returns {Reference} */ SupportingDocumentation.prototype.response = function() { if (this.json['response']) { return new Reference(this.json['response']); } }; /** Person who created the submission. @returns {Reference} */ SupportingDocumentation.prototype.author = function() { if (this.json['author']) { return new Reference(this.json['author']); } }; /** The patient who is directly or indirectly the subject of the supporting information. @returns {Reference} */ SupportingDocumentation.prototype.subject = function() { if (this.json['subject']) { return new Reference(this.json['subject']); } }; /** Supporting Files. @returns {Array} an array of {@link SupportingDocumentationDetailComponent} objects */ SupportingDocumentation.prototype.detail = function() { var i, item, len, ref, results; if (this.json['detail']) { ref = this.json['detail']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new SupportingDocumentationDetailComponent(item)); } return results; } }; return SupportingDocumentation; })(DomainResource); module.exports.SupportingDocumentation = SupportingDocumentation; }).call(this); },{"../cql-datatypes":117,"./core":173}],245:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Address, Attachment, BackboneElement, CORE, CodeableConcept, Coding, ConceptDefinitionComponent, ConceptDefinitionDesignationComponent, ConceptReferenceComponent, ConceptSetComponent, ConceptSetFilterComponent, ContactPoint, DT, DomainResource, Element, ElementDefinition, Extension, HumanName, Identifier, Narrative, Parameters, Period, Quantity, Range, Ratio, Reference, Resource, SampledData, Timing, ValueSet, ValueSetComposeComponent, ValueSetDefineComponent, ValueSetExpansionComponent, ValueSetExpansionContainsComponent, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; DT = require('../cql-datatypes'); CORE = require('./core'); Element = CORE.Element; Resource = CORE.Resource; Timing = CORE.Timing; Period = CORE.Period; Parameters = CORE.Parameters; Coding = CORE.Coding; Resource = CORE.Resource; Range = CORE.Range; Quantity = CORE.Quantity; Attachment = CORE.Attachment; BackboneElement = CORE.BackboneElement; DomainResource = CORE.DomainResource; ContactPoint = CORE.ContactPoint; ElementDefinition = CORE.ElementDefinition; Extension = CORE.Extension; HumanName = CORE.HumanName; Address = CORE.Address; Ratio = CORE.Ratio; SampledData = CORE.SampledData; Reference = CORE.Reference; CodeableConcept = CORE.CodeableConcept; Identifier = CORE.Identifier; Narrative = CORE.Narrative; Element = CORE.Element; /** Embedded class @class ConceptDefinitionDesignationComponent @exports ConceptDefinitionDesignationComponent as ConceptDefinitionDesignationComponent */ ConceptDefinitionDesignationComponent = (function(superClass) { extend(ConceptDefinitionDesignationComponent, superClass); function ConceptDefinitionDesignationComponent(json) { this.json = json; ConceptDefinitionDesignationComponent.__super__.constructor.call(this, this.json); } /** The language this designation is defined for. @returns {Array} an array of {@link String} objects */ ConceptDefinitionDesignationComponent.prototype.language = function() { return this.json['language']; }; /** A code that details how this designation would be used. @returns {Coding} */ ConceptDefinitionDesignationComponent.prototype.use = function() { if (this.json['use']) { return new Coding(this.json['use']); } }; /** The text value for this designation. @returns {Array} an array of {@link String} objects */ ConceptDefinitionDesignationComponent.prototype.value = function() { return this.json['value']; }; return ConceptDefinitionDesignationComponent; })(BackboneElement); /** Embedded class @class ConceptDefinitionComponent @exports ConceptDefinitionComponent as ConceptDefinitionComponent */ ConceptDefinitionComponent = (function(superClass) { extend(ConceptDefinitionComponent, superClass); function ConceptDefinitionComponent(json) { this.json = json; ConceptDefinitionComponent.__super__.constructor.call(this, this.json); } /** Code that identifies concept. @returns {Array} an array of {@link String} objects */ ConceptDefinitionComponent.prototype.code = function() { return this.json['code']; }; /** If this code is not for use as a real concept. @returns {Array} an array of {@link boolean} objects */ ConceptDefinitionComponent.prototype.abstract = function() { return this.json['abstract']; }; /** Text to Display to the user. @returns {Array} an array of {@link String} objects */ ConceptDefinitionComponent.prototype.display = function() { return this.json['display']; }; /** The formal definition of the concept. Formal definitions are not required, because of the prevalence of legacy systems without them, but they are highly recommended, as without them there is no formal meaning associated with the concept. @returns {Array} an array of {@link String} objects */ ConceptDefinitionComponent.prototype.definition = function() { return this.json['definition']; }; /** Additional representations for the concept - other languages, aliases, specialised purposes, used for particular purposes, etc. @returns {Array} an array of {@link ConceptDefinitionDesignationComponent} objects */ ConceptDefinitionComponent.prototype.designation = function() { var i, item, len, ref, results; if (this.json['designation']) { ref = this.json['designation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptDefinitionDesignationComponent(item)); } return results; } }; /** Child Concepts (is-a / contains). @returns {Array} an array of {@link ConceptDefinitionComponent} objects */ ConceptDefinitionComponent.prototype.concept = function() { var i, item, len, ref, results; if (this.json['concept']) { ref = this.json['concept']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptDefinitionComponent(item)); } return results; } }; return ConceptDefinitionComponent; })(BackboneElement); /** Embedded class @class ValueSetDefineComponent @exports ValueSetDefineComponent as ValueSetDefineComponent */ ValueSetDefineComponent = (function(superClass) { extend(ValueSetDefineComponent, superClass); function ValueSetDefineComponent(json) { this.json = json; ValueSetDefineComponent.__super__.constructor.call(this, this.json); } /** URI to identify the code system. @returns {Array} an array of {@link String} objects */ ValueSetDefineComponent.prototype.system = function() { return this.json['system']; }; /** The version of this code system that defines the codes. Note that the version is optional because a well maintained code system does not suffer from versioning, and therefore the version does not need to be maintained. However many code systems are not well maintained, and the version needs to be defined and tracked. @returns {Array} an array of {@link String} objects */ ValueSetDefineComponent.prototype.version = function() { return this.json['version']; }; /** If code comparison is case sensitive when codes within this system are compared to each other. @returns {Array} an array of {@link boolean} objects */ ValueSetDefineComponent.prototype.caseSensitive = function() { return this.json['caseSensitive']; }; /** Concepts in the code system. @returns {Array} an array of {@link ConceptDefinitionComponent} objects */ ValueSetDefineComponent.prototype.concept = function() { var i, item, len, ref, results; if (this.json['concept']) { ref = this.json['concept']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptDefinitionComponent(item)); } return results; } }; return ValueSetDefineComponent; })(BackboneElement); /** Embedded class @class ConceptReferenceComponent @exports ConceptReferenceComponent as ConceptReferenceComponent */ ConceptReferenceComponent = (function(superClass) { extend(ConceptReferenceComponent, superClass); function ConceptReferenceComponent(json) { this.json = json; ConceptReferenceComponent.__super__.constructor.call(this, this.json); } /** Specifies a code for the concept to be included or excluded. @returns {Array} an array of {@link String} objects */ ConceptReferenceComponent.prototype.code = function() { return this.json['code']; }; /** The text to display to the user for this concept in the context of this valueset. If no display is provided, then applications using the value set use the display specified for the code by the system. @returns {Array} an array of {@link String} objects */ ConceptReferenceComponent.prototype.display = function() { return this.json['display']; }; /** Additional representations for this concept when used in this value set - other languages, aliases, specialised purposes, used for particular purposes, etc. @returns {Array} an array of {@link ConceptDefinitionDesignationComponent} objects */ ConceptReferenceComponent.prototype.designation = function() { var i, item, len, ref, results; if (this.json['designation']) { ref = this.json['designation']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptDefinitionDesignationComponent(item)); } return results; } }; return ConceptReferenceComponent; })(BackboneElement); /** Embedded class @class ConceptSetFilterComponent @exports ConceptSetFilterComponent as ConceptSetFilterComponent */ ConceptSetFilterComponent = (function(superClass) { extend(ConceptSetFilterComponent, superClass); function ConceptSetFilterComponent(json) { this.json = json; ConceptSetFilterComponent.__super__.constructor.call(this, this.json); } /** A code that identifies a property defined in the code system. @returns {Array} an array of {@link String} objects */ ConceptSetFilterComponent.prototype.property = function() { return this.json['property']; }; /** The kind of operation to perform as a part of the filter criteria. @returns {Array} an array of {@link String} objects */ ConceptSetFilterComponent.prototype.op = function() { return this.json['op']; }; /** The match value may be either a code defined by the system, or a string value which is used a regex match on the literal string of the property value. @returns {Array} an array of {@link String} objects */ ConceptSetFilterComponent.prototype.value = function() { return this.json['value']; }; return ConceptSetFilterComponent; })(BackboneElement); /** Embedded class @class ConceptSetComponent @exports ConceptSetComponent as ConceptSetComponent */ ConceptSetComponent = (function(superClass) { extend(ConceptSetComponent, superClass); function ConceptSetComponent(json) { this.json = json; ConceptSetComponent.__super__.constructor.call(this, this.json); } /** The code system from which the selected codes come from. @returns {Array} an array of {@link String} objects */ ConceptSetComponent.prototype.system = function() { return this.json['system']; }; /** The version of the code system that the codes are selected from. @returns {Array} an array of {@link String} objects */ ConceptSetComponent.prototype.version = function() { return this.json['version']; }; /** Specifies a concept to be included or excluded. @returns {Array} an array of {@link ConceptReferenceComponent} objects */ ConceptSetComponent.prototype.concept = function() { var i, item, len, ref, results; if (this.json['concept']) { ref = this.json['concept']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptReferenceComponent(item)); } return results; } }; /** Select concepts by specify a matching criteria based on the properties (including relationships) defined by the system. If multiple filters are specified, they SHALL all be true. @returns {Array} an array of {@link ConceptSetFilterComponent} objects */ ConceptSetComponent.prototype.filter = function() { var i, item, len, ref, results; if (this.json['filter']) { ref = this.json['filter']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptSetFilterComponent(item)); } return results; } }; return ConceptSetComponent; })(BackboneElement); /** Embedded class @class ValueSetComposeComponent @exports ValueSetComposeComponent as ValueSetComposeComponent */ ValueSetComposeComponent = (function(superClass) { extend(ValueSetComposeComponent, superClass); function ValueSetComposeComponent(json) { this.json = json; ValueSetComposeComponent.__super__.constructor.call(this, this.json); } /** Includes the contents of the referenced value set as a part of the contents of this value set. @returns {Array} an array of {@link String} objects */ ValueSetComposeComponent.prototype["import"] = function() { return this.json['import']; }; /** Include one or more codes from a code system. @returns {Array} an array of {@link ConceptSetComponent} objects */ ValueSetComposeComponent.prototype.include = function() { var i, item, len, ref, results; if (this.json['include']) { ref = this.json['include']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptSetComponent(item)); } return results; } }; /** Exclude one or more codes from the value set. @returns {Array} an array of {@link ConceptSetComponent} objects */ ValueSetComposeComponent.prototype.exclude = function() { var i, item, len, ref, results; if (this.json['exclude']) { ref = this.json['exclude']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ConceptSetComponent(item)); } return results; } }; return ValueSetComposeComponent; })(BackboneElement); /** Embedded class @class ValueSetExpansionContainsComponent @exports ValueSetExpansionContainsComponent as ValueSetExpansionContainsComponent */ ValueSetExpansionContainsComponent = (function(superClass) { extend(ValueSetExpansionContainsComponent, superClass); function ValueSetExpansionContainsComponent(json) { this.json = json; ValueSetExpansionContainsComponent.__super__.constructor.call(this, this.json); } /** The system in which the code for this item in the expansion is defined. @returns {Array} an array of {@link String} objects */ ValueSetExpansionContainsComponent.prototype.system = function() { return this.json['system']; }; /** If true, this entry is included in the expansion for navigational purposes, and the user cannot select the code directly as a proper value. @returns {Array} an array of {@link boolean} objects */ ValueSetExpansionContainsComponent.prototype.abstract = function() { return this.json['abstract']; }; /** The version of this code system that defined this code and/or display. This should only be used with code systems that do not enforce concept permanence. @returns {Array} an array of {@link String} objects */ ValueSetExpansionContainsComponent.prototype.version = function() { return this.json['version']; }; /** Code - if blank, this is not a choosable code. @returns {Array} an array of {@link String} objects */ ValueSetExpansionContainsComponent.prototype.code = function() { return this.json['code']; }; /** User display for the concept. @returns {Array} an array of {@link String} objects */ ValueSetExpansionContainsComponent.prototype.display = function() { return this.json['display']; }; /** Codes contained in this concept. @returns {Array} an array of {@link ValueSetExpansionContainsComponent} objects */ ValueSetExpansionContainsComponent.prototype.contains = function() { var i, item, len, ref, results; if (this.json['contains']) { ref = this.json['contains']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ValueSetExpansionContainsComponent(item)); } return results; } }; return ValueSetExpansionContainsComponent; })(BackboneElement); /** Embedded class @class ValueSetExpansionComponent @exports ValueSetExpansionComponent as ValueSetExpansionComponent */ ValueSetExpansionComponent = (function(superClass) { extend(ValueSetExpansionComponent, superClass); function ValueSetExpansionComponent(json) { this.json = json; ValueSetExpansionComponent.__super__.constructor.call(this, this.json); } /** An identifier that uniquely identifies this expansion of the valueset. Systems may re-use the same identifier as long as the expansion and the definition remain the same, but are not required to do so. @returns {Identifier} */ ValueSetExpansionComponent.prototype.identifier = function() { if (this.json['identifier']) { return new Identifier(this.json['identifier']); } }; /** The time at which the expansion was produced by the expanding system. @returns {Array} an array of {@link Date} objects */ ValueSetExpansionComponent.prototype.timestamp = function() { if (this.json['timestamp']) { return DT.DateTime.parse(this.json['timestamp']); } }; /** The codes that are contained in the value set expansion. @returns {Array} an array of {@link ValueSetExpansionContainsComponent} objects */ ValueSetExpansionComponent.prototype.contains = function() { var i, item, len, ref, results; if (this.json['contains']) { ref = this.json['contains']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ValueSetExpansionContainsComponent(item)); } return results; } }; return ValueSetExpansionComponent; })(BackboneElement); /** A value set specifies a set of codes drawn from one or more code systems. @class ValueSet @exports ValueSet as ValueSet */ ValueSet = (function(superClass) { extend(ValueSet, superClass); function ValueSet(json) { this.json = json; ValueSet.__super__.constructor.call(this, this.json); } /** The identifier that is used to identify this value set when it is referenced in a specification, model, design or an instance (should be globally unique OID, UUID, or URI). @returns {Array} an array of {@link String} objects */ ValueSet.prototype.identifier = function() { return this.json['identifier']; }; /** The identifier that is used to identify this version of the value set when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the profile author manually and the value should be a timestamp. @returns {Array} an array of {@link String} objects */ ValueSet.prototype.version = function() { return this.json['version']; }; /** A free text natural language name describing the value set. @returns {Array} an array of {@link String} objects */ ValueSet.prototype.name = function() { return this.json['name']; }; /** This should describe "the semantic space" to be included in the value set. This can also describe the approach taken to build the value set. @returns {Array} an array of {@link String} objects */ ValueSet.prototype.purpose = function() { return this.json['purpose']; }; /** If this is set to 'true', then no new versions of the content logical definition can be created. Note: Other metadata might still change. @returns {Array} an array of {@link boolean} objects */ ValueSet.prototype.immutable = function() { return this.json['immutable']; }; /** The name of the individual or organization that published the value set. @returns {Array} an array of {@link String} objects */ ValueSet.prototype.publisher = function() { return this.json['publisher']; }; /** Contacts of the publisher to assist a user in finding and communicating with the publisher. @returns {Array} an array of {@link ContactPoint} objects */ ValueSet.prototype.telecom = function() { var i, item, len, ref, results; if (this.json['telecom']) { ref = this.json['telecom']; results = []; for (i = 0, len = ref.length; i < len; i++) { item = ref[i]; results.push(new ContactPoint(item)); } return results; } }; /** A free text natural language description of the use of the value set - reason for definition, conditions of use, etc. The description may include a list of expected usages for the value set. @returns {Array} an array of {@link String} objects */ ValueSet.prototype.description = function() { return this.json['description']; }; /** A copyright statement relating to the value set and/or its contents. These are generally legal restrictions on the use and publishing of the value set. @returns {Array} an array of {@link String} objects */ ValueSet.prototype.copyright = function() { return this.json['copyright']; }; /** The status of the value set. @returns {Array} an array of {@link String} objects */ ValueSet.prototype.status = function() { return this.json['status']; }; /** This valueset was authored for testing purposes (or education/evaluation/marketing), and is not intended to be used for genuine usage. @returns {Array} an array of {@link boolean} objects */ ValueSet.prototype.experimental = function() { return this.json['experimental']; }; /** Whether this is intended to be used with an extensible binding or not. @returns {Array} an array of {@link boolean} objects */ ValueSet.prototype.extensible = function() { return this.json['extensible']; }; /** The date that the value set status was last changed. @returns {Array} an array of {@link Date} objects */ ValueSet.prototype.date = function() { if (this.json['date']) { return DT.DateTime.parse(this.json['date']); } }; /** If a Stability Date is expanded by evaluating the Content Logical Definition using the current version of all referenced code system(s) and value sets as of the Stability Date. @returns {Array} an array of {@link Date} objects */ ValueSet.prototype.stableDate = function() { if (this.json['stableDate']) { return DT.DateTime.parse(this.json['stableDate']); } }; /** When value set defines its own codes. @returns {ValueSetDefineComponent} */ ValueSet.prototype.define = function() { if (this.json['define']) { return new ValueSetDefineComponent(this.json['define']); } }; /** When value set includes codes from elsewhere. @returns {ValueSetComposeComponent} */ ValueSet.prototype.compose = function() { if (this.json['compose']) { return new ValueSetComposeComponent(this.json['compose']); } }; /** A value set can also be "expanded", where the value set is turned into a simple collection of enumerated codes. This element holds the expansion, if it has been performed. @returns {ValueSetExpansionComponent} */ ValueSet.prototype.expansion = function() { if (this.json['expansion']) { return new ValueSetExpansionComponent(this.json['expansion']); } }; return ValueSet; })(DomainResource); module.exports.ValueSet = ValueSet; }).call(this); },{"../cql-datatypes":117,"./core":173}],246:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Context, Exception, Library, PatientContext, UnfilteredContext, dt, typeIsArray, util, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Library = require('../elm/library').Library; Exception = require('../datatypes/exception').Exception; typeIsArray = require('../util/util').typeIsArray; dt = require('../datatypes/datatypes'); util = require('util'); Function.prototype.property = function(prop, desc) { return Object.defineProperty(this.prototype, prop, desc); }; module.exports.Context = Context = (function() { function Context(parent, _codeService, _parameters) { this.parent = parent; this._codeService = _codeService != null ? _codeService : null; if (_parameters == null) { _parameters = {}; } this.context_values = {}; this.library_context = {}; this.localId_context = {}; this.checkParameters(_parameters); this._parameters = _parameters; } Context.property("parameters", { get: function() { var ref; return this._parameters || ((ref = this.parent) != null ? ref.parameters : void 0); }, set: function(params) { this.checkParameters(params); return this._parameters = params; } }); Context.property("codeService", { get: function() { var ref; return this._codeService || ((ref = this.parent) != null ? ref.codeService : void 0); }, set: function(cs) { return this._codeService = cs; } }); Context.prototype.withParameters = function(params) { this.parameters = params != null ? params : {}; return this; }; Context.prototype.withCodeService = function(cs) { this.codeService = cs; return this; }; Context.prototype.rootContext = function() { if (this.parent) { return this.parent.rootContext(); } else { return this; } }; Context.prototype.findRecords = function(profile) { var ref; return (ref = this.parent) != null ? ref.findRecords(profile) : void 0; }; Context.prototype.childContext = function(context_values) { var ctx; if (context_values == null) { context_values = {}; } ctx = new Context(this); ctx.context_values = context_values; return ctx; }; Context.prototype.getLibraryContext = function(library) { var ref; return (ref = this.parent) != null ? ref.getLibraryContext(library) : void 0; }; Context.prototype.getLocalIdContext = function(localId) { var ref; return (ref = this.parent) != null ? ref.getLocalIdContext(localId) : void 0; }; Context.prototype.getParameter = function(name) { var ref; return (ref = this.parent) != null ? ref.getParameter(name) : void 0; }; Context.prototype.getParentParameter = function(name) { var ref; if (((ref = this.parent) != null ? ref.parameters[name] : void 0) != null) { return this.parent.parameters[name]; } else if (this.parent != null) { return this.parent.getParentParameter(name); } }; Context.prototype.getTimezoneOffset = function() { var ref; if (this.executionDateTime != null) { return this.executionDateTime.timezoneOffset; } else if (((ref = this.parent) != null ? ref.getTimezoneOffset : void 0) != null) { return this.parent.getTimezoneOffset(); } else { throw new Exception("No Timezone Offset has been set"); } }; Context.prototype.getExecutionDateTime = function() { var ref; if (this.executionDateTime != null) { return this.executionDateTime; } else if (((ref = this.parent) != null ? ref.getExecutionDateTime : void 0) != null) { return this.parent.getExecutionDateTime(); } else { throw new Exception("No Execution DateTime has been set"); } }; Context.prototype.getValueSet = function(name, library) { var ref; return (ref = this.parent) != null ? ref.getValueSet(name, library) : void 0; }; Context.prototype.getCodeSystem = function(name) { var ref; return (ref = this.parent) != null ? ref.getCodeSystem(name) : void 0; }; Context.prototype.getCode = function(name) { var ref; return (ref = this.parent) != null ? ref.getCode(name) : void 0; }; Context.prototype.getConcept = function(name) { var ref; return (ref = this.parent) != null ? ref.getConcept(name) : void 0; }; Context.prototype.get = function(identifier) { var ref; if (typeof this.context_values[identifier] !== 'undefined') { return this.context_values[identifier]; } else if (identifier === "$this") { return this.context_values; } else { return (ref = this.parent) != null ? ref.get(identifier) : void 0; } }; Context.prototype.set = function(identifier, value) { return this.context_values[identifier] = value; }; Context.prototype.setLocalIdWithResult = function(localId, value) { var ctx; ctx = this.localId_context[localId]; if (ctx === false || ctx === null || ctx === void 0 || ctx.length === 0) { return this.localId_context[localId] = value; } else { return ctx; } }; Context.prototype.getLocalIdResult = function(localId) { return this.localId_context[localId]; }; Context.prototype.getAllLocalIds = function() { var lib, libName, localIdResults, ref; localIdResults = {}; localIdResults[this.parent.source.library.identifier.id] = {}; localIdResults[this.parent.source.library.identifier.id] = this.localId_context; ref = this.library_context; for (libName in ref) { lib = ref[libName]; this.supportLibraryLocalIds(lib, localIdResults); } return localIdResults; }; Context.prototype.supportLibraryLocalIds = function(lib, localIdResults) { var ref, results, supportLib, supportLibName; if (localIdResults[lib.library.source.library.identifier.id] != null) { this.mergeLibraryLocalIdResults(localIdResults, lib.library.source.library.identifier.id, lib.localId_context); } else { localIdResults[lib.library.source.library.identifier.id] = lib.localId_context; } ref = lib.library_context; results = []; for (supportLibName in ref) { supportLib = ref[supportLibName]; results.push(this.supportLibraryLocalIds(supportLib, localIdResults)); } return results; }; Context.prototype.mergeLibraryLocalIdResults = function(localIdResults, libraryId, libraryResults) { var existingResult, localId, localIdResult, results; results = []; for (localId in libraryResults) { localIdResult = libraryResults[localId]; existingResult = localIdResults[libraryId][localId]; if (existingResult === false || existingResult === null || existingResult === void 0 || existingResult.length === 0) { results.push(localIdResults[libraryId][localId] = localIdResult); } else { results.push(void 0); } } return results; }; Context.prototype.checkParameters = function(params) { var pDef, pName, pVal; for (pName in params) { pVal = params[pName]; pDef = this.getParameter(pName); if (pVal == null) { return; } if (typeof pDef === "undefined") { return; } else if ((pDef.parameterTypeSpecifier != null) && !this.matchesTypeSpecifier(pVal, pDef.parameterTypeSpecifier)) { throw new Error("Passed in parameter '" + pName + "' is wrong type"); } else if ((pDef['default'] != null) && !this.matchesInstanceType(pVal, pDef['default'])) { throw new Error("Passed in parameter '" + pName + "' is wrong type"); } } return true; }; Context.prototype.matchesTypeSpecifier = function(val, spec) { switch (spec.type) { case "NamedTypeSpecifier": return this.matchesNamedTypeSpecifier(val, spec); case "ListTypeSpecifier": return this.matchesListTypeSpecifier(val, spec); case "TupleTypeSpecifier": return this.matchesTupleTypeSpecifier(val, spec); case "IntervalTypeSpecifier": return this.matchesIntervalTypeSpecifier(val, spec); default: return true; } }; Context.prototype.matchesListTypeSpecifier = function(val, spec) { return typeIsArray(val) && val.every((function(_this) { return function(x) { return _this.matchesTypeSpecifier(x, spec.elementType); }; })(this)); }; Context.prototype.matchesTupleTypeSpecifier = function(val, spec) { return typeof val === "object" && !typeIsArray(val) && spec.element.every((function(_this) { return function(x) { return typeof val[x.name] === "undefined" || _this.matchesTypeSpecifier(val[x.name], x.elementType); }; })(this)); }; Context.prototype.matchesIntervalTypeSpecifier = function(val, spec) { return val.isInterval && ((val.low == null) || this.matchesTypeSpecifier(val.low, spec.pointType)) && ((val.high == null) || this.matchesTypeSpecifier(val.high, spec.pointType)); }; Context.prototype.matchesNamedTypeSpecifier = function(val, spec) { switch (spec.name) { case "{urn:hl7-org:elm-types:r1}Boolean": return typeof val === "boolean"; case "{urn:hl7-org:elm-types:r1}Decimal": return typeof val === "number"; case "{urn:hl7-org:elm-types:r1}Integer": return typeof val === "number" && Math.floor(val) === val; case "{urn:hl7-org:elm-types:r1}String": return typeof val === "string"; case "{urn:hl7-org:elm-types:r1}Concept": return val != null ? val.isConcept : void 0; case "{urn:hl7-org:elm-types:r1}Code": return val != null ? val.isCode : void 0; case "{urn:hl7-org:elm-types:r1}DateTime": return val != null ? val.isDateTime : void 0; case "{urn:hl7-org:elm-types:r1}Date": return val != null ? val.isDate : void 0; case "{urn:hl7-org:elm-types:r1}Quantity": return val != null ? val.isQuantity : void 0; case "{urn:hl7-org:elm-types:r1}Time": return (val != null ? val.isDateTime : void 0) && val.isTime(); default: return true; } }; Context.prototype.matchesInstanceType = function(val, inst) { switch (false) { case !inst.isBooleanLiteral: return typeof val === "boolean"; case !inst.isDecimalLiteral: return typeof val === "number"; case !inst.isIntegerLiteral: return typeof val === "number" && Math.floor(val) === val; case !inst.isStringLiteral: return typeof val === "string"; case !inst.isCode: return val != null ? val.isCode : void 0; case !inst.isConcept: return val != null ? val.isConcept : void 0; case !inst.isDateTime: return val != null ? val.isDateTime : void 0; case !inst.isQuantity: return val != null ? val.isQuantity : void 0; case !inst.isTime: return (val != null ? val.isDateTime : void 0) && val.isTime(); case !inst.isList: return this.matchesListInstanceType(val, inst); case !inst.isTuple: return this.matchesTupleInstanceType(val, inst); case !inst.isInterval: return this.matchesIntervalInstanceType(val, inst); default: return true; } }; Context.prototype.matchesListInstanceType = function(val, list) { return typeIsArray(val) && val.every((function(_this) { return function(x) { return _this.matchesInstanceType(x, list.elements[0]); }; })(this)); }; Context.prototype.matchesTupleInstanceType = function(val, tpl) { return typeof val === "object" && !typeIsArray(val) && tpl.elements.every((function(_this) { return function(x) { return typeof val[x.name] === "undefined" || _this.matchesInstanceType(val[x.name], x.value); }; })(this)); }; Context.prototype.matchesIntervalInstanceType = function(val, ivl) { var pointType, ref; pointType = (ref = ivl.low) != null ? ref : ivl.high; return val.isInterval && ((val.low == null) || this.matchesInstanceType(val.low, pointType)) && ((val.high == null) || this.matchesInstanceType(val.high, pointType)); }; return Context; })(); module.exports.PatientContext = PatientContext = (function(superClass) { extend(PatientContext, superClass); function PatientContext(library1, patient, codeService, parameters, executionDateTime) { this.library = library1; this.patient = patient; this.executionDateTime = executionDateTime != null ? executionDateTime : dt.DateTime.fromJSDate(new Date()); PatientContext.__super__.constructor.call(this, this.library, codeService, parameters); } PatientContext.prototype.rootContext = function() { return this; }; PatientContext.prototype.getLibraryContext = function(library) { var base; return (base = this.library_context)[library] || (base[library] = new PatientContext(this.get(library), this.patient, this.codeService, this.parameters, this.executionDateTime)); }; PatientContext.prototype.getLocalIdContext = function(localId) { var base; return (base = this.localId_context)[localId] || (base[localId] = new PatientContext(this.get(library), this.patient, this.codeService, this.parameters, this.executionDateTime)); }; PatientContext.prototype.findRecords = function(profile) { var ref; return (ref = this.patient) != null ? ref.findRecords(profile) : void 0; }; return PatientContext; })(Context); module.exports.UnfilteredContext = UnfilteredContext = (function(superClass) { extend(UnfilteredContext, superClass); function UnfilteredContext(library1, results, codeService, parameters, executionDateTime) { this.library = library1; this.results = results; this.executionDateTime = executionDateTime != null ? executionDateTime : dt.DateTime.fromJSDate(new Date()); UnfilteredContext.__super__.constructor.call(this, this.library, codeService, parameters); } UnfilteredContext.prototype.rootContext = function() { return this; }; UnfilteredContext.prototype.findRecords = function(template) { throw new Exception("Retreives are not currently supported in Unfiltered Context"); }; UnfilteredContext.prototype.getLibraryContext = function(library) { throw new Exception("Library expressions are not currently supported in Unfiltered Context"); }; UnfilteredContext.prototype.get = function(identifier) { var pid, ref, ref1, res, results; if (this.context_values[identifier]) { return this.context_values[identifier]; } if (((ref = this.library[identifier]) != null ? ref.context : void 0) === "Unfiltered") { return this.library.expressions[identifier]; } ref1 = this.results.patientResults; results = []; for (pid in ref1) { res = ref1[pid]; results.push(res[identifier]); } return results; }; return UnfilteredContext; })(Context); }).call(this); },{"../datatypes/datatypes":121,"../datatypes/exception":123,"../elm/library":142,"../util/util":252,"util":414}],247:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Executor, PatientContext, Results, UnfilteredContext, ref; module.exports.Executor = Executor = (function() { function Executor(library, codeService, parameters) { this.library = library; this.codeService = codeService; this.parameters = parameters; } Executor.prototype.withLibrary = function(lib) { this.library = lib; return this; }; Executor.prototype.withParameters = function(params) { this.parameters = params != null ? params : {}; return this; }; Executor.prototype.withCodeService = function(cs) { this.codeService = cs; return this; }; Executor.prototype.exec_expression = function(expression, patientSource) { var expr, p, patient_ctx, r; Results(r = new Results()); expr = this.library.expressions[expression]; while (expr && (p = patientSource.currentPatient())) { patient_ctx = new PatientContext(this.library, p, this.codeService, this.parameters); r.recordPatientResult(patient_ctx, expression, expr.execute(patient_ctx)); patientSource.nextPatient(); } return r; }; Executor.prototype.exec = function(patientSource, executionDateTime) { var expr, key, r, ref, unfilteredContext; Results(r = this.exec_patient_context(patientSource, executionDateTime)); unfilteredContext = new UnfilteredContext(this.library, r, this.codeService, this.parameters); ref = this.library.expressions; for (key in ref) { expr = ref[key]; if (expr.context === "Unfiltered") { r.recordUnfilteredResult(key, expr.exec(unfilteredContext)); } } return r; }; Executor.prototype.exec_patient_context = function(patientSource, executionDateTime) { var expr, key, p, patient_ctx, r, ref; Results(r = new Results()); while (p = patientSource.currentPatient()) { patient_ctx = new PatientContext(this.library, p, this.codeService, this.parameters, executionDateTime); ref = this.library.expressions; for (key in ref) { expr = ref[key]; if (expr.context === "Patient") { r.recordPatientResult(patient_ctx, key, expr.execute(patient_ctx)); } } patientSource.nextPatient(); } return r; }; return Executor; })(); Results = require('./results').Results; ref = require('./context'), UnfilteredContext = ref.UnfilteredContext, PatientContext = ref.PatientContext; }).call(this); },{"./context":246,"./results":249}],248:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Repository, cql; cql = require('../cql'); module.exports.Repository = Repository = (function() { function Repository(data) { var k, v; this.data = data; this.libraries = (function() { var ref, results; ref = this.data; results = []; for (k in ref) { v = ref[k]; results.push(v); } return results; }).call(this); } Repository.prototype.resolve = function(library, version) { var i, len, lib, ref, ref1, ref2, ref3, ref4; ref = this.libraries; for (i = 0, len = ref.length; i < len; i++) { lib = ref[i]; if (((ref1 = lib.library) != null ? (ref2 = ref1.identifier) != null ? ref2.id : void 0 : void 0) === library && ((ref3 = lib.library) != null ? (ref4 = ref3.identifier) != null ? ref4.version : void 0 : void 0) === version) { return new cql.Library(lib, this); } } }; return Repository; })(); }).call(this); },{"../cql":119}],249:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Results; module.exports.Results = Results = (function() { function Results() { this.patientResults = {}; this.unfilteredResults = {}; this.localIdPatientResultsMap = {}; } Results.prototype.recordPatientResult = function(patient_ctx, resultName, result) { var base, p, patientId; p = patient_ctx.patient; patientId = typeof p.getId === 'function' ? p.getId() : p.id(); if ((base = this.patientResults)[patientId] == null) { base[patientId] = {}; } this.patientResults[patientId][resultName] = result; return this.localIdPatientResultsMap[patientId] = patient_ctx.getAllLocalIds(); }; Results.prototype.recordUnfilteredResult = function(resultName, result) { return this.unfilteredResults[resultName] = result; }; return Results; })(); }).call(this); },{}],250:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DateTime, Uncertainty, areDateTimesOrQuantities, areNumbers, classesEqual, codesAreEquivalent, compareEveryItemInArrays, compareObjects, deepCompareKeysAndValues, equals, equivalent, getClassOfObjects, getKeysFromObject, isCode, isFunction, isUncertainty; DateTime = require('../datatypes/datetime').DateTime; Uncertainty = require('../datatypes/uncertainty').Uncertainty; areNumbers = function(a, b) { return typeof a === 'number' && typeof b === 'number'; }; areDateTimesOrQuantities = function(a, b) { return (a != null ? a.isDateTime : void 0) && (b != null ? b.isDateTime : void 0) || (a != null ? a.isDate : void 0) && (b != null ? b.isDate : void 0) || (a != null ? a.isTime : void 0) && (b != null ? b.isTime : void 0) || (a != null ? a.isQuantity : void 0) && (b != null ? b.isQuantity : void 0); }; isUncertainty = function(x) { return x instanceof Uncertainty; }; module.exports.lessThan = function(a, b, precision) { switch (false) { case !areNumbers(a, b): return a < b; case !areDateTimesOrQuantities(a, b): return a.before(b, precision); case !isUncertainty(a): return a.lessThan(b); case !isUncertainty(b): return Uncertainty.from(a).lessThan(b); default: return null; } }; module.exports.lessThanOrEquals = function(a, b, precision) { switch (false) { case !areNumbers(a, b): return a <= b; case !areDateTimesOrQuantities(a, b): return a.sameOrBefore(b, precision); case !isUncertainty(a): return a.lessThanOrEquals(b); case !isUncertainty(b): return Uncertainty.from(a).lessThanOrEquals(b); default: return null; } }; module.exports.greaterThan = function(a, b, precision) { switch (false) { case !areNumbers(a, b): return a > b; case !areDateTimesOrQuantities(a, b): return a.after(b, precision); case !isUncertainty(a): return a.greaterThan(b); case !isUncertainty(b): return Uncertainty.from(a).greaterThan(b); default: return null; } }; module.exports.greaterThanOrEquals = function(a, b, precision) { switch (false) { case !areNumbers(a, b): return a >= b; case !areDateTimesOrQuantities(a, b): return a.sameOrAfter(b, precision); case !isUncertainty(a): return a.greaterThanOrEquals(b); case !isUncertainty(b): return Uncertainty.from(a).greaterThanOrEquals(b); default: return null; } }; module.exports.equivalent = equivalent = function(a, b) { var aClass, bClass, ref; if ((a == null) && (b == null)) { return true; } if (!((a != null) && (b != null))) { return false; } if (isCode(a)) { return codesAreEquivalent(a, b); } if (typeof a.equivalent === 'function') { return a.equivalent(b); } ref = getClassOfObjects(a, b), aClass = ref[0], bClass = ref[1]; switch (aClass) { case '[object Array]': return compareEveryItemInArrays(a, b, equivalent); case '[object Object]': return compareObjects(a, b, equivalent); case '[object String]': if (bClass === '[object String]') { a = a.replace(/\s/g, ' '); b = b.replace(/\s/g, ' '); return (a.localeCompare(b, 'en', { sensitivity: 'base' })) === 0; } } return equals(a, b); }; isCode = function(object) { return object.hasMatch && typeof object.hasMatch === 'function'; }; codesAreEquivalent = function(code1, code2) { return code1.hasMatch(code2); }; getClassOfObjects = function(object1, object2) { var obj; return (function() { var j, len, ref, results; ref = [object1, object2]; results = []; for (j = 0, len = ref.length; j < len; j++) { obj = ref[j]; results.push({}.toString.call(obj)); } return results; })(); }; compareEveryItemInArrays = function(array1, array2, comparisonFunction) { return array1.length === array2.length && array1.every(function(item, i) { return comparisonFunction(item, array2[i]); }); }; compareObjects = function(a, b, comparisonFunction) { if (!classesEqual(a, b)) { return false; } return deepCompareKeysAndValues(a, b, comparisonFunction); }; classesEqual = function(object1, object2) { return object2 instanceof object1.constructor && object1 instanceof object2.constructor; }; deepCompareKeysAndValues = function(a, b, comparisonFunction) { var aKeys, bKeys, finalComparisonResult, shouldReturnNull; aKeys = getKeysFromObject(a).sort(); bKeys = getKeysFromObject(b).sort(); shouldReturnNull = false; if (aKeys.length === bKeys.length && aKeys.every((function(_this) { return function(value, index) { return value === bKeys[index]; }; })(this))) { finalComparisonResult = aKeys.every(function(key) { var comparisonResult; if ((a[key] == null) && (b[key] == null)) { return true; } comparisonResult = comparisonFunction(a[key], b[key]); if (comparisonResult === null) { shouldReturnNull = true; } return comparisonResult; }); } else { finalComparisonResult = false; } if (shouldReturnNull) { return null; } return finalComparisonResult; }; getKeysFromObject = function(object) { var key, objectClass; objectClass = {}.toString.call(object); return ((function() { var results; if (!isFunction(key)) { results = []; for (key in object) { results.push(key); } return results; } })()); }; isFunction = function(input) { return input instanceof Function || {}.toString.call(input) === '[object Function]'; }; module.exports.equals = equals = function(a, b) { var aClass, bClass, ref; if (!((a != null) && (b != null))) { return null; } if (a != null ? a.isQuantity : void 0) { return a.equals(b); } if (a != null ? a.isRatio : void 0) { return a.equals(b); } if (a instanceof Uncertainty) { b = Uncertainty.from(b); } else if (b instanceof Uncertainty) { a = Uncertainty.from(a); } if (typeof a.equals === 'function') { return a.equals(b); } if (typeof a === typeof b && typeof a === 'string' || typeof a === 'number' || typeof a === 'boolean') { return a === b; } ref = getClassOfObjects(a, b), aClass = ref[0], bClass = ref[1]; if (aClass !== bClass) { return false; } switch (aClass) { case '[object Date]': return a.getTime() === b.getTime(); case '[object RegExp]': return ['source', 'global', 'ignoreCase', 'multiline'].every(function(p) { return a[p] === b[p]; }); case '[object Array]': if (a.indexOf(null) >= 0 || a.indexOf(void 0) >= 0 || b.indexOf(null) >= 0 || b.indexOf(void 0) >= 0) { return null; } return compareEveryItemInArrays(a, b, equals); case '[object Object]': return compareObjects(a, b, equals); case '[object Function]': return a.toString() === b.toString(); } return false; }; }).call(this); },{"../datatypes/datetime":122,"../datatypes/uncertainty":128}],251:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Date, DateTime, Exception, MAX_DATETIME_VALUE, MAX_DATE_VALUE, MAX_FLOAT_VALUE, MAX_INT_VALUE, MAX_TIME_VALUE, MIN_DATETIME_VALUE, MIN_DATE_VALUE, MIN_FLOAT_PRECISION_VALUE, MIN_FLOAT_VALUE, MIN_INT_VALUE, MIN_TIME_VALUE, OverFlowException, Uncertainty, isValidDecimal, isValidInteger, predecessor, ref, successor, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Exception = require('../datatypes/exception').Exception; ref = require('../datatypes/datetime'), DateTime = ref.DateTime, Date = ref.Date; Uncertainty = require('../datatypes/uncertainty').Uncertainty; module.exports.MAX_INT_VALUE = MAX_INT_VALUE = Math.pow(2, 31) - 1; module.exports.MIN_INT_VALUE = MIN_INT_VALUE = Math.pow(-2, 31); module.exports.MAX_FLOAT_VALUE = MAX_FLOAT_VALUE = 99999999999999999999999999999.99999999; module.exports.MIN_FLOAT_VALUE = MIN_FLOAT_VALUE = -99999999999999999999999999999.99999999; module.exports.MIN_FLOAT_PRECISION_VALUE = MIN_FLOAT_PRECISION_VALUE = Math.pow(10, -8); module.exports.MIN_DATETIME_VALUE = MIN_DATETIME_VALUE = DateTime.parse("0001-01-01T00:00:00.000"); module.exports.MAX_DATETIME_VALUE = MAX_DATETIME_VALUE = DateTime.parse("9999-12-31T23:59:59.999"); module.exports.MIN_DATE_VALUE = MIN_DATE_VALUE = Date.parse("0001-01-01"); module.exports.MAX_DATE_VALUE = MAX_DATE_VALUE = Date.parse("9999-12-31"); module.exports.MIN_TIME_VALUE = MIN_TIME_VALUE = DateTime.parse("0000-01-01T00:00:00.000"); module.exports.MAX_TIME_VALUE = MAX_TIME_VALUE = DateTime.parse("0000-01-01T23:59:59.999"); module.exports.overflowsOrUnderflows = function(value) { if (value == null) { return false; } if (value.isQuantity) { if (!isValidDecimal(value.value)) { return true; } } else if ((value.isTime != null) && value.isTime()) { if (value.after(MAX_TIME_VALUE)) { return true; } if (value.before(MIN_TIME_VALUE)) { return true; } } else if (value.isDateTime) { if (value.after(MAX_DATETIME_VALUE)) { return true; } if (value.before(MIN_DATETIME_VALUE)) { return true; } } else if (value.isDate) { if (value.after(MAX_DATE_VALUE)) { return true; } if (value.before(MIN_DATE_VALUE)) { return true; } } else if (Number.isInteger(value)) { if (!isValidInteger(value)) { return true; } } else { if (!isValidDecimal(value)) { return true; } } return false; }; module.exports.isValidInteger = isValidInteger = function(integer) { if (isNaN(integer)) { return false; } if (integer > MAX_INT_VALUE) { return false; } if (integer < MIN_INT_VALUE) { return false; } return true; }; module.exports.isValidDecimal = isValidDecimal = function(decimal) { if (isNaN(decimal)) { return false; } if (decimal > MAX_FLOAT_VALUE) { return false; } if (decimal < MIN_FLOAT_VALUE) { return false; } return true; }; module.exports.limitDecimalPrecision = function(decimal) { var decimalPoints, decimalString, splitDecimalString; decimalString = decimal.toString(); if (decimalString.indexOf('e') !== -1) { return decimal; } splitDecimalString = decimalString.split('.'); decimalPoints = splitDecimalString[1]; if ((decimalPoints != null) && decimalPoints.length > 8) { decimalString = splitDecimalString[0] + '.' + splitDecimalString[1].substring(0, 8); } return parseFloat(decimalString); }; module.exports.OverFlowException = OverFlowException = OverFlowException = (function(superClass) { extend(OverFlowException, superClass); function OverFlowException() { return OverFlowException.__super__.constructor.apply(this, arguments); } return OverFlowException; })(Exception); module.exports.successor = successor = function(val) { var e, high, succ; if (typeof val === "number") { if (parseInt(val) === val) { if (val === MAX_INT_VALUE) { throw new OverFlowException(); } else { return val + 1; } } else { return val + MIN_FLOAT_PRECISION_VALUE; } } else if (val != null ? val.isDateTime : void 0) { if (val.sameAs(MAX_DATETIME_VALUE)) { throw new OverFlowException(); } else { return val.successor(); } } else if (val != null ? val.isDate : void 0) { if (val.sameAs(MAX_DATE_VALUE)) { throw new OverFlowException(); } else { return val.successor(); } } else if (val != null ? val.isTime : void 0) { if (val.sameAs(MAX_TIME_VALUE)) { throw new OverFlowException(); } else { return val.successor(); } } else if (val != null ? val.isUncertainty : void 0) { high = (function() { try { return successor(val.high); } catch (error) { e = error; return val.high; } })(); return new Uncertainty(successor(val.low), high); } else if (val != null ? val.isQuantity : void 0) { succ = val.clone(); succ.value = successor(val.value); return succ; } else if (val == null) { return null; } }; module.exports.predecessor = predecessor = function(val) { var e, low, pred; if (typeof val === "number") { if (parseInt(val) === val) { if (val === MIN_INT_VALUE) { throw new OverFlowException(); } else { return val - 1; } } else { return val - MIN_FLOAT_PRECISION_VALUE; } } else if (val != null ? val.isDateTime : void 0) { if (val.sameAs(MIN_DATETIME_VALUE)) { throw new OverFlowException(); } else { return val.predecessor(); } } else if (val != null ? val.isDate : void 0) { if (val.sameAs(MIN_DATE_VALUE)) { throw new OverFlowException(); } else { return val.predecessor(); } } else if (val != null ? val.isTime : void 0) { if (val.sameAs(MIN_TIME_VALUE)) { throw new OverFlowException(); } else { return val.predecessor(); } } else if (val != null ? val.isUncertainty : void 0) { low = (function() { try { return predecessor(val.low); } catch (error) { e = error; return val.low; } })(); return new Uncertainty(low, predecessor(val.high)); } else if (val != null ? val.isQuantity : void 0) { pred = val.clone(); pred.value = predecessor(val.value); return pred; } else if (val == null) { return null; } }; module.exports.maxValueForInstance = function(val) { var val2; if (typeof val === "number") { if (parseInt(val) === val) { return MAX_INT_VALUE; } else { return MAX_FLOAT_VALUE; } } else if (val != null ? val.isDateTime : void 0) { return MAX_DATETIME_VALUE.copy(); } else if (val != null ? val.isDate : void 0) { return MAX_DATE_VALUE.copy(); } else if (val != null ? val.isTime : void 0) { return MAX_TIME_VALUE.copy(); } else if (val != null ? val.isQuantity : void 0) { val2 = val.clone(); val2.value = maxValueForInstance(val2.value); return val2; } else { return null; } }; module.exports.minValueForInstance = function(val) { var val2; if (typeof val === "number") { if (parseInt(val) === val) { return MIN_INT_VALUE; } else { return MIN_FLOAT_VALUE; } } else if (val != null ? val.isDateTime : void 0) { return MIN_DATETIME_VALUE.copy(); } else if (val != null ? val.isDate : void 0) { return MIN_DATE_VALUE.copy(); } else if (val != null ? val.isTime : void 0) { return MIN_TIME_VALUE.copy(); } else if (val != null ? val.isQuantity : void 0) { val2 = val.clone(); val2.value = minValueForInstance(val2.value); return val2; } else { return null; } }; module.exports.decimalAdjust = function(type, value, exp) { var v; if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return 0/0; } value = value.toString().split('e'); v = value[1] ? +value[1] - exp : -exp; value = Math[type](+(value[0] + 'e' + v)); value = value.toString().split('e'); v = value[1] ? +value[1] + exp : exp; return +(value[0] + 'e' + v); }; }).call(this); },{"../datatypes/datetime":122,"../datatypes/exception":123,"../datatypes/uncertainty":128}],252:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var getTimezoneSeparatorFromString, normalizeMillisecondsField, normalizeMillisecondsFieldInString, typeIsArray; module.exports.removeNulls = function(things) { return things.filter(function(x) { return x != null; }); }; module.exports.numerical_sort = function(things, direction) { if (direction == null) { direction = "asc"; } return things.sort(function(a, b) { if (direction === "asc") { return a - b; } else { return b - a; } }); }; module.exports.isNull = function(value) { return value === null; }; module.exports.typeIsArray = typeIsArray = Array.isArray || function(value) { return {}.toString.call(value) === '[object Array]'; }; module.exports.allTrue = function(things) { if (typeIsArray(things)) { return things.every(function(x) { return x; }); } else { return things; } }; module.exports.anyTrue = function(things) { if (typeIsArray(things)) { return things.some(function(x) { return x; }); } else { return things; } }; module.exports.jsDate = Date; module.exports.normalizeMillisecondsFieldInString = normalizeMillisecondsFieldInString = function(string, msString) { var beforeMs, msAndAfter, ref, timezoneField, timezoneSeparator; msString = normalizeMillisecondsField(msString); ref = string.split('.'), beforeMs = ref[0], msAndAfter = ref[1]; timezoneSeparator = getTimezoneSeparatorFromString(msAndAfter); if (!!timezoneSeparator) { timezoneField = msAndAfter != null ? msAndAfter.split(timezoneSeparator)[1] : void 0; } if (timezoneField == null) { timezoneField = ''; } return string = beforeMs + '.' + msString + timezoneSeparator + timezoneField; }; module.exports.normalizeMillisecondsField = normalizeMillisecondsField = function(msString) { return msString = (msString + "00").substring(0, 3); }; module.exports.getTimezoneSeparatorFromString = getTimezoneSeparatorFromString = function(string) { var ref, ref1, timezoneSeparator; if ((string != null ? (ref = string.match(/-/)) != null ? ref.length : void 0 : void 0) === 1) { return timezoneSeparator = '-'; } else if ((string != null ? (ref1 = string.match(/\+/)) != null ? ref1.length : void 0 : void 0) === 1) { return timezoneSeparator = '+'; } else { return timezoneSeparator = ''; } }; }).call(this); },{}],253:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var objectCreate = Object.create || objectCreatePolyfill var objectKeys = Object.keys || objectKeysPolyfill var bind = Function.prototype.bind || functionBindPolyfill function EventEmitter() { if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { this._events = objectCreate(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; var hasDefineProperty; try { var o = {}; if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); hasDefineProperty = o.x === 0; } catch (err) { hasDefineProperty = false } if (hasDefineProperty) { Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { // check whether the input is a positive number (whose value is zero or // greater and not a NaN). if (typeof arg !== 'number' || arg < 0 || arg !== arg) throw new TypeError('"defaultMaxListeners" must be a positive number'); defaultMaxListeners = arg; } }); } else { EventEmitter.defaultMaxListeners = defaultMaxListeners; } // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events; var doError = (type === 'error'); events = this._events; if (events) doError = (doError && events.error == null); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { if (arguments.length > 1) er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Unhandled "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = objectCreate(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' "' + String(type) + '" listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit.'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; if (typeof console === 'object' && console.warn) { console.warn('%s: %s', w.name, w.message); } } } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; switch (arguments.length) { case 0: return this.listener.call(this.target); case 1: return this.listener.call(this.target, arguments[0]); case 2: return this.listener.call(this.target, arguments[0], arguments[1]); case 3: return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]); default: var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) args[i] = arguments[i]; this.listener.apply(this.target, args); } } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = bind.call(onceWrapper, state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = objectCreate(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else spliceOne(list, position); if (list.length === 1) events[type] = list[0]; if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = objectCreate(null); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = objectCreate(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = objectKeys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = objectCreate(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (!events) return []; var evlistener = events[type]; if (!evlistener) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); } function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function objectCreatePolyfill(proto) { var F = function() {}; F.prototype = proto; return new F; } function objectKeysPolyfill(obj) { var keys = []; for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } return k; } function functionBindPolyfill(context) { var fn = this; return function () { return fn.apply(context, arguments); }; } },{}],254:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],255:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],256:[function(require,module,exports){ (function (process){ 'use strict'; function Kareem() { this._pres = new Map(); this._posts = new Map(); } Kareem.prototype.execPre = function(name, context, args, callback) { if (arguments.length === 3) { callback = args; args = []; } var pres = get(this._pres, name, []); var numPres = pres.length; var numAsyncPres = pres.numAsync || 0; var currentPre = 0; var asyncPresLeft = numAsyncPres; var done = false; var $args = args; if (!numPres) { return process.nextTick(function() { callback(null); }); } var next = function() { if (currentPre >= numPres) { return; } var pre = pres[currentPre]; if (pre.isAsync) { var args = [ decorateNextFn(_next), decorateNextFn(function(error) { if (error) { if (done) { return; } done = true; return callback(error); } if (--asyncPresLeft === 0 && currentPre >= numPres) { return callback(null); } }) ]; callMiddlewareFunction(pre.fn, context, args, args[0]); } else if (pre.fn.length > 0) { var args = [decorateNextFn(_next)]; var _args = arguments.length >= 2 ? arguments : [null].concat($args); for (var i = 1; i < _args.length; ++i) { args.push(_args[i]); } callMiddlewareFunction(pre.fn, context, args, args[0]); } else { let maybePromise = null; try { maybePromise = pre.fn.call(context); } catch (err) { if (err != null) { return callback(err); } } if (isPromise(maybePromise)) { maybePromise.then(() => _next(), err => _next(err)); } else { if (++currentPre >= numPres) { if (asyncPresLeft > 0) { // Leave parallel hooks to run return; } else { return process.nextTick(function() { callback(null); }); } } next(); } } }; next.apply(null, [null].concat(args)); function _next(error) { if (error) { if (done) { return; } done = true; return callback(error); } if (++currentPre >= numPres) { if (asyncPresLeft > 0) { // Leave parallel hooks to run return; } else { return callback(null); } } next.apply(context, arguments); } }; Kareem.prototype.execPreSync = function(name, context, args) { var pres = get(this._pres, name, []); var numPres = pres.length; for (var i = 0; i < numPres; ++i) { pres[i].fn.apply(context, args || []); } }; Kareem.prototype.execPost = function(name, context, args, options, callback) { if (arguments.length < 5) { callback = options; options = null; } var posts = get(this._posts, name, []); var numPosts = posts.length; var currentPost = 0; var firstError = null; if (options && options.error) { firstError = options.error; } if (!numPosts) { return process.nextTick(function() { callback.apply(null, [firstError].concat(args)); }); } var next = function() { var post = posts[currentPost].fn; var numArgs = 0; var argLength = args.length; var newArgs = []; for (var i = 0; i < argLength; ++i) { numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; if (!args[i] || !args[i]._kareemIgnore) { newArgs.push(args[i]); } } if (firstError) { if (post.length === numArgs + 2) { var _cb = decorateNextFn(function(error) { if (error) { firstError = error; } if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); }); callMiddlewareFunction(post, context, [firstError].concat(newArgs).concat([_cb]), _cb); } else { if (++currentPost >= numPosts) { return callback.call(null, firstError); } next(); } } else { const _cb = decorateNextFn(function(error) { if (error) { firstError = error; return next(); } if (++currentPost >= numPosts) { return callback.apply(null, [null].concat(args)); } next(); }); if (post.length === numArgs + 2) { // Skip error handlers if no error if (++currentPost >= numPosts) { return callback.apply(null, [null].concat(args)); } return next(); } if (post.length === numArgs + 1) { callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb); } else { let error; let maybePromise; try { maybePromise = post.apply(context, newArgs); } catch (err) { error = err; firstError = err; } if (isPromise(maybePromise)) { return maybePromise.then(() => _cb(), err => _cb(err)); } if (++currentPost >= numPosts) { return callback.apply(null, [error].concat(args)); } next(error); } } }; next(); }; Kareem.prototype.execPostSync = function(name, context, args) { const posts = get(this._posts, name, []); const numPosts = posts.length; for (let i = 0; i < numPosts; ++i) { posts[i].fn.apply(context, args || []); } }; Kareem.prototype.createWrapperSync = function(name, fn) { var kareem = this; return function syncWrapper() { kareem.execPreSync(name, this, arguments); var toReturn = fn.apply(this, arguments); kareem.execPostSync(name, this, [toReturn]); return toReturn; }; } function _handleWrapError(instance, error, name, context, args, options, callback) { if (options.useErrorHandlers) { var _options = { error: error }; return instance.execPost(name, context, args, _options, function(error) { return typeof callback === 'function' && callback(error); }); } else { return typeof callback === 'function' ? callback(error) : undefined; } } Kareem.prototype.wrap = function(name, fn, context, args, options) { const lastArg = (args.length > 0 ? args[args.length - 1] : null); const argsWithoutCb = typeof lastArg === 'function' ? args.slice(0, args.length - 1) : args; const _this = this; options = options || {}; const checkForPromise = options.checkForPromise; this.execPre(name, context, args, function(error) { if (error) { const numCallbackParams = options.numCallbackParams || 0; const errorArgs = options.contextParameter ? [context] : []; for (var i = errorArgs.length; i < numCallbackParams; ++i) { errorArgs.push(null); } return _handleWrapError(_this, error, name, context, errorArgs, options, lastArg); } const end = (typeof lastArg === 'function' ? args.length - 1 : args.length); const numParameters = fn.length; const ret = fn.apply(context, args.slice(0, end).concat(_cb)); if (checkForPromise) { if (ret != null && typeof ret.then === 'function') { // Thenable, use it return ret.then( res => _cb(null, res), err => _cb(err) ); } // If `fn()` doesn't have a callback argument and doesn't return a // promise, assume it is sync if (numParameters < end + 1) { return _cb(null, ret); } } function _cb() { const args = arguments; const argsWithoutError = Array.prototype.slice.call(arguments, 1); if (options.nullResultByDefault && argsWithoutError.length === 0) { argsWithoutError.push(null); } if (arguments[0]) { // Assume error return _handleWrapError(_this, arguments[0], name, context, argsWithoutError, options, lastArg); } else { _this.execPost(name, context, argsWithoutError, function() { if (arguments[0]) { return typeof lastArg === 'function' ? lastArg(arguments[0]) : undefined; } return typeof lastArg === 'function' ? lastArg.apply(context, arguments) : undefined; }); } } }); }; Kareem.prototype.filter = function(fn) { const clone = this.clone(); const pres = Array.from(clone._pres.keys()); for (const name of pres) { const hooks = this._pres.get(name). map(h => Object.assign({}, h, { name: name })). filter(fn); if (hooks.length === 0) { clone._pres.delete(name); continue; } hooks.numAsync = hooks.filter(h => h.isAsync).length; clone._pres.set(name, hooks); } const posts = Array.from(clone._posts.keys()); for (const name of posts) { const hooks = this._posts.get(name). map(h => Object.assign({}, h, { name: name })). filter(fn); if (hooks.length === 0) { clone._posts.delete(name); continue; } clone._posts.set(name, hooks); } return clone; }; Kareem.prototype.hasHooks = function(name) { return this._pres.has(name) || this._posts.has(name); }; Kareem.prototype.createWrapper = function(name, fn, context, options) { var _this = this; if (!this.hasHooks(name)) { // Fast path: if there's no hooks for this function, just return the // function wrapped in a nextTick() return function() { process.nextTick(() => fn.apply(this, arguments)); }; } return function() { var _context = context || this; var args = Array.prototype.slice.call(arguments); _this.wrap(name, fn, _context, args, options); }; }; Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) { let options = {}; if (typeof isAsync === 'object' && isAsync != null) { options = isAsync; isAsync = options.isAsync; } else if (typeof arguments[1] !== 'boolean') { error = fn; fn = isAsync; isAsync = false; } const pres = get(this._pres, name, []); this._pres.set(name, pres); if (isAsync) { pres.numAsync = pres.numAsync || 0; ++pres.numAsync; } if (typeof fn !== 'function') { throw new Error('pre() requires a function, got "' + typeof fn + '"'); } if (unshift) { pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync })); } else { pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync })); } return this; }; Kareem.prototype.post = function(name, options, fn, unshift) { const hooks = get(this._posts, name, []); if (typeof options === 'function') { unshift = !!fn; fn = options; options = {}; } if (typeof fn !== 'function') { throw new Error('post() requires a function, got "' + typeof fn + '"'); } if (unshift) { hooks.unshift(Object.assign({}, options, { fn: fn })); } else { hooks.push(Object.assign({}, options, { fn: fn })); } this._posts.set(name, hooks); return this; }; Kareem.prototype.clone = function() { const n = new Kareem(); for (let key of this._pres.keys()) { const clone = this._pres.get(key).slice(); clone.numAsync = this._pres.get(key).numAsync; n._pres.set(key, clone); } for (let key of this._posts.keys()) { n._posts.set(key, this._posts.get(key).slice()); } return n; }; Kareem.prototype.merge = function(other, clone) { clone = arguments.length === 1 ? true : clone; var ret = clone ? this.clone() : this; for (let key of other._pres.keys()) { const sourcePres = get(ret._pres, key, []); const deduplicated = other._pres.get(key). // Deduplicate based on `fn` filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1); const combined = sourcePres.concat(deduplicated); combined.numAsync = sourcePres.numAsync || 0; combined.numAsync += deduplicated.filter(p => p.isAsync).length; ret._pres.set(key, combined); } for (let key of other._posts.keys()) { const sourcePosts = get(ret._posts, key, []); const deduplicated = other._posts.get(key). filter(p => sourcePosts.indexOf(p) === -1); ret._posts.set(key, sourcePosts.concat(deduplicated)); } return ret; }; function get(map, key, def) { if (map.has(key)) { return map.get(key); } return def; } function callMiddlewareFunction(fn, context, args, next) { let maybePromise; try { maybePromise = fn.apply(context, args); } catch (error) { return next(error); } if (isPromise(maybePromise)) { maybePromise.then(() => next(), err => next(err)); } } function isPromise(v) { return v != null && typeof v.then === 'function'; } function decorateNextFn(fn) { var called = false; var _this = this; return function() { // Ensure this function can only be called once if (called) { return; } called = true; // Make sure to clear the stack so try/catch doesn't catch errors // in subsequent middleware return process.nextTick(() => fn.apply(_this, arguments)); }; } module.exports = Kareem; }).call(this,require('_process')) },{"_process":399}],257:[function(require,module,exports){ //! moment.js //! version : 2.27.0 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.moment = factory() }(this, (function () { 'use strict'; var hookCallback; function hooks() { return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback(callback) { hookCallback = callback; } function isArray(input) { return ( input instanceof Array || Object.prototype.toString.call(input) === '[object Array]' ); } function isObject(input) { // IE8 will treat undefined and null as object if it wasn't for // input != null return ( input != null && Object.prototype.toString.call(input) === '[object Object]' ); } function hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } function isObjectEmpty(obj) { if (Object.getOwnPropertyNames) { return Object.getOwnPropertyNames(obj).length === 0; } else { var k; for (k in obj) { if (hasOwnProp(obj, k)) { return false; } } return true; } } function isUndefined(input) { return input === void 0; } function isNumber(input) { return ( typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]' ); } function isDate(input) { return ( input instanceof Date || Object.prototype.toString.call(input) === '[object Date]' ); } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function createUTC(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, true).utc(); } function defaultParsingFlags() { // We need to deep clone this object. return { empty: false, unusedTokens: [], unusedInput: [], overflow: -2, charsLeftOver: 0, nullInput: false, invalidEra: null, invalidMonth: null, invalidFormat: false, userInvalidated: false, iso: false, parsedDateParts: [], era: null, meridiem: null, rfc2822: false, weekdayMismatch: false, }; } function getParsingFlags(m) { if (m._pf == null) { m._pf = defaultParsingFlags(); } return m._pf; } var some; if (Array.prototype.some) { some = Array.prototype.some; } else { some = function (fun) { var t = Object(this), len = t.length >>> 0, i; for (i = 0; i < len; i++) { if (i in t && fun.call(this, t[i], i, t)) { return true; } } return false; }; } function isValid(m) { if (m._isValid == null) { var flags = getParsingFlags(m), parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }), isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || (flags.meridiem && parsedParts)); if (m._strict) { isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined; } if (Object.isFrozen == null || !Object.isFrozen(m)) { m._isValid = isNowValid; } else { return isNowValid; } } return m._isValid; } function createInvalid(flags) { var m = createUTC(NaN); if (flags != null) { extend(getParsingFlags(m), flags); } else { getParsingFlags(m).userInvalidated = true; } return m; } // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. var momentProperties = (hooks.momentProperties = []), updateInProgress = false; function copyConfig(to, from) { var i, prop, val; if (!isUndefined(from._isAMomentObject)) { to._isAMomentObject = from._isAMomentObject; } if (!isUndefined(from._i)) { to._i = from._i; } if (!isUndefined(from._f)) { to._f = from._f; } if (!isUndefined(from._l)) { to._l = from._l; } if (!isUndefined(from._strict)) { to._strict = from._strict; } if (!isUndefined(from._tzm)) { to._tzm = from._tzm; } if (!isUndefined(from._isUTC)) { to._isUTC = from._isUTC; } if (!isUndefined(from._offset)) { to._offset = from._offset; } if (!isUndefined(from._pf)) { to._pf = getParsingFlags(from); } if (!isUndefined(from._locale)) { to._locale = from._locale; } if (momentProperties.length > 0) { for (i = 0; i < momentProperties.length; i++) { prop = momentProperties[i]; val = from[prop]; if (!isUndefined(val)) { to[prop] = val; } } } return to; } // Moment prototype object function Moment(config) { copyConfig(this, config); this._d = new Date(config._d != null ? config._d.getTime() : NaN); if (!this.isValid()) { this._d = new Date(NaN); } // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; hooks.updateOffset(this); updateInProgress = false; } } function isMoment(obj) { return ( obj instanceof Moment || (obj != null && obj._isAMomentObject != null) ); } function warn(msg) { if ( hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn ) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(null, msg); } if (firstTime) { var args = [], arg, i, key; for (i = 0; i < arguments.length; i++) { arg = ''; if (typeof arguments[i] === 'object') { arg += '\n[' + i + '] '; for (key in arguments[0]) { if (hasOwnProp(arguments[0], key)) { arg += key + ': ' + arguments[0][key] + ', '; } } arg = arg.slice(0, -2); // Remove trailing comma and space } else { arg = arguments[i]; } args.push(arg); } warn( msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + new Error().stack ); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } hooks.suppressDeprecationWarnings = false; hooks.deprecationHandler = null; function isFunction(input) { return ( (typeof Function !== 'undefined' && input instanceof Function) || Object.prototype.toString.call(input) === '[object Function]' ); } function set(config) { var prop, i; for (i in config) { if (hasOwnProp(config, i)) { prop = config[i]; if (isFunction(prop)) { this[i] = prop; } else { this['_' + i] = prop; } } } this._config = config; // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. // TODO: Remove "ordinalParse" fallback in next major release. this._dayOfMonthOrdinalParseLenient = new RegExp( (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source ); } function mergeConfigs(parentConfig, childConfig) { var res = extend({}, parentConfig), prop; for (prop in childConfig) { if (hasOwnProp(childConfig, prop)) { if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { res[prop] = {}; extend(res[prop], parentConfig[prop]); extend(res[prop], childConfig[prop]); } else if (childConfig[prop] != null) { res[prop] = childConfig[prop]; } else { delete res[prop]; } } } for (prop in parentConfig) { if ( hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop]) ) { // make sure changes to properties don't modify parent config res[prop] = extend({}, res[prop]); } } return res; } function Locale(config) { if (config != null) { this.set(config); } } var keys; if (Object.keys) { keys = Object.keys; } else { keys = function (obj) { var i, res = []; for (i in obj) { if (hasOwnProp(obj, i)) { res.push(i); } } return res; }; } var defaultCalendar = { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L', }; function calendar(key, mom, now) { var output = this._calendar[key] || this._calendar['sameElse']; return isFunction(output) ? output.call(mom, now) : output; } function zeroFill(number, targetLength, forceSign) { var absNumber = '' + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign = number >= 0; return ( (sign ? (forceSign ? '+' : '') : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber ); } var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken(token, padded, ordinal, callback) { var func = callback; if (typeof callback === 'string') { func = function () { return this[callback](); }; } if (token) { formatTokenFunctions[token] = func; } if (padded) { formatTokenFunctions[padded[0]] = function () { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal) { formatTokenFunctions[ordinal] = function () { return this.localeData().ordinal( func.apply(this, arguments), token ); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = '', i; for (i = 0; i < length; i++) { output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace( localFormattingTokens, replaceLongDateFormatTokens ); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } var defaultLongDateFormat = { LTS: 'h:mm:ss A', LT: 'h:mm A', L: 'MM/DD/YYYY', LL: 'MMMM D, YYYY', LLL: 'MMMM D, YYYY h:mm A', LLLL: 'dddd, MMMM D, YYYY h:mm A', }; function longDateFormat(key) { var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; if (format || !formatUpper) { return format; } this._longDateFormat[key] = formatUpper .match(formattingTokens) .map(function (tok) { if ( tok === 'MMMM' || tok === 'MM' || tok === 'DD' || tok === 'dddd' ) { return tok.slice(1); } return tok; }) .join(''); return this._longDateFormat[key]; } var defaultInvalidDate = 'Invalid date'; function invalidDate() { return this._invalidDate; } var defaultOrdinal = '%d', defaultDayOfMonthOrdinalParse = /\d{1,2}/; function ordinal(number) { return this._ordinal.replace('%d', number); } var defaultRelativeTime = { future: 'in %s', past: '%s ago', s: 'a few seconds', ss: '%d seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', w: 'a week', ww: '%d weeks', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years', }; function relativeTime(number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); } function pastFuture(diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return isFunction(format) ? format(output) : format.replace(/%s/i, output); } var aliases = {}; function addUnitAlias(unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { var units = [], u; for (u in unitsObj) { if (hasOwnProp(unitsObj, u)) { units.push({ unit: u, priority: priorities[u] }); } } units.sort(function (a, b) { return a.priority - b.priority; }); return units; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function absFloor(number) { if (number < 0) { // -0 -> 0 return Math.ceil(number) || 0; } else { return Math.floor(number); } } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { value = absFloor(coercedNumber); } return value; } function makeGetSet(unit, keepTime) { return function (value) { if (value != null) { set$1(this, unit, value); hooks.updateOffset(this, keepTime); return this; } else { return get(this, unit); } }; } function get(mom, unit) { return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; } function set$1(mom, unit, value) { if (mom.isValid() && !isNaN(value)) { if ( unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29 ) { value = toInt(value); mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit]( value, mom.month(), daysInMonth(value, mom.month()) ); } else { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } } // MOMENTS function stringGet(units) { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](); } return this; } function stringSet(units, value) { if (typeof units === 'object') { units = normalizeObjectUnits(units); var prioritized = getPrioritizedUnits(units), i; for (i = 0; i < prioritized.length; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](value); } } return this; } var match1 = /\d/, // 0 - 9 match2 = /\d\d/, // 00 - 99 match3 = /\d{3}/, // 000 - 999 match4 = /\d{4}/, // 0000 - 9999 match6 = /[+-]?\d{6}/, // -999999 - 999999 match1to2 = /\d\d?/, // 0 - 99 match3to4 = /\d\d\d\d?/, // 999 - 9999 match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999 match1to3 = /\d{1,3}/, // 0 - 999 match1to4 = /\d{1,4}/, // 0 - 9999 match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999 matchUnsigned = /\d+/, // 0 - inf matchSigned = /[+-]?\d+/, // -inf - inf matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 // any word (or two) characters or numbers including two/three word month in arabic. // includes scottish gaelic two word and hyphenated months matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, regexes; regexes = {}; function addRegexToken(token, regex, strictRegex) { regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { return isStrict && strictRegex ? strictRegex : regex; }; } function getParseRegexForToken(token, config) { if (!hasOwnProp(regexes, token)) { return new RegExp(unescapeFormat(token)); } return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { return regexEscape( s .replace('\\', '') .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function ( matched, p1, p2, p3, p4 ) { return p1 || p2 || p3 || p4; }) ); } function regexEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var tokens = {}; function addParseToken(token, callback) { var i, func = callback; if (typeof token === 'string') { token = [token]; } if (isNumber(callback)) { func = function (input, array) { array[callback] = toInt(input); }; } for (i = 0; i < token.length; i++) { tokens[token[i]] = func; } } function addWeekParseToken(token, callback) { addParseToken(token, function (input, array, config, token) { config._w = config._w || {}; callback(input, config._w, config, token); }); } function addTimeToArrayFromToken(token, input, config) { if (input != null && hasOwnProp(tokens, token)) { tokens[token](input, config._a, config, token); } } var YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8; function mod(n, x) { return ((n % x) + x) % x; } var indexOf; if (Array.prototype.indexOf) { indexOf = Array.prototype.indexOf; } else { indexOf = function (o) { // I know var i; for (i = 0; i < this.length; ++i) { if (this[i] === o) { return i; } } return -1; }; } function daysInMonth(year, month) { if (isNaN(year) || isNaN(month)) { return NaN; } var modMonth = mod(month, 12); year += (month - modMonth) / 12; return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - ((modMonth % 7) % 2); } // FORMATTING addFormatToken('M', ['MM', 2], 'Mo', function () { return this.month() + 1; }); addFormatToken('MMM', 0, 0, function (format) { return this.localeData().monthsShort(this, format); }); addFormatToken('MMMM', 0, 0, function (format) { return this.localeData().months(this, format); }); // ALIASES addUnitAlias('month', 'M'); // PRIORITY addUnitPriority('month', 8); // PARSING addRegexToken('M', match1to2); addRegexToken('MM', match1to2, match2); addRegexToken('MMM', function (isStrict, locale) { return locale.monthsShortRegex(isStrict); }); addRegexToken('MMMM', function (isStrict, locale) { return locale.monthsRegex(isStrict); }); addParseToken(['M', 'MM'], function (input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (month != null) { array[MONTH] = month; } else { getParsingFlags(config).invalidMonth = input; } }); // LOCALES var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split( '_' ), defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split( '_' ), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, defaultMonthsShortRegex = matchWord, defaultMonthsRegex = matchWord; function localeMonths(m, format) { if (!m) { return isArray(this._months) ? this._months : this._months['standalone']; } return isArray(this._months) ? this._months[m.month()] : this._months[ (this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone' ][m.month()]; } function localeMonthsShort(m, format) { if (!m) { return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone']; } return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[ MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone' ][m.month()]; } function handleStrictParse(monthName, format, strict) { var i, ii, mom, llc = monthName.toLocaleLowerCase(); if (!this._monthsParse) { // this is not used this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; for (i = 0; i < 12; ++i) { mom = createUTC([2000, i]); this._shortMonthsParse[i] = this.monthsShort( mom, '' ).toLocaleLowerCase(); this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } } } function localeMonthsParse(monthName, format, strict) { var i, mom, regex; if (this._monthsParseExact) { return handleStrictParse.call(this, monthName, format, strict); } if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } // TODO: add sorting // Sorting makes sure if one month (or abbr) is a prefix of another // see sorting in computeMonthsParse for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp( '^' + this.months(mom, '').replace('.', '') + '$', 'i' ); this._shortMonthsParse[i] = new RegExp( '^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i' ); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if ( strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName) ) { return i; } else if ( strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName) ) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } // MOMENTS function setMonth(mom, value) { var dayOfMonth; if (!mom.isValid()) { // No op return mom; } if (typeof value === 'string') { if (/^\d+$/.test(value)) { value = toInt(value); } else { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (!isNumber(value)) { return mom; } } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function getSetMonth(value) { if (value != null) { setMonth(this, value); hooks.updateOffset(this, true); return this; } else { return get(this, 'Month'); } } function getDaysInMonth() { return daysInMonth(this.year(), this.month()); } function monthsShortRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsShortStrictRegex; } else { return this._monthsShortRegex; } } else { if (!hasOwnProp(this, '_monthsShortRegex')) { this._monthsShortRegex = defaultMonthsShortRegex; } return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } } function monthsRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsStrictRegex; } else { return this._monthsRegex; } } else { if (!hasOwnProp(this, '_monthsRegex')) { this._monthsRegex = defaultMonthsRegex; } return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } } function computeMonthsParse() { function cmpLenRev(a, b) { return b.length - a.length; } var shortPieces = [], longPieces = [], mixedPieces = [], i, mom; for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); shortPieces.push(this.monthsShort(mom, '')); longPieces.push(this.months(mom, '')); mixedPieces.push(this.months(mom, '')); mixedPieces.push(this.monthsShort(mom, '')); } // Sorting makes sure if one month (or abbr) is a prefix of another it // will match the longer piece. shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 12; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); } for (i = 0; i < 24; i++) { mixedPieces[i] = regexEscape(mixedPieces[i]); } this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._monthsShortRegex = this._monthsRegex; this._monthsStrictRegex = new RegExp( '^(' + longPieces.join('|') + ')', 'i' ); this._monthsShortStrictRegex = new RegExp( '^(' + shortPieces.join('|') + ')', 'i' ); } // FORMATTING addFormatToken('Y', 0, 0, function () { var y = this.year(); return y <= 9999 ? zeroFill(y, 4) : '+' + y; }); addFormatToken(0, ['YY', 2], 0, function () { return this.year() % 100; }); addFormatToken(0, ['YYYY', 4], 0, 'year'); addFormatToken(0, ['YYYYY', 5], 0, 'year'); addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES addUnitAlias('year', 'y'); // PRIORITIES addUnitPriority('year', 1); // PARSING addRegexToken('Y', matchSigned); addRegexToken('YY', match1to2, match2); addRegexToken('YYYY', match1to4, match4); addRegexToken('YYYYY', match1to6, match6); addRegexToken('YYYYYY', match1to6, match6); addParseToken(['YYYYY', 'YYYYYY'], YEAR); addParseToken('YYYY', function (input, array) { array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); }); addParseToken('YY', function (input, array) { array[YEAR] = hooks.parseTwoDigitYear(input); }); addParseToken('Y', function (input, array) { array[YEAR] = parseInt(input, 10); }); // HELPERS function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } // HOOKS hooks.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS var getSetYear = makeGetSet('FullYear', true); function getIsLeapYear() { return isLeapYear(this.year()); } function createDate(y, m, d, h, M, s, ms) { // can't just apply() to create a date: // https://stackoverflow.com/q/181348 var date; // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset date = new Date(y + 400, m, d, h, M, s, ms); if (isFinite(date.getFullYear())) { date.setFullYear(y); } } else { date = new Date(y, m, d, h, M, s, ms); } return date; } function createUTCDate(y) { var date, args; // the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { args = Array.prototype.slice.call(arguments); // preserve leap years using a full 400 year cycle, then reset args[0] = y + 400; date = new Date(Date.UTC.apply(null, args)); if (isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } } else { date = new Date(Date.UTC.apply(null, arguments)); } return date; } // start-of-first-week - start-of-year function firstWeekOffset(year, dow, doy) { var // first-week day -- which january is always in the first week (4 for iso, 1 for other) fwd = 7 + dow - doy, // first-week day local weekday -- which local weekday is fwd fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; return -fwdlw + fwd - 1; } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, dow, doy) { var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; if (dayOfYear <= 0) { resYear = year - 1; resDayOfYear = daysInYear(resYear) + dayOfYear; } else if (dayOfYear > daysInYear(year)) { resYear = year + 1; resDayOfYear = dayOfYear - daysInYear(year); } else { resYear = year; resDayOfYear = dayOfYear; } return { year: resYear, dayOfYear: resDayOfYear, }; } function weekOfYear(mom, dow, doy) { var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; if (week < 1) { resYear = mom.year() - 1; resWeek = week + weeksInYear(resYear, dow, doy); } else if (week > weeksInYear(mom.year(), dow, doy)) { resWeek = week - weeksInYear(mom.year(), dow, doy); resYear = mom.year() + 1; } else { resYear = mom.year(); resWeek = week; } return { week: resWeek, year: resYear, }; } function weeksInYear(year, dow, doy) { var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } // FORMATTING addFormatToken('w', ['ww', 2], 'wo', 'week'); addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES addUnitAlias('week', 'w'); addUnitAlias('isoWeek', 'W'); // PRIORITIES addUnitPriority('week', 5); addUnitPriority('isoWeek', 5); // PARSING addRegexToken('w', match1to2); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2); addRegexToken('WW', match1to2, match2); addWeekParseToken(['w', 'ww', 'W', 'WW'], function ( input, week, config, token ) { week[token.substr(0, 1)] = toInt(input); }); // HELPERS // LOCALES function localeWeek(mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow: 0, // Sunday is the first day of the week. doy: 6, // The week that contains Jan 6th is the first week of the year. }; function localeFirstDayOfWeek() { return this._week.dow; } function localeFirstDayOfYear() { return this._week.doy; } // MOMENTS function getSetWeek(input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); } function getSetISOWeek(input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); } // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES function shiftWeekdays(ws, n) { return ws.slice(n, 7).concat(ws.slice(0, n)); } var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( '_' ), defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), defaultWeekdaysRegex = matchWord, defaultWeekdaysShortRegex = matchWord, defaultWeekdaysMinRegex = matchWord; function localeWeekdays(m, format) { var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[ m && m !== true && this._weekdays.isFormat.test(format) ? 'format' : 'standalone' ]; return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays; } function localeWeekdaysShort(m) { return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort; } function localeWeekdaysMin(m) { return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin; } function handleStrictParse$1(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin( mom, '' ).toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort( mom, '' ).toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } function localeWeekdaysParse(weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return handleStrictParse$1.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp( '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i' ); this._shortWeekdaysParse[i] = new RegExp( '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i' ); this._minWeekdaysParse[i] = new RegExp( '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i' ); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if ( strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName) ) { return i; } else if ( strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName) ) { return i; } else if ( strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName) ) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS function getSetDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } function getSetLocaleDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } function getSetISODayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } function weekdaysRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } function weekdaysShortRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } function weekdaysMinRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse() { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); minp = regexEscape(this.weekdaysMin(mom, '')); shortp = regexEscape(this.weekdaysShort(mom, '')); longp = regexEscape(this.weekdays(mom, '')); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp( '^(' + longPieces.join('|') + ')', 'i' ); this._weekdaysShortStrictRegex = new RegExp( '^(' + shortPieces.join('|') + ')', 'i' ); this._weekdaysMinStrictRegex = new RegExp( '^(' + minPieces.join('|') + ')', 'i' ); } // FORMATTING function hFormat() { return this.hours() % 12 || 12; } function kFormat() { return this.hours() || 24; } addFormatToken('H', ['HH', 2], 0, 'hour'); addFormatToken('h', ['hh', 2], 0, hFormat); addFormatToken('k', ['kk', 2], 0, kFormat); addFormatToken('hmm', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); addFormatToken('hmmss', 0, 0, function () { return ( '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2) ); }); addFormatToken('Hmm', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2); }); addFormatToken('Hmmss', 0, 0, function () { return ( '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2) ); }); function meridiem(token, lowercase) { addFormatToken(token, 0, 0, function () { return this.localeData().meridiem( this.hours(), this.minutes(), lowercase ); }); } meridiem('a', true); meridiem('A', false); // ALIASES addUnitAlias('hour', 'h'); // PRIORITY addUnitPriority('hour', 13); // PARSING function matchMeridiem(isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2); addRegexToken('h', match1to2); addRegexToken('k', match1to2); addRegexToken('HH', match1to2, match2); addRegexToken('hh', match1to2, match2); addRegexToken('kk', match1to2, match2); addRegexToken('hmm', match3to4); addRegexToken('hmmss', match5to6); addRegexToken('Hmm', match3to4); addRegexToken('Hmmss', match5to6); addParseToken(['H', 'HH'], HOUR); addParseToken(['k', 'kk'], function (input, array, config) { var kInput = toInt(input); array[HOUR] = kInput === 24 ? 0 : kInput; }); addParseToken(['a', 'A'], function (input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(['h', 'hh'], function (input, array, config) { array[HOUR] = toInt(input); getParsingFlags(config).bigHour = true; }); addParseToken('hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); getParsingFlags(config).bigHour = true; }); addParseToken('hmmss', function (input, array, config) { var pos1 = input.length - 4, pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); getParsingFlags(config).bigHour = true; }); addParseToken('Hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); }); addParseToken('Hmmss', function (input, array, config) { var pos1 = input.length - 4, pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); }); // LOCALES function localeIsPM(input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return (input + '').toLowerCase().charAt(0) === 'p'; } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, // Setting the hour should keep the time, because the user explicitly // specified which hour they want. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. getSetHour = makeGetSet('Hours', true); function localeMeridiem(hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } var baseConfig = { calendar: defaultCalendar, longDateFormat: defaultLongDateFormat, invalidDate: defaultInvalidDate, ordinal: defaultOrdinal, dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, relativeTime: defaultRelativeTime, months: defaultLocaleMonths, monthsShort: defaultLocaleMonthsShort, week: defaultLocaleWeek, weekdays: defaultLocaleWeekdays, weekdaysMin: defaultLocaleWeekdaysMin, weekdaysShort: defaultLocaleWeekdaysShort, meridiemParse: defaultLocaleMeridiemParse, }; // internal storage for locale config files var locales = {}, localeFamilies = {}, globalLocale; function commonPrefix(arr1, arr2) { var i, minl = Math.min(arr1.length, arr2.length); for (i = 0; i < minl; i += 1) { if (arr1[i] !== arr2[i]) { return i; } } return minl; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if ( next && next.length >= j && commonPrefix(split, next) >= j - 1 ) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return globalLocale; } function loadLocale(name) { var oldLocale = null, aliasedRequire; // TODO: Find a better way to register and load all the locales in Node if ( locales[name] === undefined && typeof module !== 'undefined' && module && module.exports ) { try { oldLocale = globalLocale._abbr; aliasedRequire = require; aliasedRequire('./locale/' + name); getSetGlobalLocale(oldLocale); } catch (e) { // mark as not found to avoid repeating expensive file require call causing high CPU // when trying to find en-US, en_US, en-us for every format call locales[name] = null; // null means not found } } return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function getSetGlobalLocale(key, values) { var data; if (key) { if (isUndefined(values)) { data = getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } else { if (typeof console !== 'undefined' && console.warn) { //warn user if arguments are passed but the locale could not be set console.warn( 'Locale ' + key + ' not found. Did you forget to load it?' ); } } } return globalLocale._abbr; } function defineLocale(name, config) { if (config !== null) { var locale, parentConfig = baseConfig; config.abbr = name; if (locales[name] != null) { deprecateSimple( 'defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.' ); parentConfig = locales[name]._config; } else if (config.parentLocale != null) { if (locales[config.parentLocale] != null) { parentConfig = locales[config.parentLocale]._config; } else { locale = loadLocale(config.parentLocale); if (locale != null) { parentConfig = locale._config; } else { if (!localeFamilies[config.parentLocale]) { localeFamilies[config.parentLocale] = []; } localeFamilies[config.parentLocale].push({ name: name, config: config, }); return null; } } } locales[name] = new Locale(mergeConfigs(parentConfig, config)); if (localeFamilies[name]) { localeFamilies[name].forEach(function (x) { defineLocale(x.name, x.config); }); } // backwards compat for now: also set the locale // make sure we set the locale AFTER all child locales have been // created, so we won't end up with the child locale set. getSetGlobalLocale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } } function updateLocale(name, config) { if (config != null) { var locale, tmpLocale, parentConfig = baseConfig; if (locales[name] != null && locales[name].parentLocale != null) { // Update existing child locale in-place to avoid memory-leaks locales[name].set(mergeConfigs(locales[name]._config, config)); } else { // MERGE tmpLocale = loadLocale(name); if (tmpLocale != null) { parentConfig = tmpLocale._config; } config = mergeConfigs(parentConfig, config); if (tmpLocale == null) { // updateLocale is called for creating a new locale // Set abbr so it will have a name (getters return // undefined otherwise). config.abbr = name; } locale = new Locale(config); locale.parentLocale = locales[name]; locales[name] = locale; } // backwards compat for now: also set the locale getSetGlobalLocale(name); } else { // pass null for config to unupdate, useful for tests if (locales[name] != null) { if (locales[name].parentLocale != null) { locales[name] = locales[name].parentLocale; if (name === getSetGlobalLocale()) { getSetGlobalLocale(name); } } else if (locales[name] != null) { delete locales[name]; } } } return locales[name]; } // returns locale data function getLocale(key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); } function listLocales() { return keys(locales); } function checkOverflow(m) { var overflow, a = m._a; if (a && getParsingFlags(m).overflow === -2) { overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; if ( getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE) ) { overflow = DATE; } if (getParsingFlags(m)._overflowWeeks && overflow === -1) { overflow = WEEK; } if (getParsingFlags(m)._overflowWeekday && overflow === -1) { overflow = WEEKDAY; } getParsingFlags(m).overflow = overflow; } return m; } // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/], ['YYYYMM', /\d{6}/, false], ['YYYY', /\d{4}/, false], ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/], ], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = { UT: 0, GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60, }; // date from iso format function configFromISO(config) { var i, l, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(match[1])) { dateFormat = isoDates[i][0]; allowTime = isoDates[i][2] !== false; break; } } if (dateFormat == null) { config._isValid = false; return; } if (match[3]) { for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(match[3])) { // match[2] should be 'T' or space timeFormat = (match[2] || ' ') + isoTimes[i][0]; break; } } if (timeFormat == null) { config._isValid = false; return; } } if (!allowTime && timeFormat != null) { config._isValid = false; return; } if (match[4]) { if (tzRegex.exec(match[4])) { tzFormat = 'Z'; } else { config._isValid = false; return; } } config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); configFromStringAndFormat(config); } else { config._isValid = false; } } function extractFromRFC2822Strings( yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr ) { var result = [ untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10), ]; if (secondStr) { result.push(parseInt(secondStr, 10)); } return result; } function untruncateYear(yearStr) { var year = parseInt(yearStr, 10); if (year <= 49) { return 2000 + year; } else if (year <= 999) { return 1900 + year; } return year; } function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s .replace(/\([^)]*\)|[\n\t]/g, ' ') .replace(/(\s\s+)/g, ' ') .replace(/^\s\s*/, '') .replace(/\s\s*$/, ''); } function checkWeekday(weekdayStr, parsedInput, config) { if (weekdayStr) { // TODO: Replace the vanilla JS Date object with an independent day-of-week check. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date( parsedInput[0], parsedInput[1], parsedInput[2] ).getDay(); if (weekdayProvided !== weekdayActual) { getParsingFlags(config).weekdayMismatch = true; config._isValid = false; return false; } } return true; } function calculateOffset(obsOffset, militaryOffset, numOffset) { if (obsOffset) { return obsOffsets[obsOffset]; } else if (militaryOffset) { // the only allowed military tz is Z return 0; } else { var hm = parseInt(numOffset, 10), m = hm % 100, h = (hm - m) / 100; return h * 60 + m; } } // date and time from ref 2822 format function configFromRFC2822(config) { var match = rfc2822.exec(preprocessRFC2822(config._i)), parsedArray; if (match) { parsedArray = extractFromRFC2822Strings( match[4], match[3], match[2], match[5], match[6], match[7] ); if (!checkWeekday(match[1], parsedArray, config)) { return; } config._a = parsedArray; config._tzm = calculateOffset(match[8], match[9], match[10]); config._d = createUTCDate.apply(null, config._a); config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); getParsingFlags(config).rfc2822 = true; } else { config._isValid = false; } } // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; } else { return; } configFromRFC2822(config); if (config._isValid === false) { delete config._isValid; } else { return; } if (config._strict) { config._isValid = false; } else { // Final attempt, use Input Fallback hooks.createFromInputFallback(config); } } hooks.createFromInputFallback = deprecate( 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // Pick the first defined of two or three arguments. function defaults(a, b, c) { if (a != null) { return a; } if (b != null) { return b; } return c; } function currentDateArray(config) { // hooks is actually the exported moment object var nowValue = new Date(hooks.now()); if (config._useUTC) { return [ nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate(), ]; } return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray(config) { var i, date, input = [], currentDate, expectedWeekday, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear != null) { yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); if ( config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0 ) { getParsingFlags(config)._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if ( config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0 ) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply( null, input ); expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } // check for mismatching day of week if ( config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday ) { getParsingFlags(config).weekdayMismatch = true; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = defaults( w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year ); week = defaults(w.W, 1); weekday = defaults(w.E, 1); if (weekday < 1 || weekday > 7) { weekdayOverflow = true; } } else { dow = config._locale._week.dow; doy = config._locale._week.doy; curWeek = weekOfYear(createLocal(), dow, doy); weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); // Default to current week. week = defaults(w.w, curWeek.week); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < 0 || weekday > 6) { weekdayOverflow = true; } } else if (w.e != null) { // local weekday -- counting starts from beginning of week weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { // default to beginning of week weekday = dow; } } if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { getParsingFlags(config)._overflowWeeks = true; } else if (weekdayOverflow != null) { getParsingFlags(config)._overflowWeekday = true; } else { temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } } // constant that refers to the ISO standard hooks.ISO_8601 = function () {}; // constant that refers to the RFC 2822 form hooks.RFC_2822 = function () {}; // date from string and format string function configFromStringAndFormat(config) { // TODO: Move this to another part of the creation flow to prevent circular deps if (config._f === hooks.ISO_8601) { configFromISO(config); return; } if (config._f === hooks.RFC_2822) { configFromRFC2822(config); return; } config._a = []; getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0, era; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { getParsingFlags(config).unusedInput.push(skipped); } string = string.slice( string.indexOf(parsedInput) + parsedInput.length ); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { getParsingFlags(config).empty = false; } else { getParsingFlags(config).unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { getParsingFlags(config).unusedTokens.push(token); } } // add remaining unparsed input length to the string getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { getParsingFlags(config).unusedInput.push(string); } // clear _12h flag if hour is <= 12 if ( config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0 ) { getParsingFlags(config).bigHour = undefined; } getParsingFlags(config).parsedDateParts = config._a.slice(0); getParsingFlags(config).meridiem = config._meridiem; // handle meridiem config._a[HOUR] = meridiemFixWrap( config._locale, config._a[HOUR], config._meridiem ); // handle era era = getParsingFlags(config).era; if (era !== null) { config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); } configFromArray(config); checkOverflow(config); } function meridiemFixWrap(locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // this is not supposed to happen return hour; } } // date from string and array of format strings function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = false; if (config._f.length === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; validFormatFound = false; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (isValid(tempConfig)) { validFormatFound = true; } // if there is any input that was not parsed add a penalty for that format currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; getParsingFlags(tempConfig).score = currentScore; if (!bestFormatIsValid) { if ( scoreToBeat == null || currentScore < scoreToBeat || validFormatFound ) { scoreToBeat = currentScore; bestMoment = tempConfig; if (validFormatFound) { bestFormatIsValid = true; } } } else { if (currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i), dayOrDate = i.day === undefined ? i.date : i.day; config._a = map( [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], function (obj) { return obj && parseInt(obj, 10); } ); configFromArray(config); } function createFromConfig(config) { var res = new Moment(checkOverflow(prepareConfig(config))); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } function prepareConfig(config) { var input = config._i, format = config._f; config._locale = config._locale || getLocale(config._l); if (input === null || (format === undefined && input === '')) { return createInvalid({ nullInput: true }); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isDate(input)) { config._d = input; } else if (isArray(format)) { configFromStringAndArray(config); } else if (format) { configFromStringAndFormat(config); } else { configFromInput(config); } if (!isValid(config)) { config._d = null; } return config; } function configFromInput(config) { var input = config._i; if (isUndefined(input)) { config._d = new Date(hooks.now()); } else if (isDate(input)) { config._d = new Date(input.valueOf()); } else if (typeof input === 'string') { configFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (isObject(input)) { configFromObject(config); } else if (isNumber(input)) { // from milliseconds config._d = new Date(input); } else { hooks.createFromInputFallback(config); } } function createLocalOrUTC(input, format, locale, strict, isUTC) { var c = {}; if (format === true || format === false) { strict = format; format = undefined; } if (locale === true || locale === false) { strict = locale; locale = undefined; } if ( (isObject(input) && isObjectEmpty(input)) || (isArray(input) && input.length === 0) ) { input = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale; c._i = input; c._f = format; c._strict = strict; return createFromConfig(c); } function createLocal(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other < this ? this : other; } else { return createInvalid(); } } ), prototypeMax = deprecate( 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other > this ? this : other; } else { return createInvalid(); } } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (!moments[i].isValid() || moments[i][fn](res)) { res = moments[i]; } } return res; } // TODO: Use [].sort instead? function min() { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); } function max() { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); } var now = function () { return Date.now ? Date.now() : +new Date(); }; var ordering = [ 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond', ]; function isDurationValid(m) { var key, unitHasDecimal = false, i; for (key in m) { if ( hasOwnProp(m, key) && !( indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])) ) ) { return false; } } for (i = 0; i < ordering.length; ++i) { if (m[ordering[i]]) { if (unitHasDecimal) { return false; // only allow non-integers for smallest unit } if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { unitHasDecimal = true; } } } return true; } function isValid$1() { return this._isValid; } function createInvalid$1() { return createDuration(NaN); } function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || normalizedInput.isoWeek || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; this._isValid = isDurationValid(normalizedInput); // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible to translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = getLocale(); this._bubble(); } function isDuration(obj) { return obj instanceof Duration; } function absRound(number) { if (number < 0) { return Math.round(-1 * number) * -1; } else { return Math.round(number); } } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ( (dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i])) ) { diffs++; } } return diffs + lengthDiff; } // FORMATTING function offset(token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(), sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } return ( sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2) ); }); } offset('Z', ':'); offset('ZZ', ''); // PARSING addRegexToken('Z', matchShortOffset); addRegexToken('ZZ', matchShortOffset); addParseToken(['Z', 'ZZ'], function (input, array, config) { config._useUTC = true; config._tzm = offsetFromString(matchShortOffset, input); }); // HELPERS // timezone chunker // '+10:00' > ['10', '00'] // '-1530' > ['-15', '30'] var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string) { var matches = (string || '').match(matcher), chunk, parts, minutes; if (matches === null) { return null; } chunk = matches[matches.length - 1] || []; parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; minutes = +(parts[1] * 60) + toInt(parts[2]); return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api. res._d.setTime(res._d.valueOf() + diff); hooks.updateOffset(res, false); return res; } else { return createLocal(input).local(); } } function getDateOffset(m) { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(m._d.getTimezoneOffset()); } // HOOKS // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. hooks.updateOffset = function () {}; // MOMENTS // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset(input, keepLocalTime, keepMinutes) { var offset = this._offset || 0, localAdjust; if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { if (typeof input === 'string') { input = offsetFromString(matchShortOffset, input); if (input === null) { return this; } } else if (Math.abs(input) < 16 && !keepMinutes) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addSubtract( this, createDuration(input - offset, 'm'), 1, false ); } else if (!this._changeInProgress) { this._changeInProgress = true; hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : getDateOffset(this); } } function getSetZone(input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC(keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal(keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), 'm'); } } return this; } function setOffsetToParsedOffset() { if (this._tzm != null) { this.utcOffset(this._tzm, false, true); } else if (typeof this._i === 'string') { var tZone = offsetFromString(matchOffset, this._i); if (tZone != null) { this.utcOffset(tZone); } else { this.utcOffset(0, true); } } return this; } function hasAlignedHourOffset(input) { if (!this.isValid()) { return false; } input = input ? createLocal(input).utcOffset() : 0; return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime() { return ( this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() ); } function isDaylightSavingTimeShifted() { if (!isUndefined(this._isDSTShifted)) { return this._isDSTShifted; } var c = {}, other; copyConfig(c, this); c = prepareConfig(c); if (c._a) { other = c._isUTC ? createUTC(c._a) : createLocal(c._a); this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { this._isDSTShifted = false; } return this._isDSTShifted; } function isLocal() { return this.isValid() ? !this._isUTC : false; } function isUtcOffset() { return this.isValid() ? this._isUTC : false; } function isUtc() { return this.isValid() ? this._isUTC && this._offset === 0 : false; } // ASP.NET json date format regex var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; function createDuration(input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months, }; } else if (isNumber(input) || !isNaN(+input)) { duration = {}; if (key) { duration[key] = +input; } else { duration.milliseconds = +input; } } else if ((match = aspNetRegex.exec(input))) { sign = match[1] === '-' ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match }; } else if ((match = isoRegex.exec(input))) { sign = match[1] === '-' ? -1 : 1; duration = { y: parseIso(match[2], sign), M: parseIso(match[3], sign), w: parseIso(match[4], sign), d: parseIso(match[5], sign), h: parseIso(match[6], sign), m: parseIso(match[7], sign), s: parseIso(match[8], sign), }; } else if (duration == null) { // checks for null or undefined duration = {}; } else if ( typeof duration === 'object' && ('from' in duration || 'to' in duration) ) { diffRes = momentsDifference( createLocal(duration.from), createLocal(duration.to) ); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } if (isDuration(input) && hasOwnProp(input, '_isValid')) { ret._isValid = input._isValid; } return ret; } createDuration.fn = Duration.prototype; createDuration.invalid = createInvalid$1; function parseIso(inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +base.clone().add(res.months, 'M'); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return { milliseconds: 0, months: 0 }; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple( name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.' ); tmp = val; val = period; period = tmp; } dur = createDuration(val, period); addSubtract(this, dur, direction); return this; }; } function addSubtract(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months); if (!mom.isValid()) { // No op return; } updateOffset = updateOffset == null ? true : updateOffset; if (months) { setMonth(mom, get(mom, 'Month') + months * isAdding); } if (days) { set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); } if (milliseconds) { mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); } if (updateOffset) { hooks.updateOffset(mom, days || months); } } var add = createAdder(1, 'add'), subtract = createAdder(-1, 'subtract'); function isString(input) { return typeof input === 'string' || input instanceof String; } // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined function isMomentInput(input) { return ( isMoment(input) || isDate(input) || isString(input) || isNumber(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === undefined ); } function isMomentInputObject(input) { var objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = false, properties = [ 'years', 'year', 'y', 'months', 'month', 'M', 'days', 'day', 'd', 'dates', 'date', 'D', 'hours', 'hour', 'h', 'minutes', 'minute', 'm', 'seconds', 'second', 's', 'milliseconds', 'millisecond', 'ms', ], i, property; for (i = 0; i < properties.length; i += 1) { property = properties[i]; propertyTest = propertyTest || hasOwnProp(input, property); } return objectTest && propertyTest; } function isNumberOrStringArray(input) { var arrayTest = isArray(input), dataTypeTest = false; if (arrayTest) { dataTypeTest = input.filter(function (item) { return !isNumber(item) && isString(input); }).length === 0; } return arrayTest && dataTypeTest; } function isCalendarSpec(input) { var objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = false, properties = [ 'sameDay', 'nextDay', 'lastDay', 'nextWeek', 'lastWeek', 'sameElse', ], i, property; for (i = 0; i < properties.length; i += 1) { property = properties[i]; propertyTest = propertyTest || hasOwnProp(input, property); } return objectTest && propertyTest; } function getCalendarFormat(myMoment, now) { var diff = myMoment.diff(now, 'days', true); return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; } function calendar$1(time, formats) { // Support for single parameter, formats only overload to the calendar function if (arguments.length === 1) { if (isMomentInput(arguments[0])) { time = arguments[0]; formats = undefined; } else if (isCalendarSpec(arguments[0])) { formats = arguments[0]; time = undefined; } } // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're local/utc/offset or not. var now = time || createLocal(), sod = cloneWithOffset(now, this).startOf('day'), format = hooks.calendarFormat(this, sod) || 'sameElse', output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); return this.format( output || this.localeData().calendar(format, this, createLocal(now)) ); } function clone() { return new Moment(this); } function isAfter(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() > localInput.valueOf(); } else { return localInput.valueOf() < this.clone().startOf(units).valueOf(); } } function isBefore(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() < localInput.valueOf(); } else { return this.clone().endOf(units).valueOf() < localInput.valueOf(); } } function isBetween(from, to, units, inclusivity) { var localFrom = isMoment(from) ? from : createLocal(from), localTo = isMoment(to) ? to : createLocal(to); if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { return false; } inclusivity = inclusivity || '()'; return ( (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)) ); } function isSame(input, units) { var localInput = isMoment(input) ? input : createLocal(input), inputMs; if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() === localInput.valueOf(); } else { inputMs = localInput.valueOf(); return ( this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf() ); } } function isSameOrAfter(input, units) { return this.isSame(input, units) || this.isAfter(input, units); } function isSameOrBefore(input, units) { return this.isSame(input, units) || this.isBefore(input, units); } function diff(input, units, asFloat) { var that, zoneDelta, output; if (!this.isValid()) { return NaN; } that = cloneWithOffset(input, this); if (!that.isValid()) { return NaN; } zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; units = normalizeUnits(units); switch (units) { case 'year': output = monthDiff(this, that) / 12; break; case 'month': output = monthDiff(this, that); break; case 'quarter': output = monthDiff(this, that) / 3; break; case 'second': output = (this - that) / 1e3; break; // 1000 case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst default: output = this - that; } return asFloat ? output : absFloor(output); } function monthDiff(a, b) { if (a.date() < b.date()) { // end-of-month calculations work correct when the start month has more // days than the end month. return -monthDiff(b, a); } // difference in months var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } //check for negative zero, return zero if negative zero return -(wholeMonthDiff + adjust) || 0; } hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; function toString() { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } function toISOString(keepOffset) { if (!this.isValid()) { return null; } var utc = keepOffset !== true, m = utc ? this.clone().utc() : this; if (m.year() < 0 || m.year() > 9999) { return formatMoment( m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ' ); } if (isFunction(Date.prototype.toISOString)) { // native implementation is ~50x faster, use it when we can if (utc) { return this.toDate().toISOString(); } else { return new Date(this.valueOf() + this.utcOffset() * 60 * 1000) .toISOString() .replace('Z', formatMoment(m, 'Z')); } } return formatMoment( m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ' ); } /** * Return a human readable representation of a moment that can * also be evaluated to get a new moment which is the same * * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects */ function inspect() { if (!this.isValid()) { return 'moment.invalid(/* ' + this._i + ' */)'; } var func = 'moment', zone = '', prefix, year, datetime, suffix; if (!this.isLocal()) { func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; zone = 'Z'; } prefix = '[' + func + '("]'; year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY'; datetime = '-MM-DD[T]HH:mm:ss.SSS'; suffix = zone + '[")]'; return this.format(prefix + year + datetime + suffix); } function format(inputString) { if (!inputString) { inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; } var output = formatMoment(this, inputString); return this.localeData().postformat(output); } function from(time, withoutSuffix) { if ( this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) ) { return createDuration({ to: this, from: time }) .locale(this.locale()) .humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function fromNow(withoutSuffix) { return this.from(createLocal(), withoutSuffix); } function to(time, withoutSuffix) { if ( this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) ) { return createDuration({ from: this, to: time }) .locale(this.locale()) .humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function toNow(withoutSuffix) { return this.to(createLocal(), withoutSuffix); } // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. function locale(key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ); function localeData() { return this._locale; } var MS_PER_SECOND = 1000, MS_PER_MINUTE = 60 * MS_PER_SECOND, MS_PER_HOUR = 60 * MS_PER_MINUTE, MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; // actual modulo - handles negative numbers (for dates before 1970): function mod$1(dividend, divisor) { return ((dividend % divisor) + divisor) % divisor; } function localStartOfDate(y, m, d) { // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset return new Date(y + 400, m, d) - MS_PER_400_YEARS; } else { return new Date(y, m, d).valueOf(); } } function utcStartOfDate(y, m, d) { // Date.UTC remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; } else { return Date.UTC(y, m, d); } } function startOf(units) { var time, startOfDate; units = normalizeUnits(units); if (units === undefined || units === 'millisecond' || !this.isValid()) { return this; } startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case 'year': time = startOfDate(this.year(), 0, 1); break; case 'quarter': time = startOfDate( this.year(), this.month() - (this.month() % 3), 1 ); break; case 'month': time = startOfDate(this.year(), this.month(), 1); break; case 'week': time = startOfDate( this.year(), this.month(), this.date() - this.weekday() ); break; case 'isoWeek': time = startOfDate( this.year(), this.month(), this.date() - (this.isoWeekday() - 1) ); break; case 'day': case 'date': time = startOfDate(this.year(), this.month(), this.date()); break; case 'hour': time = this._d.valueOf(); time -= mod$1( time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR ); break; case 'minute': time = this._d.valueOf(); time -= mod$1(time, MS_PER_MINUTE); break; case 'second': time = this._d.valueOf(); time -= mod$1(time, MS_PER_SECOND); break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function endOf(units) { var time, startOfDate; units = normalizeUnits(units); if (units === undefined || units === 'millisecond' || !this.isValid()) { return this; } startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case 'year': time = startOfDate(this.year() + 1, 0, 1) - 1; break; case 'quarter': time = startOfDate( this.year(), this.month() - (this.month() % 3) + 3, 1 ) - 1; break; case 'month': time = startOfDate(this.year(), this.month() + 1, 1) - 1; break; case 'week': time = startOfDate( this.year(), this.month(), this.date() - this.weekday() + 7 ) - 1; break; case 'isoWeek': time = startOfDate( this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7 ) - 1; break; case 'day': case 'date': time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; break; case 'hour': time = this._d.valueOf(); time += MS_PER_HOUR - mod$1( time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR ) - 1; break; case 'minute': time = this._d.valueOf(); time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; break; case 'second': time = this._d.valueOf(); time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function valueOf() { return this._d.valueOf() - (this._offset || 0) * 60000; } function unix() { return Math.floor(this.valueOf() / 1000); } function toDate() { return new Date(this.valueOf()); } function toArray() { var m = this; return [ m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond(), ]; } function toObject() { var m = this; return { years: m.year(), months: m.month(), date: m.date(), hours: m.hours(), minutes: m.minutes(), seconds: m.seconds(), milliseconds: m.milliseconds(), }; } function toJSON() { // new Date(NaN).toJSON() === null return this.isValid() ? this.toISOString() : null; } function isValid$2() { return isValid(this); } function parsingFlags() { return extend({}, getParsingFlags(this)); } function invalidAt() { return getParsingFlags(this).overflow; } function creationData() { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict, }; } addFormatToken('N', 0, 0, 'eraAbbr'); addFormatToken('NN', 0, 0, 'eraAbbr'); addFormatToken('NNN', 0, 0, 'eraAbbr'); addFormatToken('NNNN', 0, 0, 'eraName'); addFormatToken('NNNNN', 0, 0, 'eraNarrow'); addFormatToken('y', ['y', 1], 'yo', 'eraYear'); addFormatToken('y', ['yy', 2], 0, 'eraYear'); addFormatToken('y', ['yyy', 3], 0, 'eraYear'); addFormatToken('y', ['yyyy', 4], 0, 'eraYear'); addRegexToken('N', matchEraAbbr); addRegexToken('NN', matchEraAbbr); addRegexToken('NNN', matchEraAbbr); addRegexToken('NNNN', matchEraName); addRegexToken('NNNNN', matchEraNarrow); addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function ( input, array, config, token ) { var era = config._locale.erasParse(input, token, config._strict); if (era) { getParsingFlags(config).era = era; } else { getParsingFlags(config).invalidEra = input; } }); addRegexToken('y', matchUnsigned); addRegexToken('yy', matchUnsigned); addRegexToken('yyy', matchUnsigned); addRegexToken('yyyy', matchUnsigned); addRegexToken('yo', matchEraYearOrdinal); addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR); addParseToken(['yo'], function (input, array, config, token) { var match; if (config._locale._eraYearOrdinalRegex) { match = input.match(config._locale._eraYearOrdinalRegex); } if (config._locale.eraYearOrdinalParse) { array[YEAR] = config._locale.eraYearOrdinalParse(input, match); } else { array[YEAR] = parseInt(input, 10); } }); function localeEras(m, format) { var i, l, date, eras = this._eras || getLocale('en')._eras; for (i = 0, l = eras.length; i < l; ++i) { switch (typeof eras[i].since) { case 'string': // truncate time date = hooks(eras[i].since).startOf('day'); eras[i].since = date.valueOf(); break; } switch (typeof eras[i].until) { case 'undefined': eras[i].until = +Infinity; break; case 'string': // truncate time date = hooks(eras[i].until).startOf('day').valueOf(); eras[i].until = date.valueOf(); break; } } return eras; } function localeErasParse(eraName, format, strict) { var i, l, eras = this.eras(), name, abbr, narrow; eraName = eraName.toUpperCase(); for (i = 0, l = eras.length; i < l; ++i) { name = eras[i].name.toUpperCase(); abbr = eras[i].abbr.toUpperCase(); narrow = eras[i].narrow.toUpperCase(); if (strict) { switch (format) { case 'N': case 'NN': case 'NNN': if (abbr === eraName) { return eras[i]; } break; case 'NNNN': if (name === eraName) { return eras[i]; } break; case 'NNNNN': if (narrow === eraName) { return eras[i]; } break; } } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { return eras[i]; } } } function localeErasConvertYear(era, year) { var dir = era.since <= era.until ? +1 : -1; if (year === undefined) { return hooks(era.since).year(); } else { return hooks(era.since).year() + (year - era.offset) * dir; } } function getEraName() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { // truncate time val = this.startOf('day').valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].name; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].name; } } return ''; } function getEraNarrow() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { // truncate time val = this.startOf('day').valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].narrow; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].narrow; } } return ''; } function getEraAbbr() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { // truncate time val = this.startOf('day').valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].abbr; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].abbr; } } return ''; } function getEraYear() { var i, l, dir, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { dir = eras[i].since <= eras[i].until ? +1 : -1; // truncate time val = this.startOf('day').valueOf(); if ( (eras[i].since <= val && val <= eras[i].until) || (eras[i].until <= val && val <= eras[i].since) ) { return ( (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset ); } } return this.year(); } function erasNameRegex(isStrict) { if (!hasOwnProp(this, '_erasNameRegex')) { computeErasParse.call(this); } return isStrict ? this._erasNameRegex : this._erasRegex; } function erasAbbrRegex(isStrict) { if (!hasOwnProp(this, '_erasAbbrRegex')) { computeErasParse.call(this); } return isStrict ? this._erasAbbrRegex : this._erasRegex; } function erasNarrowRegex(isStrict) { if (!hasOwnProp(this, '_erasNarrowRegex')) { computeErasParse.call(this); } return isStrict ? this._erasNarrowRegex : this._erasRegex; } function matchEraAbbr(isStrict, locale) { return locale.erasAbbrRegex(isStrict); } function matchEraName(isStrict, locale) { return locale.erasNameRegex(isStrict); } function matchEraNarrow(isStrict, locale) { return locale.erasNarrowRegex(isStrict); } function matchEraYearOrdinal(isStrict, locale) { return locale._eraYearOrdinalRegex || matchUnsigned; } function computeErasParse() { var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i, l, eras = this.eras(); for (i = 0, l = eras.length; i < l; ++i) { namePieces.push(regexEscape(eras[i].name)); abbrPieces.push(regexEscape(eras[i].abbr)); narrowPieces.push(regexEscape(eras[i].narrow)); mixedPieces.push(regexEscape(eras[i].name)); mixedPieces.push(regexEscape(eras[i].abbr)); mixedPieces.push(regexEscape(eras[i].narrow)); } this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i'); this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i'); this._erasNarrowRegex = new RegExp( '^(' + narrowPieces.join('|') + ')', 'i' ); } // FORMATTING addFormatToken(0, ['gg', 2], 0, function () { return this.weekYear() % 100; }); addFormatToken(0, ['GG', 2], 0, function () { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken(token, getter) { addFormatToken(0, [token, token.length], 0, getter); } addWeekYearFormatToken('gggg', 'weekYear'); addWeekYearFormatToken('ggggg', 'weekYear'); addWeekYearFormatToken('GGGG', 'isoWeekYear'); addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES addUnitAlias('weekYear', 'gg'); addUnitAlias('isoWeekYear', 'GG'); // PRIORITY addUnitPriority('weekYear', 1); addUnitPriority('isoWeekYear', 1); // PARSING addRegexToken('G', matchSigned); addRegexToken('g', matchSigned); addRegexToken('GG', match1to2, match2); addRegexToken('gg', match1to2, match2); addRegexToken('GGGG', match1to4, match4); addRegexToken('gggg', match1to4, match4); addRegexToken('GGGGG', match1to6, match6); addRegexToken('ggggg', match1to6, match6); addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function ( input, week, config, token ) { week[token.substr(0, 2)] = toInt(input); }); addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { week[token] = hooks.parseTwoDigitYear(input); }); // MOMENTS function getSetWeekYear(input) { return getSetWeekYearHelper.call( this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy ); } function getSetISOWeekYear(input) { return getSetWeekYearHelper.call( this, input, this.isoWeek(), this.isoWeekday(), 1, 4 ); } function getISOWeeksInYear() { return weeksInYear(this.year(), 1, 4); } function getISOWeeksInISOWeekYear() { return weeksInYear(this.isoWeekYear(), 1, 4); } function getWeeksInYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getWeeksInWeekYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { var weeksTarget; if (input == null) { return weekOfYear(this, dow, doy).year; } else { weeksTarget = weeksInYear(input, dow, doy); if (week > weeksTarget) { week = weeksTarget; } return setWeekAll.call(this, input, week, weekday, dow, doy); } } function setWeekAll(weekYear, week, weekday, dow, doy) { var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); this.year(date.getUTCFullYear()); this.month(date.getUTCMonth()); this.date(date.getUTCDate()); return this; } // FORMATTING addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES addUnitAlias('quarter', 'Q'); // PRIORITY addUnitPriority('quarter', 7); // PARSING addRegexToken('Q', match1); addParseToken('Q', function (input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter(input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + (this.month() % 3)); } // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIORITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { // TODO: Remove "ordinalParse" fallback in next major release. return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0]); }); // MOMENTS var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES addUnitAlias('dayOfYear', 'DDD'); // PRIORITY addUnitPriority('dayOfYear', 4); // PARSING addRegexToken('DDD', match1to3); addRegexToken('DDDD', match3); addParseToken(['DDD', 'DDDD'], function (input, array, config) { config._dayOfYear = toInt(input); }); // HELPERS // MOMENTS function getSetDayOfYear(input) { var dayOfYear = Math.round( (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5 ) + 1; return input == null ? dayOfYear : this.add(input - dayOfYear, 'd'); } // FORMATTING addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES addUnitAlias('minute', 'm'); // PRIORITY addUnitPriority('minute', 14); // PARSING addRegexToken('m', match1to2); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); // FORMATTING addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES addUnitAlias('second', 's'); // PRIORITY addUnitPriority('second', 15); // PARSING addRegexToken('s', match1to2); addRegexToken('ss', match1to2, match2); addParseToken(['s', 'ss'], SECOND); // MOMENTS var getSetSecond = makeGetSet('Seconds', false); // FORMATTING addFormatToken('S', 0, 0, function () { return ~~(this.millisecond() / 100); }); addFormatToken(0, ['SS', 2], 0, function () { return ~~(this.millisecond() / 10); }); addFormatToken(0, ['SSS', 3], 0, 'millisecond'); addFormatToken(0, ['SSSS', 4], 0, function () { return this.millisecond() * 10; }); addFormatToken(0, ['SSSSS', 5], 0, function () { return this.millisecond() * 100; }); addFormatToken(0, ['SSSSSS', 6], 0, function () { return this.millisecond() * 1000; }); addFormatToken(0, ['SSSSSSS', 7], 0, function () { return this.millisecond() * 10000; }); addFormatToken(0, ['SSSSSSSS', 8], 0, function () { return this.millisecond() * 100000; }); addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { return this.millisecond() * 1000000; }); // ALIASES addUnitAlias('millisecond', 'ms'); // PRIORITY addUnitPriority('millisecond', 16); // PARSING addRegexToken('S', match1to3, match1); addRegexToken('SS', match1to3, match2); addRegexToken('SSS', match1to3, match3); var token, getSetMillisecond; for (token = 'SSSS'; token.length <= 9; token += 'S') { addRegexToken(token, matchUnsigned); } function parseMs(input, array) { array[MILLISECOND] = toInt(('0.' + input) * 1000); } for (token = 'S'; token.length <= 9; token += 'S') { addParseToken(token, parseMs); } getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING addFormatToken('z', 0, 0, 'zoneAbbr'); addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS function getZoneAbbr() { return this._isUTC ? 'UTC' : ''; } function getZoneName() { return this._isUTC ? 'Coordinated Universal Time' : ''; } var proto = Moment.prototype; proto.add = add; proto.calendar = calendar$1; proto.clone = clone; proto.diff = diff; proto.endOf = endOf; proto.format = format; proto.from = from; proto.fromNow = fromNow; proto.to = to; proto.toNow = toNow; proto.get = stringGet; proto.invalidAt = invalidAt; proto.isAfter = isAfter; proto.isBefore = isBefore; proto.isBetween = isBetween; proto.isSame = isSame; proto.isSameOrAfter = isSameOrAfter; proto.isSameOrBefore = isSameOrBefore; proto.isValid = isValid$2; proto.lang = lang; proto.locale = locale; proto.localeData = localeData; proto.max = prototypeMax; proto.min = prototypeMin; proto.parsingFlags = parsingFlags; proto.set = stringSet; proto.startOf = startOf; proto.subtract = subtract; proto.toArray = toArray; proto.toObject = toObject; proto.toDate = toDate; proto.toISOString = toISOString; proto.inspect = inspect; if (typeof Symbol !== 'undefined' && Symbol.for != null) { proto[Symbol.for('nodejs.util.inspect.custom')] = function () { return 'Moment<' + this.format() + '>'; }; } proto.toJSON = toJSON; proto.toString = toString; proto.unix = unix; proto.valueOf = valueOf; proto.creationData = creationData; proto.eraName = getEraName; proto.eraNarrow = getEraNarrow; proto.eraAbbr = getEraAbbr; proto.eraYear = getEraYear; proto.year = getSetYear; proto.isLeapYear = getIsLeapYear; proto.weekYear = getSetWeekYear; proto.isoWeekYear = getSetISOWeekYear; proto.quarter = proto.quarters = getSetQuarter; proto.month = getSetMonth; proto.daysInMonth = getDaysInMonth; proto.week = proto.weeks = getSetWeek; proto.isoWeek = proto.isoWeeks = getSetISOWeek; proto.weeksInYear = getWeeksInYear; proto.weeksInWeekYear = getWeeksInWeekYear; proto.isoWeeksInYear = getISOWeeksInYear; proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; proto.date = getSetDayOfMonth; proto.day = proto.days = getSetDayOfWeek; proto.weekday = getSetLocaleDayOfWeek; proto.isoWeekday = getSetISODayOfWeek; proto.dayOfYear = getSetDayOfYear; proto.hour = proto.hours = getSetHour; proto.minute = proto.minutes = getSetMinute; proto.second = proto.seconds = getSetSecond; proto.millisecond = proto.milliseconds = getSetMillisecond; proto.utcOffset = getSetOffset; proto.utc = setOffsetToUTC; proto.local = setOffsetToLocal; proto.parseZone = setOffsetToParsedOffset; proto.hasAlignedHourOffset = hasAlignedHourOffset; proto.isDST = isDaylightSavingTime; proto.isLocal = isLocal; proto.isUtcOffset = isUtcOffset; proto.isUtc = isUtc; proto.isUTC = isUtc; proto.zoneAbbr = getZoneAbbr; proto.zoneName = getZoneName; proto.dates = deprecate( 'dates accessor is deprecated. Use date instead.', getSetDayOfMonth ); proto.months = deprecate( 'months accessor is deprecated. Use month instead', getSetMonth ); proto.years = deprecate( 'years accessor is deprecated. Use year instead', getSetYear ); proto.zone = deprecate( 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone ); proto.isDSTShifted = deprecate( 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted ); function createUnix(input) { return createLocal(input * 1000); } function createInZone() { return createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat(string) { return string; } var proto$1 = Locale.prototype; proto$1.calendar = calendar; proto$1.longDateFormat = longDateFormat; proto$1.invalidDate = invalidDate; proto$1.ordinal = ordinal; proto$1.preparse = preParsePostFormat; proto$1.postformat = preParsePostFormat; proto$1.relativeTime = relativeTime; proto$1.pastFuture = pastFuture; proto$1.set = set; proto$1.eras = localeEras; proto$1.erasParse = localeErasParse; proto$1.erasConvertYear = localeErasConvertYear; proto$1.erasAbbrRegex = erasAbbrRegex; proto$1.erasNameRegex = erasNameRegex; proto$1.erasNarrowRegex = erasNarrowRegex; proto$1.months = localeMonths; proto$1.monthsShort = localeMonthsShort; proto$1.monthsParse = localeMonthsParse; proto$1.monthsRegex = monthsRegex; proto$1.monthsShortRegex = monthsShortRegex; proto$1.week = localeWeek; proto$1.firstDayOfYear = localeFirstDayOfYear; proto$1.firstDayOfWeek = localeFirstDayOfWeek; proto$1.weekdays = localeWeekdays; proto$1.weekdaysMin = localeWeekdaysMin; proto$1.weekdaysShort = localeWeekdaysShort; proto$1.weekdaysParse = localeWeekdaysParse; proto$1.weekdaysRegex = weekdaysRegex; proto$1.weekdaysShortRegex = weekdaysShortRegex; proto$1.weekdaysMinRegex = weekdaysMinRegex; proto$1.isPM = localeIsPM; proto$1.meridiem = localeMeridiem; function get$1(format, index, field, setter) { var locale = getLocale(), utc = createUTC().set(setter, index); return locale[field](utc, format); } function listMonthsImpl(format, index, field) { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; if (index != null) { return get$1(format, index, field, 'month'); } var i, out = []; for (i = 0; i < 12; i++) { out[i] = get$1(format, i, field, 'month'); } return out; } // () // (5) // (fmt, 5) // (fmt) // (true) // (true, 5) // (true, fmt, 5) // (true, fmt) function listWeekdaysImpl(localeSorted, format, index, field) { if (typeof localeSorted === 'boolean') { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } else { format = localeSorted; index = format; localeSorted = false; if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } var locale = getLocale(), shift = localeSorted ? locale._week.dow : 0, i, out = []; if (index != null) { return get$1(format, (index + shift) % 7, field, 'day'); } for (i = 0; i < 7; i++) { out[i] = get$1(format, (i + shift) % 7, field, 'day'); } return out; } function listMonths(format, index) { return listMonthsImpl(format, index, 'months'); } function listMonthsShort(format, index) { return listMonthsImpl(format, index, 'monthsShort'); } function listWeekdays(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); } function listWeekdaysShort(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); } function listWeekdaysMin(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); } getSetGlobalLocale('en', { eras: [ { since: '0001-01-01', until: +Infinity, offset: 1, name: 'Anno Domini', narrow: 'AD', abbr: 'AD', }, { since: '0000-12-31', until: -Infinity, offset: 1, name: 'Before Christ', narrow: 'BC', abbr: 'BC', }, ], dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: function (number) { var b = number % 10, output = toInt((number % 100) / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th'; return number + output; }, }); // Side effect imports hooks.lang = deprecate( 'moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale ); hooks.langData = deprecate( 'moment.langData is deprecated. Use moment.localeData instead.', getLocale ); var mathAbs = Math.abs; function abs() { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function addSubtract$1(duration, input, value, direction) { var other = createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function add$1(input, value) { return addSubtract$1(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function subtract$1(input, value) { return addSubtract$1(this, input, value, -1); } function absCeil(number) { if (number < 0) { return Math.floor(number); } else { return Math.ceil(number); } } function bubble() { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first // check: https://github.com/moment/moment/issues/2166 if ( !( (milliseconds >= 0 && days >= 0 && months >= 0) || (milliseconds <= 0 && days <= 0 && months <= 0) ) ) { milliseconds += absCeil(monthsToDays(months) + days) * 864e5; days = 0; months = 0; } // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absFloor(milliseconds / 1000); data.seconds = seconds % 60; minutes = absFloor(seconds / 60); data.minutes = minutes % 60; hours = absFloor(minutes / 60); data.hours = hours % 24; days += absFloor(hours / 24); // convert days to months monthsFromDays = absFloor(daysToMonths(days)); months += monthsFromDays; days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year years = absFloor(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; return this; } function daysToMonths(days) { // 400 years have 146097 days (taking into account leap year rules) // 400 years have 12 months === 4800 return (days * 4800) / 146097; } function monthsToDays(months) { // the reverse of daysToMonths return (months * 146097) / 4800; } function as(units) { if (!this.isValid()) { return NaN; } var days, months, milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'quarter' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToMonths(days); switch (units) { case 'month': return months; case 'quarter': return months / 3; case 'year': return months / 12; } } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(monthsToDays(this._months)); switch (units) { case 'week': return days / 7 + milliseconds / 6048e5; case 'day': return days + milliseconds / 864e5; case 'hour': return days * 24 + milliseconds / 36e5; case 'minute': return days * 1440 + milliseconds / 6e4; case 'second': return days * 86400 + milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 864e5) + milliseconds; default: throw new Error('Unknown unit ' + units); } } } // TODO: Use this.as('ms')? function valueOf$1() { if (!this.isValid()) { return NaN; } return ( this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6 ); } function makeAs(alias) { return function () { return this.as(alias); }; } var asMilliseconds = makeAs('ms'), asSeconds = makeAs('s'), asMinutes = makeAs('m'), asHours = makeAs('h'), asDays = makeAs('d'), asWeeks = makeAs('w'), asMonths = makeAs('M'), asQuarters = makeAs('Q'), asYears = makeAs('y'); function clone$1() { return createDuration(this); } function get$2(units) { units = normalizeUnits(units); return this.isValid() ? this[units + 's']() : NaN; } function makeGetter(name) { return function () { return this.isValid() ? this._data[name] : NaN; }; } var milliseconds = makeGetter('milliseconds'), seconds = makeGetter('seconds'), minutes = makeGetter('minutes'), hours = makeGetter('hours'), days = makeGetter('days'), months = makeGetter('months'), years = makeGetter('years'); function weeks() { return absFloor(this.days() / 7); } var round = Math.round, thresholds = { ss: 44, // a few seconds to seconds s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month/week w: null, // weeks to month M: 11, // months to year }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) { var duration = createDuration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), weeks = round(duration.as('w')), years = round(duration.as('y')), a = (seconds <= thresholds.ss && ['s', seconds]) || (seconds < thresholds.s && ['ss', seconds]) || (minutes <= 1 && ['m']) || (minutes < thresholds.m && ['mm', minutes]) || (hours <= 1 && ['h']) || (hours < thresholds.h && ['hh', hours]) || (days <= 1 && ['d']) || (days < thresholds.d && ['dd', days]); if (thresholds.w != null) { a = a || (weeks <= 1 && ['w']) || (weeks < thresholds.w && ['ww', weeks]); } a = a || (months <= 1 && ['M']) || (months < thresholds.M && ['MM', months]) || (years <= 1 && ['y']) || ['yy', years]; a[2] = withoutSuffix; a[3] = +posNegDuration > 0; a[4] = locale; return substituteTimeAgo.apply(null, a); } // This function allows you to set the rounding function for relative time strings function getSetRelativeTimeRounding(roundingFunction) { if (roundingFunction === undefined) { return round; } if (typeof roundingFunction === 'function') { round = roundingFunction; return true; } return false; } // This function allows you to set a threshold for relative time strings function getSetRelativeTimeThreshold(threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; if (threshold === 's') { thresholds.ss = limit - 1; } return true; } function humanize(argWithSuffix, argThresholds) { if (!this.isValid()) { return this.localeData().invalidDate(); } var withSuffix = false, th = thresholds, locale, output; if (typeof argWithSuffix === 'object') { argThresholds = argWithSuffix; argWithSuffix = false; } if (typeof argWithSuffix === 'boolean') { withSuffix = argWithSuffix; } if (typeof argThresholds === 'object') { th = Object.assign({}, thresholds, argThresholds); if (argThresholds.s != null && argThresholds.ss == null) { th.ss = argThresholds.s - 1; } } locale = this.localeData(); output = relativeTime$1(this, !withSuffix, th, locale); if (withSuffix) { output = locale.pastFuture(+this, output); } return locale.postformat(output); } var abs$1 = Math.abs; function sign(x) { return (x > 0) - (x < 0) || +x; } function toISOString$1() { // for ISO strings we do not use the normal bubbling rules: // * milliseconds bubble up until they become hours // * days do not bubble at all // * months bubble up until they become years // This is because there is no context-free conversion between hours and days // (think of clock changes) // and also not between days and months (28-31 days per month) if (!this.isValid()) { return this.localeData().invalidDate(); } var seconds = abs$1(this._milliseconds) / 1000, days = abs$1(this._days), months = abs$1(this._months), minutes, hours, years, s, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign; if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } // 3600 seconds -> 60 minutes -> 1 hour minutes = absFloor(seconds / 60); hours = absFloor(minutes / 60); seconds %= 60; minutes %= 60; // 12 months -> 1 year years = absFloor(months / 12); months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; totalSign = total < 0 ? '-' : ''; ymSign = sign(this._months) !== sign(total) ? '-' : ''; daysSign = sign(this._days) !== sign(total) ? '-' : ''; hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; return ( totalSign + 'P' + (years ? ymSign + years + 'Y' : '') + (months ? ymSign + months + 'M' : '') + (days ? daysSign + days + 'D' : '') + (hours || minutes || seconds ? 'T' : '') + (hours ? hmsSign + hours + 'H' : '') + (minutes ? hmsSign + minutes + 'M' : '') + (seconds ? hmsSign + s + 'S' : '') ); } var proto$2 = Duration.prototype; proto$2.isValid = isValid$1; proto$2.abs = abs; proto$2.add = add$1; proto$2.subtract = subtract$1; proto$2.as = as; proto$2.asMilliseconds = asMilliseconds; proto$2.asSeconds = asSeconds; proto$2.asMinutes = asMinutes; proto$2.asHours = asHours; proto$2.asDays = asDays; proto$2.asWeeks = asWeeks; proto$2.asMonths = asMonths; proto$2.asQuarters = asQuarters; proto$2.asYears = asYears; proto$2.valueOf = valueOf$1; proto$2._bubble = bubble; proto$2.clone = clone$1; proto$2.get = get$2; proto$2.milliseconds = milliseconds; proto$2.seconds = seconds; proto$2.minutes = minutes; proto$2.hours = hours; proto$2.days = days; proto$2.weeks = weeks; proto$2.months = months; proto$2.years = years; proto$2.humanize = humanize; proto$2.toISOString = toISOString$1; proto$2.toString = toISOString$1; proto$2.toJSON = toISOString$1; proto$2.locale = locale; proto$2.localeData = localeData; proto$2.toIsoString = deprecate( 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1 ); proto$2.lang = lang; // FORMATTING addFormatToken('X', 0, 0, 'unix'); addFormatToken('x', 0, 0, 'valueOf'); // PARSING addRegexToken('x', matchSigned); addRegexToken('X', matchTimestamp); addParseToken('X', function (input, array, config) { config._d = new Date(parseFloat(input) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); //! moment.js hooks.version = '2.27.0'; setHookCallback(createLocal); hooks.fn = proto; hooks.min = min; hooks.max = max; hooks.now = now; hooks.utc = createUTC; hooks.unix = createUnix; hooks.months = listMonths; hooks.isDate = isDate; hooks.locale = getSetGlobalLocale; hooks.invalid = createInvalid; hooks.duration = createDuration; hooks.isMoment = isMoment; hooks.weekdays = listWeekdays; hooks.parseZone = createInZone; hooks.localeData = getLocale; hooks.isDuration = isDuration; hooks.monthsShort = listMonthsShort; hooks.weekdaysMin = listWeekdaysMin; hooks.defineLocale = defineLocale; hooks.updateLocale = updateLocale; hooks.locales = listLocales; hooks.weekdaysShort = listWeekdaysShort; hooks.normalizeUnits = normalizeUnits; hooks.relativeTimeRounding = getSetRelativeTimeRounding; hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; hooks.calendarFormat = getCalendarFormat; hooks.prototype = proto; // currently HTML5 input type only supports 24-hour formats hooks.HTML5_FMT = { DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // DATE: 'YYYY-MM-DD', // TIME: 'HH:mm', // TIME_SECONDS: 'HH:mm:ss', // TIME_MS: 'HH:mm:ss.SSS', // WEEK: 'GGGG-[W]WW', // MONTH: 'YYYY-MM', // }; return hooks; }))); },{}],258:[function(require,module,exports){ /** * Export lib/mongoose * */ 'use strict'; module.exports = require('./lib/browser'); },{"./lib/browser":259}],259:[function(require,module,exports){ (function (Buffer){ /* eslint-env browser */ 'use strict'; require('./driver').set(require('./drivers/browser')); const DocumentProvider = require('./document_provider.js'); const PromiseProvider = require('./promise_provider'); DocumentProvider.setBrowser(true); /** * The Mongoose [Promise](#promise_Promise) constructor. * * @method Promise * @api public */ Object.defineProperty(exports, 'Promise', { get: function() { return PromiseProvider.get(); }, set: function(lib) { PromiseProvider.set(lib); } }); /** * Storage layer for mongoose promises * * @method PromiseProvider * @api public */ exports.PromiseProvider = PromiseProvider; /** * The [MongooseError](#error_MongooseError) constructor. * * @method Error * @api public */ exports.Error = require('./error/index'); /** * The Mongoose [Schema](#schema_Schema) constructor * * ####Example: * * const mongoose = require('mongoose'); * const Schema = mongoose.Schema; * const CatSchema = new Schema(..); * * @method Schema * @api public */ exports.Schema = require('./schema'); /** * The various Mongoose Types. * * ####Example: * * const mongoose = require('mongoose'); * const array = mongoose.Types.Array; * * ####Types: * * - [ObjectId](#types-objectid-js) * - [Buffer](#types-buffer-js) * - [SubDocument](#types-embedded-js) * - [Array](#types-array-js) * - [DocumentArray](#types-documentarray-js) * * Using this exposed access to the `ObjectId` type, we can construct ids on demand. * * const ObjectId = mongoose.Types.ObjectId; * const id1 = new ObjectId; * * @property Types * @api public */ exports.Types = require('./types'); /** * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor * * @method VirtualType * @api public */ exports.VirtualType = require('./virtualtype'); /** * The various Mongoose SchemaTypes. * * ####Note: * * _Alias of mongoose.Schema.Types for backwards compatibility._ * * @property SchemaTypes * @see Schema.SchemaTypes #schema_Schema.Types * @api public */ exports.SchemaType = require('./schematype.js'); /** * Internal utils * * @property utils * @api private */ exports.utils = require('./utils.js'); /** * The Mongoose browser [Document](/api/document.html) constructor. * * @method Document * @api public */ exports.Document = DocumentProvider(); /** * Return a new browser model. In the browser, a model is just * a simplified document with a schema - it does **not** have * functions like `findOne()`, etc. * * @method model * @api public * @param {String} name * @param {Schema} schema * @return Class */ exports.model = function(name, schema) { class Model extends exports.Document { constructor(obj, fields) { super(obj, schema, fields); } } Model.modelName = name; return Model; }; /*! * Module exports. */ if (typeof window !== 'undefined') { window.mongoose = module.exports; window.Buffer = Buffer; } }).call(this,require("buffer").Buffer) },{"./document_provider.js":269,"./driver":270,"./drivers/browser":274,"./error/index":278,"./promise_provider":346,"./schema":348,"./schematype.js":369,"./types":377,"./utils.js":381,"./virtualtype":382,"buffer":115}],260:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const NodeJSDocument = require('./document'); const EventEmitter = require('events').EventEmitter; const MongooseError = require('./error/index'); const Schema = require('./schema'); const ObjectId = require('./types/objectid'); const ValidationError = MongooseError.ValidationError; const applyHooks = require('./helpers/model/applyHooks'); const isObject = require('./helpers/isObject'); /** * Document constructor. * * @param {Object} obj the values to set * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. * @event `save`: Emitted when the document is successfully saved * @api private */ function Document(obj, schema, fields, skipId, skipInit) { if (!(this instanceof Document)) { return new Document(obj, schema, fields, skipId, skipInit); } if (isObject(schema) && !schema.instanceOfSchema) { schema = new Schema(schema); } // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id schema = this.schema || schema; // Generate ObjectId if it is missing, but it requires a scheme if (!this.schema && schema.options._id) { obj = obj || {}; if (obj._id === undefined) { obj._id = new ObjectId(); } } if (!schema) { throw new MongooseError.MissingSchemaError(); } this.$__setSchema(schema); NodeJSDocument.call(this, obj, fields, skipId, skipInit); applyHooks(this, schema, { decorateDoc: true }); // apply methods for (const m in schema.methods) { this[m] = schema.methods[m]; } // apply statics for (const s in schema.statics) { this[s] = schema.statics[s]; } } /*! * Inherit from the NodeJS document */ Document.prototype = Object.create(NodeJSDocument.prototype); Document.prototype.constructor = Document; /*! * ignore */ Document.events = new EventEmitter(); /*! * Browser doc exposes the event emitter API */ Document.$emitter = new EventEmitter(); ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', 'removeAllListeners', 'addListener'].forEach(function(emitterFn) { Document[emitterFn] = function() { return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); }; }); /*! * Module exports. */ Document.ValidationError = ValidationError; module.exports = exports = Document; },{"./document":268,"./error/index":278,"./helpers/isObject":308,"./helpers/model/applyHooks":310,"./schema":348,"./types/objectid":379,"events":253}],261:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const CastError = require('./error/cast'); const StrictModeError = require('./error/strict'); const Types = require('./schema/index'); const castTextSearch = require('./schema/operators/text'); const get = require('./helpers/get'); const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue'); const isOperator = require('./helpers/query/isOperator'); const util = require('util'); const isObject = require('./helpers/isObject'); const isMongooseObject = require('./helpers/isMongooseObject'); const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon']; /** * Handles internal casting for query filters. * * @param {Schema} schema * @param {Object} obj Object to cast * @param {Object} options the query options * @param {Query} context passed to setters * @api private */ module.exports = function cast(schema, obj, options, context) { if (Array.isArray(obj)) { throw new Error('Query filter must be an object, got an array ', util.inspect(obj)); } if (obj == null) { return obj; } // bson 1.x has the unfortunate tendency to remove filters that have a top-level // `_bsontype` property. But we should still allow ObjectIds because // `Collection#find()` has a special case to support `find(objectid)`. // Should remove this when we upgrade to bson 4.x. See gh-8222, gh-8268 if (obj.hasOwnProperty('_bsontype') && obj._bsontype !== 'ObjectID') { delete obj._bsontype; } if (schema != null && schema.discriminators != null && obj[schema.options.discriminatorKey] != null) { schema = getSchemaDiscriminatorByValue(schema, obj[schema.options.discriminatorKey]) || schema; } const paths = Object.keys(obj); let i = paths.length; let _keys; let any$conditionals; let schematype; let nested; let path; let type; let val; options = options || {}; while (i--) { path = paths[i]; val = obj[path]; if (path === '$or' || path === '$nor' || path === '$and') { if (!Array.isArray(val)) { throw new CastError('Array', val, path); } for (let k = 0; k < val.length; ++k) { if (val[k] == null || typeof val[k] !== 'object') { throw new CastError('Object', val[k], path + '.' + k); } val[k] = cast(schema, val[k], options, context); } } else if (path === '$where') { type = typeof val; if (type !== 'string' && type !== 'function') { throw new Error('Must have a string or function for $where'); } if (type === 'function') { obj[path] = val.toString(); } continue; } else if (path === '$elemMatch') { val = cast(schema, val, options, context); } else if (path === '$text') { val = castTextSearch(val, path); } else { if (!schema) { // no casting for Mixed types continue; } schematype = schema.path(path); // Check for embedded discriminator paths if (!schematype) { const split = path.split('.'); let j = split.length; while (j--) { const pathFirstHalf = split.slice(0, j).join('.'); const pathLastHalf = split.slice(j).join('.'); const _schematype = schema.path(pathFirstHalf); const discriminatorKey = get(_schematype, 'schema.options.discriminatorKey'); // gh-6027: if we haven't found the schematype but this path is // underneath an embedded discriminator and the embedded discriminator // key is in the query, use the embedded discriminator schema if (_schematype != null && get(_schematype, 'schema.discriminators') != null && discriminatorKey != null && pathLastHalf !== discriminatorKey) { const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey); if (discriminatorVal != null) { schematype = _schematype.schema.discriminators[discriminatorVal]. path(pathLastHalf); } } } } if (!schematype) { // Handle potential embedded array queries const split = path.split('.'); let j = split.length; let pathFirstHalf; let pathLastHalf; let remainingConds; // Find the part of the var path that is a path of the Schema while (j--) { pathFirstHalf = split.slice(0, j).join('.'); schematype = schema.path(pathFirstHalf); if (schematype) { break; } } // If a substring of the input path resolves to an actual real path... if (schematype) { // Apply the casting; similar code for $elemMatch in schema/array.js if (schematype.caster && schematype.caster.schema) { remainingConds = {}; pathLastHalf = split.slice(j).join('.'); remainingConds[pathLastHalf] = val; obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf]; } else { obj[path] = val; } continue; } if (isObject(val)) { // handle geo schemas that use object notation // { loc: { long: Number, lat: Number } let geo = ''; if (val.$near) { geo = '$near'; } else if (val.$nearSphere) { geo = '$nearSphere'; } else if (val.$within) { geo = '$within'; } else if (val.$geoIntersects) { geo = '$geoIntersects'; } else if (val.$geoWithin) { geo = '$geoWithin'; } if (geo) { const numbertype = new Types.Number('__QueryCasting__'); let value = val[geo]; if (val.$maxDistance != null) { val.$maxDistance = numbertype.castForQueryWrapper({ val: val.$maxDistance, context: context }); } if (val.$minDistance != null) { val.$minDistance = numbertype.castForQueryWrapper({ val: val.$minDistance, context: context }); } if (geo === '$within') { const withinType = value.$center || value.$centerSphere || value.$box || value.$polygon; if (!withinType) { throw new Error('Bad $within parameter: ' + JSON.stringify(val)); } value = withinType; } else if (geo === '$near' && typeof value.type === 'string' && Array.isArray(value.coordinates)) { // geojson; cast the coordinates value = value.coordinates; } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && value.$geometry && typeof value.$geometry.type === 'string' && Array.isArray(value.$geometry.coordinates)) { if (value.$maxDistance != null) { value.$maxDistance = numbertype.castForQueryWrapper({ val: value.$maxDistance, context: context }); } if (value.$minDistance != null) { value.$minDistance = numbertype.castForQueryWrapper({ val: value.$minDistance, context: context }); } if (isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ transform: false, virtuals: false }); } value = value.$geometry.coordinates; } else if (geo === '$geoWithin') { if (value.$geometry) { if (isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ virtuals: false }); } const geoWithinType = value.$geometry.type; if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) { throw new Error('Invalid geoJSON type for $geoWithin "' + geoWithinType + '", must be "Polygon" or "MultiPolygon"'); } value = value.$geometry.coordinates; } else { value = value.$box || value.$polygon || value.$center || value.$centerSphere; if (isMongooseObject(value)) { value = value.toObject({ virtuals: false }); } } } _cast(value, numbertype, context); continue; } } if (schema.nested[path]) { continue; } if (options.upsert && options.strict) { if (options.strict === 'throw') { throw new StrictModeError(path); } throw new StrictModeError(path, 'Path "' + path + '" is not in ' + 'schema, strict mode is `true`, and upsert is `true`.'); } else if (options.strictQuery === 'throw') { throw new StrictModeError(path, 'Path "' + path + '" is not in ' + 'schema and strictQuery is \'throw\'.'); } else if (options.strictQuery) { delete obj[path]; } } else if (val == null) { continue; } else if (val.constructor.name === 'Object') { any$conditionals = Object.keys(val).some(isOperator); if (!any$conditionals) { obj[path] = schematype.castForQueryWrapper({ val: val, context: context }); } else { const ks = Object.keys(val); let $cond; let k = ks.length; while (k--) { $cond = ks[k]; nested = val[$cond]; if ($cond === '$not') { if (nested && schematype && !schematype.caster) { _keys = Object.keys(nested); if (_keys.length && isOperator(_keys[0])) { for (const key in nested) { nested[key] = schematype.castForQueryWrapper({ $conditional: key, val: nested[key], context: context }); } } else { val[$cond] = schematype.castForQueryWrapper({ $conditional: $cond, val: nested, context: context }); } continue; } cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); } else { val[$cond] = schematype.castForQueryWrapper({ $conditional: $cond, val: nested, context: context }); } } } } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) { const casted = []; const valuesArray = val; for (const _val of valuesArray) { casted.push(schematype.castForQueryWrapper({ val: _val, context: context })); } obj[path] = { $in: casted }; } else { obj[path] = schematype.castForQueryWrapper({ val: val, context: context }); } } } return obj; }; function _cast(val, numbertype, context) { if (Array.isArray(val)) { val.forEach(function(item, i) { if (Array.isArray(item) || isObject(item)) { return _cast(item, numbertype, context); } val[i] = numbertype.castForQueryWrapper({ val: item, context: context }); }); } else { const nearKeys = Object.keys(val); let nearLen = nearKeys.length; while (nearLen--) { const nkey = nearKeys[nearLen]; const item = val[nkey]; if (Array.isArray(item) || isObject(item)) { _cast(item, numbertype, context); val[nkey] = item; } else { val[nkey] = numbertype.castForQuery({ val: item, context: context }); } } } } },{"./error/cast":276,"./error/strict":288,"./helpers/discriminator/getSchemaDiscriminatorByValue":298,"./helpers/get":303,"./helpers/isMongooseObject":307,"./helpers/isObject":308,"./helpers/query/isOperator":317,"./schema/index":356,"./schema/operators/text":365,"util":414}],262:[function(require,module,exports){ 'use strict'; const CastError = require('../error/cast'); /*! * Given a value, cast it to a boolean, or throw a `CastError` if the value * cannot be casted. `null` and `undefined` are considered valid. * * @param {Any} value * @param {String} [path] optional the path to set on the CastError * @return {Boolean|null|undefined} * @throws {CastError} if `value` is not one of the allowed values * @api private */ module.exports = function castBoolean(value, path) { if (module.exports.convertToTrue.has(value)) { return true; } if (module.exports.convertToFalse.has(value)) { return false; } if (value == null) { return value; } throw new CastError('boolean', value, path); }; module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']); module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']); },{"../error/cast":276}],263:[function(require,module,exports){ 'use strict'; const assert = require('assert'); module.exports = function castDate(value) { // Support empty string because of empty form values. Originally introduced // in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe if (value == null || value === '') { return null; } if (value instanceof Date) { assert.ok(!isNaN(value.valueOf())); return value; } let date; assert.ok(typeof value !== 'boolean'); if (value instanceof Number || typeof value === 'number') { date = new Date(value); } else if (typeof value === 'string' && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) { // string representation of milliseconds take this path date = new Date(Number(value)); } else if (typeof value.valueOf === 'function') { // support for moment.js. This is also the path strings will take because // strings have a `valueOf()` date = new Date(value.valueOf()); } else { // fallback date = new Date(value); } if (!isNaN(date.valueOf())) { return date; } assert.ok(false); }; },{"assert":89}],264:[function(require,module,exports){ (function (Buffer){ 'use strict'; const Decimal128Type = require('../types/decimal128'); const assert = require('assert'); module.exports = function castDecimal128(value) { if (value == null) { return value; } if (typeof value === 'object' && typeof value.$numberDecimal === 'string') { return Decimal128Type.fromString(value.$numberDecimal); } if (value instanceof Decimal128Type) { return value; } if (typeof value === 'string') { return Decimal128Type.fromString(value); } if (Buffer.isBuffer(value)) { return new Decimal128Type(value); } if (typeof value === 'number') { return Decimal128Type.fromString(String(value)); } if (typeof value.valueOf === 'function' && typeof value.valueOf() === 'string') { return Decimal128Type.fromString(value.valueOf()); } assert.ok(false); }; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../types/decimal128":374,"assert":89}],265:[function(require,module,exports){ 'use strict'; const assert = require('assert'); /*! * Given a value, cast it to a number, or throw a `CastError` if the value * cannot be casted. `null` and `undefined` are considered valid. * * @param {Any} value * @param {String} [path] optional the path to set on the CastError * @return {Boolean|null|undefined} * @throws {Error} if `value` is not one of the allowed values * @api private */ module.exports = function castNumber(val) { if (val == null) { return val; } if (val === '') { return null; } if (typeof val === 'string' || typeof val === 'boolean') { val = Number(val); } assert.ok(!isNaN(val)); if (val instanceof Number) { return val.valueOf(); } if (typeof val === 'number') { return val; } if (!Array.isArray(val) && typeof val.valueOf === 'function') { return Number(val.valueOf()); } if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { return Number(val); } assert.ok(false); }; },{"assert":89}],266:[function(require,module,exports){ 'use strict'; const ObjectId = require('../driver').get().ObjectId; const assert = require('assert'); module.exports = function castObjectId(value) { if (value == null) { return value; } if (value instanceof ObjectId) { return value; } if (value._id) { if (value._id instanceof ObjectId) { return value._id; } if (value._id.toString instanceof Function) { return new ObjectId(value._id.toString()); } } if (value.toString instanceof Function) { return new ObjectId(value.toString()); } assert.ok(false); }; },{"../driver":270,"assert":89}],267:[function(require,module,exports){ 'use strict'; const CastError = require('../error/cast'); /*! * Given a value, cast it to a string, or throw a `CastError` if the value * cannot be casted. `null` and `undefined` are considered valid. * * @param {Any} value * @param {String} [path] optional the path to set on the CastError * @return {string|null|undefined} * @throws {CastError} * @api private */ module.exports = function castString(value, path) { // If null or undefined if (value == null) { return value; } // handle documents being passed if (value._id && typeof value._id === 'string') { return value._id; } // Re: gh-647 and gh-3030, we're ok with casting using `toString()` // **unless** its the default Object.toString, because "[object Object]" // doesn't really qualify as useful data if (value.toString && value.toString !== Object.prototype.toString && !Array.isArray(value)) { return value.toString(); } throw new CastError('string', value, path); }; },{"../error/cast":276}],268:[function(require,module,exports){ (function (Buffer,process){ 'use strict'; /*! * Module dependencies. */ const EventEmitter = require('events').EventEmitter; const InternalCache = require('./internal'); const MongooseError = require('./error/index'); const MixedSchema = require('./schema/mixed'); const ObjectExpectedError = require('./error/objectExpected'); const ObjectParameterError = require('./error/objectParameter'); const ParallelValidateError = require('./error/parallelValidate'); const Schema = require('./schema'); const StrictModeError = require('./error/strict'); const ValidationError = require('./error/validation'); const ValidatorError = require('./error/validator'); const VirtualType = require('./virtualtype'); const promiseOrCallback = require('./helpers/promiseOrCallback'); const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths'); const compile = require('./helpers/document/compile').compile; const defineKey = require('./helpers/document/compile').defineKey; const flatten = require('./helpers/common').flatten; const get = require('./helpers/get'); const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath'); const handleSpreadDoc = require('./helpers/document/handleSpreadDoc'); const idGetter = require('./plugins/idGetter'); const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); const isExclusive = require('./helpers/projection/isExclusive'); const inspect = require('util').inspect; const internalToObjectOptions = require('./options').internalToObjectOptions; const mpath = require('mpath'); const queryhelpers = require('./queryhelpers'); const utils = require('./utils'); const isPromise = require('./helpers/isPromise'); const clone = utils.clone; const deepEqual = utils.deepEqual; const isMongooseObject = utils.isMongooseObject; const arrayAtomicsBackupSymbol = Symbol('mongoose.Array#atomicsBackup'); const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; const documentArrayParent = require('./helpers/symbols').documentArrayParent; const documentIsSelected = require('./helpers/symbols').documentIsSelected; const documentIsModified = require('./helpers/symbols').documentIsModified; const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths; const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol; const getSymbol = require('./helpers/symbols').getSymbol; const populateModelSymbol = require('./helpers/symbols').populateModelSymbol; const scopeSymbol = require('./helpers/symbols').scopeSymbol; let DocumentArray; let MongooseArray; let Embedded; const specialProperties = utils.specialProperties; /** * The core Mongoose document constructor. You should not call this directly, * the Mongoose [Model constructor](./api.html#Model) calls this for you. * * @param {Object} obj the values to set * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data * @param {Object} [options] various configuration options for the document * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document. * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose. * @event `save`: Emitted when the document is successfully saved * @api private */ function Document(obj, fields, skipId, options) { if (typeof skipId === 'object' && skipId != null) { options = skipId; skipId = options.skipId; } options = Object.assign({}, options); const defaults = get(options, 'defaults', true); options.defaults = defaults; // Support `browserDocument.js` syntax if (this.schema == null) { const _schema = utils.isObject(fields) && !fields.instanceOfSchema ? new Schema(fields) : fields; this.$__setSchema(_schema); fields = skipId; skipId = options; options = arguments[4] || {}; } this.$__ = new InternalCache; this.$__.emitter = new EventEmitter(); this.isNew = 'isNew' in options ? options.isNew : true; this.errors = undefined; this.$__.$options = options || {}; this.$locals = {}; this.$op = null; if (obj != null && typeof obj !== 'object') { throw new ObjectParameterError(obj, 'obj', 'Document'); } const schema = this.schema; if (typeof fields === 'boolean' || fields === 'throw') { this.$__.strictMode = fields; fields = undefined; } else { this.$__.strictMode = schema.options.strict; this.$__.selected = fields; } const requiredPaths = schema.requiredPaths(true); for (const path of requiredPaths) { this.$__.activePaths.require(path); } this.$__.emitter.setMaxListeners(0); let exclude = null; // determine if this doc is a result of a query with // excluded fields if (utils.isPOJO(fields)) { exclude = isExclusive(fields); } const hasIncludedChildren = exclude === false && fields ? $__hasIncludedChildren(fields) : {}; if (this._doc == null) { this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); // By default, defaults get applied **before** setting initial values // Re: gh-6155 if (defaults) { $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, { isNew: this.isNew }); } } if (obj) { // Skip set hooks if (this.$__original_set) { this.$__original_set(obj, undefined, true); } else { this.$set(obj, undefined, true); } if (obj instanceof Document) { this.isNew = obj.isNew; } } // Function defaults get applied **after** setting initial values so they // see the full doc rather than an empty one, unless they opt out. // Re: gh-3781, gh-6155 if (options.willInit && defaults) { EventEmitter.prototype.once.call(this, 'init', () => { $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { isNew: this.isNew }); }); } else if (defaults) { $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { isNew: this.isNew }); } this.$__._id = this._id; if (!this.$__.strictMode && obj) { const _this = this; const keys = Object.keys(this._doc); keys.forEach(function(key) { if (!(key in schema.tree)) { defineKey(key, null, _this); } }); } applyQueue(this); } /*! * Document exposes the NodeJS event emitter API, so you can use * `on`, `once`, etc. */ utils.each( ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', 'removeAllListeners', 'addListener'], function(emitterFn) { Document.prototype[emitterFn] = function() { return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); }; }); Document.prototype.constructor = Document; for (const i in EventEmitter.prototype) { Document[i] = EventEmitter.prototype[i]; } /** * The document's schema. * * @api public * @property schema * @memberOf Document * @instance */ Document.prototype.schema; /** * Empty object that you can use for storing properties on the document. This * is handy for passing data to middleware without conflicting with Mongoose * internals. * * ####Example: * * schema.pre('save', function() { * // Mongoose will set `isNew` to `false` if `save()` succeeds * this.$locals.wasNew = this.isNew; * }); * * schema.post('save', function() { * // Prints true if `isNew` was set before `save()` * console.log(this.$locals.wasNew); * }); * * @api public * @property $locals * @memberOf Document * @instance */ Object.defineProperty(Document.prototype, '$locals', { configurable: false, enumerable: false, writable: true }); /** * Boolean flag specifying if the document is new. * * @api public * @property isNew * @memberOf Document * @instance */ Document.prototype.isNew; /** * The string version of this documents _id. * * ####Note: * * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. * * new Schema({ name: String }, { id: false }); * * @api public * @see Schema options /docs/guide.html#options * @property id * @memberOf Document * @instance */ Document.prototype.id; /** * Hash containing current validation errors. * * @api public * @property errors * @memberOf Document * @instance */ Document.prototype.errors; /** * A string containing the current operation that Mongoose is executing * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. * * ####Example: * * const doc = new Model({ name: 'test' }); * doc.$op; // null * * const promise = doc.save(); * doc.$op; // 'save' * * await promise; * doc.$op; // null * * @api public * @property $op * @memberOf Document * @instance */ Document.prototype.$op; /*! * ignore */ function $__hasIncludedChildren(fields) { const hasIncludedChildren = {}; const keys = Object.keys(fields); for (const key of keys) { const parts = key.split('.'); const c = []; for (const part of parts) { c.push(part); hasIncludedChildren[c.join('.')] = 1; } } return hasIncludedChildren; } /*! * ignore */ function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) { const paths = Object.keys(doc.schema.paths); const plen = paths.length; for (let i = 0; i < plen; ++i) { let def; let curPath = ''; const p = paths[i]; if (p === '_id' && skipId) { continue; } const type = doc.schema.paths[p]; const path = p.indexOf('.') === -1 ? [p] : p.split('.'); const len = path.length; let included = false; let doc_ = doc._doc; for (let j = 0; j < len; ++j) { if (doc_ == null) { break; } const piece = path[j]; curPath += (!curPath.length ? '' : '.') + piece; if (exclude === true) { if (curPath in fields) { break; } } else if (exclude === false && fields && !included) { if (curPath in fields) { included = true; } else if (!hasIncludedChildren[curPath]) { break; } } if (j === len - 1) { if (doc_[piece] !== void 0) { break; } if (typeof type.defaultValue === 'function') { if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) { break; } if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) { break; } } else if (!isBeforeSetters) { // Non-function defaults should always run **before** setters continue; } if (pathsToSkip && pathsToSkip[curPath]) { break; } if (fields && exclude !== null) { if (exclude === true) { // apply defaults to all non-excluded fields if (p in fields) { continue; } try { def = type.getDefault(doc, false); } catch (err) { doc.invalidate(p, err); break; } if (typeof def !== 'undefined') { doc_[piece] = def; doc.$__.activePaths.default(p); } } else if (included) { // selected field try { def = type.getDefault(doc, false); } catch (err) { doc.invalidate(p, err); break; } if (typeof def !== 'undefined') { doc_[piece] = def; doc.$__.activePaths.default(p); } } } else { try { def = type.getDefault(doc, false); } catch (err) { doc.invalidate(p, err); break; } if (typeof def !== 'undefined') { doc_[piece] = def; doc.$__.activePaths.default(p); } } } else { doc_ = doc_[piece]; } } } } /** * Builds the default doc structure * * @param {Object} obj * @param {Object} [fields] * @param {Boolean} [skipId] * @api private * @method $__buildDoc * @memberOf Document * @instance */ Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { const doc = {}; const paths = Object.keys(this.schema.paths). // Don't build up any paths that are underneath a map, we don't know // what the keys will be filter(p => !p.includes('$*')); const plen = paths.length; let ii = 0; for (; ii < plen; ++ii) { const p = paths[ii]; if (p === '_id') { if (skipId) { continue; } if (obj && '_id' in obj) { continue; } } const path = p.split('.'); const len = path.length; const last = len - 1; let curPath = ''; let doc_ = doc; let included = false; for (let i = 0; i < len; ++i) { const piece = path[i]; curPath += (!curPath.length ? '' : '.') + piece; // support excluding intermediary levels if (exclude === true) { if (curPath in fields) { break; } } else if (exclude === false && fields && !included) { if (curPath in fields) { included = true; } else if (!hasIncludedChildren[curPath]) { break; } } if (i < last) { doc_ = doc_[piece] || (doc_[piece] = {}); } } } this._doc = doc; }; /*! * Converts to POJO when you use the document for querying */ Document.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; /** * Initializes the document without setters or marking anything modified. * * Called internally after a document is returned from mongodb. Normally, * you do **not** need to call this function on your own. * * This function triggers `init` [middleware](/docs/middleware.html). * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous). * * @param {Object} doc document returned by mongo * @api public * @memberOf Document * @instance */ Document.prototype.init = function(doc, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = null; } this.$__init(doc, opts); if (fn) { fn(null, this); } return this; }; /*! * ignore */ Document.prototype.$__init = function(doc, opts) { this.isNew = false; this.$init = true; opts = opts || {}; // handle docs with populated paths // If doc._id is not null or undefined if (doc._id != null && opts.populated && opts.populated.length) { const id = String(doc._id); for (const item of opts.populated) { if (item.isVirtual) { this.populated(item.path, utils.getValue(item.path, doc), item); } else { this.populated(item.path, item._docs[id], item); } if (item._childDocs == null) { continue; } for (const child of item._childDocs) { if (child == null || child.$__ == null) { continue; } child.$__.parent = this; } } } init(this, doc, this._doc, opts); markArraySubdocsPopulated(this, opts.populated); this.emit('init', this); this.constructor.emit('init', this); this.$__._id = this._id; return this; }; /*! * If populating a path within a document array, make sure each * subdoc within the array knows its subpaths are populated. * * ####Example: * const doc = await Article.findOne().populate('comments.author'); * doc.comments[0].populated('author'); // Should be set */ function markArraySubdocsPopulated(doc, populated) { if (doc._id == null || populated == null || populated.length === 0) { return; } const id = String(doc._id); for (const item of populated) { if (item.isVirtual) { continue; } const path = item.path; const pieces = path.split('.'); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join('.'); const rest = pieces.slice(i + 1).join('.'); const val = doc.get(subpath); if (val == null) { continue; } if (val.isMongooseDocumentArray) { for (let j = 0; j < val.length; ++j) { val[j].populated(rest, item._docs[id] == null ? [] : item._docs[id][j], item); } break; } } } } /*! * Init helper. * * @param {Object} self document instance * @param {Object} obj raw mongodb doc * @param {Object} doc object we are initializing * @api private */ function init(self, obj, doc, opts, prefix) { prefix = prefix || ''; const keys = Object.keys(obj); const len = keys.length; let schema; let path; let i; let index = 0; while (index < len) { _init(index++); } function _init(index) { i = keys[index]; path = prefix + i; schema = self.schema.path(path); // Should still work if not a model-level discriminator, but should not be // necessary. This is *only* to catch the case where we queried using the // base model and the discriminated model has a projection if (self.schema.$isRootDiscriminator && !self.isSelected(path)) { return; } if (!schema && utils.isPOJO(obj[i])) { // assume nested object if (!doc[i]) { doc[i] = {}; } init(self, obj[i], doc[i], opts, path + '.'); } else if (!schema) { doc[i] = obj[i]; } else { if (obj[i] === null) { doc[i] = schema._castNullish(null); } else if (obj[i] !== undefined) { const intCache = obj[i].$__ || {}; const wasPopulated = intCache.wasPopulated || null; if (schema && !wasPopulated) { try { doc[i] = schema.cast(obj[i], self, true); } catch (e) { self.invalidate(e.path, new ValidatorError({ path: e.path, message: e.message, type: 'cast', value: e.value, reason: e })); } } else { doc[i] = obj[i]; } } // mark as hydrated if (!self.isModified(path)) { self.$__.activePaths.init(path); } } } } /** * Sends an update command with this document `_id` as the query selector. * * ####Example: * * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); * * ####Valid options: * * - same as in [Model.update](#model_Model.update) * * @see Model.update #model_Model.update * @param {Object} doc * @param {Object} options * @param {Function} callback * @return {Query} * @api public * @memberOf Document * @instance */ Document.prototype.update = function update() { const args = utils.args(arguments); args.unshift({ _id: this._id }); const query = this.constructor.update.apply(this.constructor, args); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } return query; }; /** * Sends an updateOne command with this document `_id` as the query selector. * * ####Example: * * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); * * ####Valid options: * * - same as in [Model.updateOne](#model_Model.updateOne) * * @see Model.updateOne #model_Model.updateOne * @param {Object} doc * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Function} callback * @return {Query} * @api public * @memberOf Document * @instance */ Document.prototype.updateOne = function updateOne(doc, options, callback) { const query = this.constructor.updateOne({ _id: this._id }, doc, options); query._pre(cb => { this.constructor._middleware.execPre('updateOne', this, [this], cb); }); query._post(cb => { this.constructor._middleware.execPost('updateOne', this, [this], {}, cb); }); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } if (callback != null) { return query.exec(callback); } return query; }; /** * Sends a replaceOne command with this document `_id` as the query selector. * * ####Valid options: * * - same as in [Model.replaceOne](#model_Model.replaceOne) * * @see Model.replaceOne #model_Model.replaceOne * @param {Object} doc * @param {Object} options * @param {Function} callback * @return {Query} * @api public * @memberOf Document * @instance */ Document.prototype.replaceOne = function replaceOne() { const args = utils.args(arguments); args.unshift({ _id: this._id }); return this.constructor.replaceOne.apply(this.constructor, args); }; /** * Getter/setter around the session associated with this document. Used to * automatically set `session` if you `save()` a doc that you got from a * query with an associated session. * * ####Example: * * const session = MyModel.startSession(); * const doc = await MyModel.findOne().session(session); * doc.$session() === session; // true * doc.$session(null); * doc.$session() === null; // true * * If this is a top-level document, setting the session propagates to all child * docs. * * @param {ClientSession} [session] overwrite the current session * @return {ClientSession} * @method $session * @api public * @memberOf Document */ Document.prototype.$session = function $session(session) { if (arguments.length === 0) { return this.$__.session; } this.$__.session = session; if (!this.ownerDocument) { const subdocs = this.$__getAllSubdocs(); for (const child of subdocs) { child.$session(session); } } return session; }; /** * Overwrite all values in this document with the values of `obj`, except * for immutable properties. Behaves similarly to `set()`, except for it * unsets all properties that aren't in `obj`. * * @param {Object} obj the object to overwrite this document with * @method overwrite * @name overwrite * @memberOf Document * @instance * @api public */ Document.prototype.overwrite = function overwrite(obj) { const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); for (const key of keys) { if (key === '_id') { continue; } // Explicitly skip version key if (this.schema.options.versionKey && key === this.schema.options.versionKey) { continue; } if (this.schema.options.discriminatorKey && key === this.schema.options.discriminatorKey) { continue; } this.$set(key, obj[key]); } return this; }; /** * Alias for `set()`, used internally to avoid conflicts * * @param {String|Object} path path or object of key/vals to set * @param {Any} val the value to set * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes * @param {Object} [options] optionally specify options that modify the behavior of the set * @method $set * @name $set * @memberOf Document * @instance * @api public */ Document.prototype.$set = function $set(path, val, type, options) { if (utils.isPOJO(type)) { options = type; type = undefined; } options = options || {}; const merge = options.merge; const adhoc = type && type !== true; const constructing = type === true; let adhocs; let keys; let i = 0; let pathtype; let key; let prefix; const strict = 'strict' in options ? options.strict : this.$__.strictMode; if (adhoc) { adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); adhocs[path] = this.schema.interpretAsType(path, type, this.schema.options); } if (path == null) { const _ = path; path = val; val = _; } else if (typeof path !== 'string') { // new Document({ key: val }) if (path instanceof Document) { if (path.$__isNested) { path = path.toObject(); } else { path = path._doc; } } prefix = val ? val + '.' : ''; keys = Object.keys(path); const len = keys.length; // `_skipMinimizeTopLevel` is because we may have deleted the top-level // nested key to ensure key order. const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false); if (len === 0 && _skipMinimizeTopLevel) { delete options._skipMinimizeTopLevel; if (val) { this.$set(val, {}); } return this; } for (let i = 0; i < len; ++i) { key = keys[i]; const pathName = prefix + key; pathtype = this.schema.pathType(pathName); // On initial set, delete any nested keys if we're going to overwrite // them to ensure we keep the user's key order. if (type === true && !prefix && path[key] != null && pathtype === 'nested' && this._doc[key] != null && Object.keys(this._doc[key]).length === 0) { delete this._doc[key]; // Make sure we set `{}` back even if we minimize re: gh-8565 options = Object.assign({}, options, { _skipMinimizeTopLevel: true }); } const someCondition = typeof path[key] === 'object' && !utils.isNativeObject(path[key]) && !utils.isMongooseType(path[key]) && path[key] != null && pathtype !== 'virtual' && pathtype !== 'real' && pathtype !== 'adhocOrUndefined' && !(this.$__path(pathName) instanceof MixedSchema) && !(this.schema.paths[pathName] && this.schema.paths[pathName].options && this.schema.paths[pathName].options.ref); if (someCondition) { this.$__.$setCalled.add(prefix + key); this.$set(path[key], prefix + key, constructing, options); } else if (strict) { // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039) if (constructing && path[key] === void 0 && this.get(pathName) !== void 0) { continue; } if (pathtype === 'adhocOrUndefined') { pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); } if (pathtype === 'real' || pathtype === 'virtual') { // Check for setting single embedded schema to document (gh-3535) let p = path[key]; if (this.schema.paths[pathName] && this.schema.paths[pathName].$isSingleNested && path[key] instanceof Document) { p = p.toObject({ virtuals: false, transform: false }); } this.$set(prefix + key, p, constructing, options); } else if (pathtype === 'nested' && path[key] instanceof Document) { this.$set(prefix + key, path[key].toObject({ transform: false }), constructing, options); } else if (strict === 'throw') { if (pathtype === 'nested') { throw new ObjectExpectedError(key, path[key]); } else { throw new StrictModeError(key); } } } else if (path[key] !== void 0) { this.$set(prefix + key, path[key], constructing, options); } } return this; } else { this.$__.$setCalled.add(path); } let pathType = this.schema.pathType(path); if (pathType === 'adhocOrUndefined') { pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true }); } // Assume this is a Mongoose document that was copied into a POJO using // `Object.assign()` or `{...doc}` val = handleSpreadDoc(val); if (pathType === 'nested' && val) { if (typeof val === 'object' && val != null) { const hasPriorVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path); if (this.$__.savedState != null && !this.isNew && !this.$__.savedState.hasOwnProperty(path)) { const priorVal = this.$__getValue(path); this.$__.savedState[path] = priorVal; const keys = Object.keys(priorVal || {}); for (const key of keys) { this.$__.savedState[path + '.' + key] = priorVal[key]; } } if (!merge) { this.$__setValue(path, null); cleanModifiedSubpaths(this, path); } else { return this.$set(val, path, constructing); } const keys = Object.keys(val); this.$__setValue(path, {}); for (const key of keys) { this.$set(path + '.' + key, val[key], constructing); } if (hasPriorVal && utils.deepEqual(this.$__.savedState[path], val)) { this.unmarkModified(path); } else { this.markModified(path); } cleanModifiedSubpaths(this, path, { skipDocArrays: true }); return this; } this.invalidate(path, new MongooseError.CastError('Object', val, path)); return this; } let schema; const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); // Might need to change path for top-level alias if (typeof this.schema.aliases[parts[0]] == 'string') { parts[0] = this.schema.aliases[parts[0]]; } if (pathType === 'adhocOrUndefined' && strict) { // check for roots that are Mixed types let mixed; for (i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join('.'); // If path is underneath a virtual, bypass everything and just set it. if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') { mpath.set(path, val, this); return this; } schema = this.schema.path(subpath); if (schema == null) { continue; } if (schema instanceof MixedSchema) { // allow changes to sub paths of mixed types mixed = true; break; } } if (schema == null) { // Check for embedded discriminators schema = getEmbeddedDiscriminatorPath(this, path); } if (!mixed && !schema) { if (strict === 'throw') { throw new StrictModeError(path); } return this; } } else if (pathType === 'virtual') { schema = this.schema.virtualpath(path); schema.applySetters(val, this); return this; } else { schema = this.$__path(path); } // gh-4578, if setting a deeply nested path that doesn't exist yet, create it let cur = this._doc; let curPath = ''; for (i = 0; i < parts.length - 1; ++i) { cur = cur[parts[i]]; curPath += (curPath.length > 0 ? '.' : '') + parts[i]; if (!cur) { this.$set(curPath, {}); // Hack re: gh-5800. If nested field is not selected, it probably exists // so `MongoError: cannot use the part (nested of nested.num) to // traverse the element ({nested: null})` is not likely. If user gets // that error, its their fault for now. We should reconsider disallowing // modifying not selected paths for 6.x if (!this.isSelected(curPath)) { this.unmarkModified(curPath); } cur = this.$__getValue(curPath); } } let pathToMark; // When using the $set operator the path to the field must already exist. // Else mongodb throws: "LEFT_SUBFIELD only supports Object" if (parts.length <= 1) { pathToMark = path; } else { for (i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join('.'); if (this.get(subpath, null, { getters: false }) === null) { pathToMark = subpath; break; } } if (!pathToMark) { pathToMark = path; } } // if this doc is being constructed we should not trigger getters const priorVal = (() => { if (this.$__.$options.priorDoc != null) { return this.$__.$options.priorDoc.$__getValue(path); } if (constructing) { return void 0; } return this.$__getValue(path); })(); if (!schema) { this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); return this; } // If overwriting a subdocument path, make sure to clear out // any errors _before_ setting, so new errors that happen // get persisted. Re: #9080 if (schema.$isSingleNested || schema.$isMongooseArray) { _markValidSubpaths(this, path); } if (schema.$isSingleNested && val != null && merge) { if (val instanceof Document) { val = val.toObject({ virtuals: false, transform: false }); } const keys = Object.keys(val); for (const key of keys) { this.$set(path + '.' + key, val[key], constructing, options); } return this; } let shouldSet = true; try { // If the user is trying to set a ref path to a document with // the correct model name, treat it as populated const refMatches = (() => { if (schema.options == null) { return false; } if (!(val instanceof Document)) { return false; } const model = val.constructor; // Check ref const ref = schema.options.ref; if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { return true; } // Check refPath const refPath = schema.options.refPath; if (refPath == null) { return false; } const modelName = val.get(refPath); return modelName === model.modelName || modelName === model.baseModelName; })(); let didPopulate = false; if (refMatches && val instanceof Document) { this.populated(path, val._id, { [populateModelSymbol]: val.constructor }); didPopulate = true; } let popOpts; if (schema.options && Array.isArray(schema.options[this.schema.options.typeKey]) && schema.options[this.schema.options.typeKey].length && schema.options[this.schema.options.typeKey][0].ref && _isManuallyPopulatedArray(val, schema.options[this.schema.options.typeKey][0].ref)) { if (this.ownerDocument) { popOpts = { [populateModelSymbol]: val[0].constructor }; this.ownerDocument().populated(this.$__fullPath(path), val.map(function(v) { return v._id; }), popOpts); } else { popOpts = { [populateModelSymbol]: val[0].constructor }; this.populated(path, val.map(function(v) { return v._id; }), popOpts); } didPopulate = true; } if (this.schema.singleNestedPaths[path] == null) { // If this path is underneath a single nested schema, we'll call the setter // later in `$__set()` because we don't take `_doc` when we iterate through // a single nested doc. That's to make sure we get the correct context. // Otherwise we would double-call the setter, see gh-7196. val = schema.applySetters(val, this, false, priorVal); } if (schema.$isMongooseDocumentArray && Array.isArray(val) && val.length > 0 && val[0] != null && val[0].$__ != null && val[0].$__.populated != null) { const populatedPaths = Object.keys(val[0].$__.populated); for (const populatedPath of populatedPaths) { this.populated(path + '.' + populatedPath, val.map(v => v.populated(populatedPath)), val[0].$__.populated[populatedPath].options); } didPopulate = true; } if (!didPopulate && this.$__.populated) { // If this array partially contains populated documents, convert them // all to ObjectIds re: #8443 if (Array.isArray(val) && this.$__.populated[path]) { for (let i = 0; i < val.length; ++i) { if (val[i] instanceof Document) { val[i] = val[i]._id; } } } delete this.$__.populated[path]; } if (schema.$isSingleNested && val != null) { _checkImmutableSubpaths(val, schema, priorVal); } this.$markValid(path); } catch (e) { if (e instanceof MongooseError.StrictModeError && e.isImmutableError) { this.invalidate(path, e); } else if (e instanceof MongooseError.CastError) { this.invalidate(e.path, e); if (e.$originalErrorPath) { this.invalidate(path, new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath)); } } else { this.invalidate(path, new MongooseError.CastError(schema.instance, val, path, e)); } shouldSet = false; } if (shouldSet) { this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); if (this.$__.savedState != null) { if (!this.isNew && !this.$__.savedState.hasOwnProperty(path)) { this.$__.savedState[path] = priorVal; } else if (this.$__.savedState.hasOwnProperty(path) && utils.deepEqual(val, this.$__.savedState[path])) { this.unmarkModified(path); } } } if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { cleanModifiedSubpaths(this, path); } return this; }; /*! * ignore */ function _isManuallyPopulatedArray(val, ref) { if (!Array.isArray(val)) { return false; } if (val.length === 0) { return false; } for (const el of val) { if (!(el instanceof Document)) { return false; } const modelName = el.constructor.modelName; if (modelName == null) { return false; } if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { return false; } } return true; } /** * Sets the value of a path, or many paths. * * ####Example: * * // path, value * doc.set(path, value) * * // object * doc.set({ * path : value * , path2 : { * path : value * } * }) * * // on-the-fly cast to number * doc.set(path, value, Number) * * // on-the-fly cast to string * doc.set(path, value, String) * * // changing strict mode behavior * doc.set(path, value, { strict: false }); * * @param {String|Object} path path or object of key/vals to set * @param {Any} val the value to set * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes * @param {Object} [options] optionally specify options that modify the behavior of the set * @api public * @method set * @memberOf Document * @instance */ Document.prototype.set = Document.prototype.$set; /** * Determine if we should mark this change as modified. * * @return {Boolean} * @api private * @method $__shouldModify * @memberOf Document * @instance */ Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) { if (this.isNew) { return true; } // Re: the note about gh-7196, `val` is the raw value without casting or // setters if the full path is under a single nested subdoc because we don't // want to double run setters. So don't set it as modified. See gh-7264. if (this.schema.singleNestedPaths[path] != null) { return false; } if (val === void 0 && !this.isSelected(path)) { // when a path is not selected in a query, its initial // value will be undefined. return true; } if (val === void 0 && path in this.$__.activePaths.states.default) { // we're just unsetting the default value which was never saved return false; } // gh-3992: if setting a populated field to a doc, don't mark modified // if they have the same _id if (this.populated(path) && val instanceof Document && deepEqual(val._id, priorVal)) { return false; } if (!deepEqual(val, priorVal || utils.getValue(path, this))) { return true; } if (!constructing && val !== null && val !== undefined && path in this.$__.activePaths.states.default && deepEqual(val, schema.getDefault(this, constructing))) { // a path with a default was $unset on the server // and the user is setting it to the same value again return true; } return false; }; /** * Handles the actual setting of the value and marking the path modified if appropriate. * * @api private * @method $__set * @memberOf Document * @instance */ Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) { Embedded = Embedded || require('./types/embedded'); const shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts, schema, val, priorVal); const _this = this; if (shouldModify) { this.markModified(pathToMark); // handle directly setting arrays (gh-1126) MongooseArray || (MongooseArray = require('./types/array')); if (val && val.isMongooseArray) { val._registerAtomic('$set', val); // Update embedded document parent references (gh-5189) if (val.isMongooseDocumentArray) { val.forEach(function(item) { item && item.__parentArray && (item.__parentArray = val); }); } // Small hack for gh-1638: if we're overwriting the entire array, ignore // paths that were modified before the array overwrite this.$__.activePaths.forEach(function(modifiedPath) { if (modifiedPath.startsWith(path + '.')) { _this.$__.activePaths.ignore(modifiedPath); } }); } } let obj = this._doc; let i = 0; const l = parts.length; let cur = ''; for (; i < l; i++) { const next = i + 1; const last = next === l; cur += (cur ? '.' + parts[i] : parts[i]); if (specialProperties.has(parts[i])) { return; } if (last) { if (obj instanceof Map) { obj.set(parts[i], val); } else { obj[parts[i]] = val; } } else { if (utils.isPOJO(obj[parts[i]])) { obj = obj[parts[i]]; } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { obj = obj[parts[i]]; } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { obj = obj[parts[i]]; } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { obj = obj[parts[i]]; } else { obj[parts[i]] = obj[parts[i]] || {}; obj = obj[parts[i]]; } } } }; /** * Gets a raw value from a path (no getters) * * @param {String} path * @api private */ Document.prototype.$__getValue = function(path) { return utils.getValue(path, this._doc); }; /** * Sets a raw value for a path (no casting, setters, transformations) * * @param {String} path * @param {Object} value * @api private */ Document.prototype.$__setValue = function(path, val) { utils.setValue(path, val, this._doc); return this; }; /** * Returns the value of a path. * * ####Example * * // path * doc.get('age') // 47 * * // dynamic casting to a string * doc.get('age', String) // "47" * * @param {String} path * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes * @param {Object} [options] * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value * @api public */ Document.prototype.get = function(path, type, options) { let adhoc; options = options || {}; if (type) { adhoc = this.schema.interpretAsType(path, type, this.schema.options); } let schema = this.$__path(path); if (schema == null) { schema = this.schema.virtualpath(path); } if (schema instanceof MixedSchema) { const virtual = this.schema.virtualpath(path); if (virtual != null) { schema = virtual; } } const pieces = path.split('.'); let obj = this._doc; if (schema instanceof VirtualType) { return schema.applyGetters(void 0, this); } // Might need to change path for top-level alias if (typeof this.schema.aliases[pieces[0]] == 'string') { pieces[0] = this.schema.aliases[pieces[0]]; } for (let i = 0, l = pieces.length; i < l; i++) { if (obj && obj._doc) { obj = obj._doc; } if (obj == null) { obj = void 0; } else if (obj instanceof Map) { obj = obj.get(pieces[i], { getters: false }); } else if (i === l - 1) { obj = utils.getValue(pieces[i], obj); } else { obj = obj[pieces[i]]; } } if (adhoc) { obj = adhoc.cast(obj); } if (schema != null && options.getters !== false) { obj = schema.applyGetters(obj, this); } else if (this.schema.nested[path] && options.virtuals) { // Might need to apply virtuals if this is a nested path return applyVirtuals(this, utils.clone(obj) || {}, { path: path }); } return obj; }; /*! * ignore */ Document.prototype[getSymbol] = Document.prototype.get; /** * Returns the schematype for the given `path`. * * @param {String} path * @api private * @method $__path * @memberOf Document * @instance */ Document.prototype.$__path = function(path) { const adhocs = this.$__.adhocPaths; const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; if (adhocType) { return adhocType; } return this.schema.path(path); }; /** * Marks the path as having pending changes to write to the db. * * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ * * ####Example: * * doc.mixed.type = 'changed'; * doc.markModified('mixed.type'); * doc.save() // changes to mixed.type are now persisted * * @param {String} path the path to mark modified * @param {Document} [scope] the scope to run validators with * @api public */ Document.prototype.markModified = function(path, scope) { this.$__.activePaths.modify(path); if (scope != null && !this.ownerDocument) { this.$__.pathsToScopes[path] = scope; } }; /** * Clears the modified state on the specified path. * * ####Example: * * doc.foo = 'bar'; * doc.unmarkModified('foo'); * doc.save(); // changes to foo will not be persisted * * @param {String} path the path to unmark modified * @api public */ Document.prototype.unmarkModified = function(path) { this.$__.activePaths.init(path); delete this.$__.pathsToScopes[path]; }; /** * Don't run validation on this path or persist changes to this path. * * ####Example: * * doc.foo = null; * doc.$ignore('foo'); * doc.save(); // changes to foo will not be persisted and validators won't be run * * @memberOf Document * @instance * @method $ignore * @param {String} path the path to ignore * @api public */ Document.prototype.$ignore = function(path) { this.$__.activePaths.ignore(path); }; /** * Returns the list of paths that have been directly modified. A direct * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`. * * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()` * because a child of `a` was directly modified. * * ####Example * const schema = new Schema({ foo: String, nested: { bar: String } }); * const Model = mongoose.model('Test', schema); * await Model.create({ foo: 'original', nested: { bar: 'original' } }); * * const doc = await Model.findOne(); * doc.nested.bar = 'modified'; * doc.directModifiedPaths(); // ['nested.bar'] * doc.modifiedPaths(); // ['nested', 'nested.bar'] * * @return {Array} * @api public */ Document.prototype.directModifiedPaths = function() { return Object.keys(this.$__.activePaths.states.modify); }; /** * Returns true if the given path is nullish or only contains empty objects. * Useful for determining whether this subdoc will get stripped out by the * [minimize option](/docs/guide.html#minimize). * * ####Example: * const schema = new Schema({ nested: { foo: String } }); * const Model = mongoose.model('Test', schema); * const doc = new Model({}); * doc.$isEmpty('nested'); // true * doc.nested.$isEmpty(); // true * * doc.nested.foo = 'bar'; * doc.$isEmpty('nested'); // false * doc.nested.$isEmpty(); // false * * @memberOf Document * @instance * @api public * @method $isEmpty * @return {Boolean} */ Document.prototype.$isEmpty = function(path) { const isEmptyOptions = { minimize: true, virtuals: false, getters: false, transform: false }; if (arguments.length > 0) { const v = this.get(path); if (v == null) { return true; } if (typeof v !== 'object') { return false; } if (utils.isPOJO(v)) { return _isEmpty(v); } return Object.keys(v.toObject(isEmptyOptions)).length === 0; } return Object.keys(this.toObject(isEmptyOptions)).length === 0; }; function _isEmpty(v) { if (v == null) { return true; } if (typeof v !== 'object' || Array.isArray(v)) { return false; } for (const key of Object.keys(v)) { if (!_isEmpty(v[key])) { return false; } } return true; } /** * Returns the list of paths that have been modified. * * @param {Object} [options] * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. * @return {Array} * @api public */ Document.prototype.modifiedPaths = function(options) { options = options || {}; const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); const _this = this; return directModifiedPaths.reduce(function(list, path) { const parts = path.split('.'); list = list.concat(parts.reduce(function(chains, part, i) { return chains.concat(parts.slice(0, i).concat(part).join('.')); }, []).filter(function(chain) { return (list.indexOf(chain) === -1); })); if (!options.includeChildren) { return list; } let cur = _this.get(path); if (cur != null && typeof cur === 'object') { if (cur._doc) { cur = cur._doc; } if (Array.isArray(cur)) { const len = cur.length; for (let i = 0; i < len; ++i) { if (list.indexOf(path + '.' + i) === -1) { list.push(path + '.' + i); if (cur[i] != null && cur[i].$__) { const modified = cur[i].modifiedPaths(); for (const childPath of modified) { list.push(path + '.' + i + '.' + childPath); } } } } } else { Object.keys(cur). filter(function(key) { return list.indexOf(path + '.' + key) === -1; }). forEach(function(key) { list.push(path + '.' + key); }); } } return list; }, []); }; Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths; /** * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path * in this document is modified. * * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. * * ####Example * * doc.set('documents.0.title', 'changed'); * doc.isModified() // true * doc.isModified('documents') // true * doc.isModified('documents.0.title') // true * doc.isModified('documents otherProp') // true * doc.isDirectModified('documents') // false * * @param {String} [path] optional * @return {Boolean} * @api public */ Document.prototype.isModified = function(paths, modifiedPaths) { if (paths) { if (!Array.isArray(paths)) { paths = paths.split(' '); } const modified = modifiedPaths || this[documentModifiedPaths](); const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); const isModifiedChild = paths.some(function(path) { return !!~modified.indexOf(path); }); return isModifiedChild || paths.some(function(path) { return directModifiedPaths.some(function(mod) { return mod === path || path.startsWith(mod + '.'); }); }); } return this.$__.activePaths.some('modify'); }; Document.prototype[documentIsModified] = Document.prototype.isModified; /** * Checks if a path is set to its default. * * ####Example * * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); * const m = new MyModel(); * m.$isDefault('name'); // true * * @memberOf Document * @instance * @method $isDefault * @param {String} [path] * @return {Boolean} * @api public */ Document.prototype.$isDefault = function(path) { if (path == null) { return this.$__.activePaths.some('default'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.default.hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.states.default.hasOwnProperty(path)); }; /** * Getter/setter, determines whether the document was removed or not. * * ####Example: * product.remove(function (err, product) { * product.$isDeleted(); // true * product.remove(); // no-op, doesn't send anything to the db * * product.$isDeleted(false); * product.$isDeleted(); // false * product.remove(); // will execute a remove against the db * }) * * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted * @return {Boolean} whether mongoose thinks this doc is deleted. * @method $isDeleted * @memberOf Document * @instance * @api public */ Document.prototype.$isDeleted = function(val) { if (arguments.length === 0) { return !!this.$__.isDeleted; } this.$__.isDeleted = !!val; return this; }; /** * Returns true if `path` was directly set and modified, else false. * * ####Example * * doc.set('documents.0.title', 'changed'); * doc.isDirectModified('documents.0.title') // true * doc.isDirectModified('documents') // false * * @param {String|Array} path * @return {Boolean} * @api public */ Document.prototype.isDirectModified = function(path) { if (path == null) { return this.$__.activePaths.some('modify'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.modify.hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.states.modify.hasOwnProperty(path)); }; /** * Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. * * @param {String} path * @return {Boolean} * @api public */ Document.prototype.isInit = function(path) { if (path == null) { return this.$__.activePaths.some('init'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.states.init.hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.states.init.hasOwnProperty(path)); }; /** * Checks if `path` was selected in the source query which initialized this document. * * ####Example * * Thing.findOne().select('name').exec(function (err, doc) { * doc.isSelected('name') // true * doc.isSelected('age') // false * }) * * @param {String|Array} path * @return {Boolean} * @api public */ Document.prototype.isSelected = function isSelected(path) { if (this.$__.selected == null) { return true; } if (path === '_id') { return this.$__.selected._id !== 0; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(p => this.isSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (const cur of paths) { if (cur === '_id') { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (path in this.$__.selected) { return inclusive; } const pathDot = path + '.'; for (const cur of paths) { if (cur === '_id') { continue; } if (cur.startsWith(pathDot)) { return inclusive || cur !== pathDot; } if (pathDot.startsWith(cur + '.')) { return inclusive; } } return !inclusive; }; Document.prototype[documentIsSelected] = Document.prototype.isSelected; /** * Checks if `path` was explicitly selected. If no projection, always returns * true. * * ####Example * * Thing.findOne().select('nested.name').exec(function (err, doc) { * doc.isDirectSelected('nested.name') // true * doc.isDirectSelected('nested.otherName') // false * doc.isDirectSelected('nested') // false * }) * * @param {String} path * @return {Boolean} * @api public */ Document.prototype.isDirectSelected = function isDirectSelected(path) { if (this.$__.selected == null) { return true; } if (path === '_id') { return this.$__.selected._id !== 0; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(p => this.isDirectSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (const cur of paths) { if (cur === '_id') { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (this.$__.selected.hasOwnProperty(path)) { return inclusive; } return !inclusive; }; /** * Executes registered validation rules for this document. * * ####Note: * * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. * * ####Example: * * doc.validate(function (err) { * if (err) handleError(err); * else // validation passed * }); * * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. * @param {Object} [options] internal options * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths. * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred * @return {Promise} Promise * @api public */ Document.prototype.validate = function(pathsToValidate, options, callback) { let parallelValidate; this.$op = 'validate'; if (this.ownerDocument != null) { // Skip parallel validate check for subdocuments } else if (this.$__.validating) { parallelValidate = new ParallelValidateError(this, { parentStack: options && options.parentStack, conflictStack: this.$__.validating.stack }); } else { this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack }); } if (typeof pathsToValidate === 'function') { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === 'function') { callback = options; options = pathsToValidate; pathsToValidate = null; } return promiseOrCallback(callback, cb => { if (parallelValidate != null) { return cb(parallelValidate); } this.$__validate(pathsToValidate, options, (error) => { this.$op = null; cb(error); }); }, this.constructor.events); }; /*! * ignore */ function _evaluateRequiredFunctions(doc) { Object.keys(doc.$__.activePaths.states.require).forEach(path => { const p = doc.schema.path(path); if (p != null && typeof p.originalRequiredValue === 'function') { doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc); } }); } /*! * ignore */ function _getPathsToValidate(doc) { const skipSchemaValidators = {}; _evaluateRequiredFunctions(doc); // only validate required fields when necessary let paths = new Set(Object.keys(doc.$__.activePaths.states.require).filter(function(path) { if (!doc.isSelected(path) && !doc.isModified(path)) { return false; } if (path in doc.$__.cachedRequired) { return doc.$__.cachedRequired[path]; } return true; })); Object.keys(doc.$__.activePaths.states.init).forEach(addToPaths); Object.keys(doc.$__.activePaths.states.modify).forEach(addToPaths); Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths); function addToPaths(p) { paths.add(p); } const subdocs = doc.$__getAllSubdocs(); const modifiedPaths = doc.modifiedPaths(); for (const subdoc of subdocs) { if (subdoc.$basePath) { // Remove child paths for now, because we'll be validating the whole // subdoc for (const p of paths) { if (p === null || p.startsWith(subdoc.$basePath + '.')) { paths.delete(p); } } if (doc.isModified(subdoc.$basePath, modifiedPaths) && !doc.isDirectModified(subdoc.$basePath) && !doc.$isDefault(subdoc.$basePath)) { paths.add(subdoc.$basePath); skipSchemaValidators[subdoc.$basePath] = true; } } } // from here on we're not removing items from paths // gh-661: if a whole array is modified, make sure to run validation on all // the children as well for (const path of paths) { const _pathType = doc.schema.path(path); if (!_pathType || !_pathType.$isMongooseArray || // To avoid potential performance issues, skip doc arrays whose children // are not required. `getPositionalPathType()` may be slow, so avoid // it unless we have a case of #6364 (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) { continue; } const val = doc.$__getValue(path); _pushNestedArrayPaths(val, paths, path); } function _pushNestedArrayPaths(val, paths, path) { if (val != null) { const numElements = val.length; for (let j = 0; j < numElements; ++j) { if (Array.isArray(val[j])) { _pushNestedArrayPaths(val[j], paths, path + '.' + j); } else { paths.add(path + '.' + j); } } } } const flattenOptions = { skipArrays: true }; for (const pathToCheck of paths) { if (doc.schema.nested[pathToCheck]) { let _v = doc.$__getValue(pathToCheck); if (isMongooseObject(_v)) { _v = _v.toObject({ transform: false }); } const flat = flatten(_v, pathToCheck, flattenOptions, doc.schema); Object.keys(flat).forEach(addToPaths); } } for (const path of paths) { // Single nested paths (paths embedded under single nested subdocs) will // be validated on their own when we call `validate()` on the subdoc itself. // Re: gh-8468 if (doc.schema.singleNestedPaths.hasOwnProperty(path)) { paths.delete(path); continue; } const _pathType = doc.schema.path(path); if (!_pathType || !_pathType.$isSchemaMap) { continue; } const val = doc.$__getValue(path); if (val == null) { continue; } for (const key of val.keys()) { paths.add(path + '.' + key); } } paths = Array.from(paths); return [paths, skipSchemaValidators]; } /*! * ignore */ Document.prototype.$__validate = function(pathsToValidate, options, callback) { if (typeof pathsToValidate === 'function') { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === 'function') { callback = options; options = null; } const hasValidateModifiedOnlyOption = options && (typeof options === 'object') && ('validateModifiedOnly' in options); let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly; } const _this = this; const _complete = () => { let validationError = this.$__.validationError; this.$__.validationError = undefined; if (shouldValidateModifiedOnly && validationError != null) { // Remove any validation errors that aren't from modified paths const errors = Object.keys(validationError.errors); for (const errPath of errors) { if (!this.isModified(errPath)) { delete validationError.errors[errPath]; } } if (Object.keys(validationError.errors).length === 0) { validationError = void 0; } } this.$__.cachedRequired = {}; this.emit('validate', _this); this.constructor.emit('validate', _this); this.$__.validating = null; if (validationError) { for (const key in validationError.errors) { // Make sure cast errors persist if (!this[documentArrayParent] && validationError.errors[key] instanceof MongooseError.CastError) { this.invalidate(key, validationError.errors[key]); } } return validationError; } }; // only validate required fields when necessary const pathDetails = _getPathsToValidate(this); let paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.isModified(path)) : pathDetails[0]; const skipSchemaValidators = pathDetails[1]; if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } if (paths.length === 0) { return process.nextTick(function() { const error = _complete(); if (error) { return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { callback(error); }); } callback(null, _this); }); } const validated = {}; let total = 0; const complete = function() { const error = _complete(); if (error) { return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { callback(error); }); } callback(null, _this); }; const validatePath = function(path) { if (path == null || validated[path]) { return; } validated[path] = true; total++; process.nextTick(function() { const schemaType = _this.schema.path(path); if (!schemaType) { return --total || complete(); } // If user marked as invalid or there was a cast error, don't validate if (!_this.$isValid(path)) { --total || complete(); return; } let val = _this.$__getValue(path); // If you `populate()` and get back a null value, required validators // shouldn't fail (gh-8018). We should always fall back to the populated // value. let pop; if (val == null && (pop = _this.populated(path))) { val = pop; } const scope = path in _this.$__.pathsToScopes ? _this.$__.pathsToScopes[path] : _this; const doValidateOptions = { skipSchemaValidators: skipSchemaValidators[path], path: path }; schemaType.doValidate(val, function(err) { if (err && (!schemaType.$isMongooseDocumentArray || err.$isArrayValidatorError)) { if (schemaType.$isSingleNested && err instanceof ValidationError && schemaType.schema.options.storeSubdocValidationError === false) { return --total || complete(); } _this.invalidate(path, err, undefined, true); } --total || complete(); }, scope, doValidateOptions); }); }; const numPaths = paths.length; for (let i = 0; i < numPaths; ++i) { validatePath(paths[i]); } }; /*! * ignore */ function _handlePathsToValidate(paths, pathsToValidate) { const _pathsToValidate = new Set(pathsToValidate); const parentPaths = new Map([]); for (const path of pathsToValidate) { if (path.indexOf('.') === -1) { continue; } const pieces = path.split('.'); let cur = pieces[0]; for (let i = 1; i < pieces.length; ++i) { // Since we skip subpaths under single nested subdocs to // avoid double validation, we need to add back the // single nested subpath if the user asked for it (gh-8626) parentPaths.set(cur, path); cur = cur + '.' + pieces[i]; } } const ret = []; for (const path of paths) { if (_pathsToValidate.has(path)) { ret.push(path); } else if (parentPaths.has(path)) { ret.push(parentPaths.get(path)); } } return ret; } /** * Executes registered validation rules (skipping asynchronous validators) for this document. * * ####Note: * * This method is useful if you need synchronous validation. * * ####Example: * * const err = doc.validateSync(); * if (err) { * handleError(err); * } else { * // validation passed * } * * @param {Array|string} pathsToValidate only validate the given paths * @param {Object} [options] options for validation * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. * @api public */ Document.prototype.validateSync = function(pathsToValidate, options) { const _this = this; const hasValidateModifiedOnlyOption = options && (typeof options === 'object') && ('validateModifiedOnly' in options); let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly; } if (typeof pathsToValidate === 'string') { pathsToValidate = pathsToValidate.split(' '); } // only validate required fields when necessary const pathDetails = _getPathsToValidate(this); let paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.isModified(path)) : pathDetails[0]; const skipSchemaValidators = pathDetails[1]; if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } const validating = {}; paths.forEach(function(path) { if (validating[path]) { return; } validating[path] = true; const p = _this.schema.path(path); if (!p) { return; } if (!_this.$isValid(path)) { return; } const val = _this.$__getValue(path); const err = p.doValidateSync(val, _this, { skipSchemaValidators: skipSchemaValidators[path], path: path }); if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) { if (p.$isSingleNested && err instanceof ValidationError && p.schema.options.storeSubdocValidationError === false) { return; } _this.invalidate(path, err, undefined, true); } }); const err = _this.$__.validationError; _this.$__.validationError = undefined; _this.emit('validate', _this); _this.constructor.emit('validate', _this); if (err) { for (const key in err.errors) { // Make sure cast errors persist if (err.errors[key] instanceof MongooseError.CastError) { _this.invalidate(key, err.errors[key]); } } } return err; }; /** * Marks a path as invalid, causing validation to fail. * * The `errorMsg` argument will become the message of the `ValidationError`. * * The `value` argument (if passed) will be available through the `ValidationError.value` property. * * doc.invalidate('size', 'must be less than 20', 14); * doc.validate(function (err) { * console.log(err) * // prints * { message: 'Validation failed', * name: 'ValidationError', * errors: * { size: * { message: 'must be less than 20', * name: 'ValidatorError', * path: 'size', * type: 'user defined', * value: 14 } } } * }) * * @param {String} path the field to invalidate. For array elements, use the `array.i.field` syntax, where `i` is the 0-based index in the array. * @param {String|Error} errorMsg the error which states the reason `path` was invalid * @param {Object|String|Number|any} value optional invalid value * @param {String} [kind] optional `kind` property for the error * @return {ValidationError} the current ValidationError, with all currently invalidated paths * @api public */ Document.prototype.invalidate = function(path, err, val, kind) { if (!this.$__.validationError) { this.$__.validationError = new ValidationError(this); } if (this.$__.validationError.errors[path]) { return; } if (!err || typeof err === 'string') { err = new ValidatorError({ path: path, message: err, type: kind || 'user defined', value: val }); } if (this.$__.validationError === err) { return this.$__.validationError; } this.$__.validationError.addError(path, err); return this.$__.validationError; }; /** * Marks a path as valid, removing existing validation errors. * * @param {String} path the field to mark as valid * @api public * @memberOf Document * @instance * @method $markValid */ Document.prototype.$markValid = function(path) { if (!this.$__.validationError || !this.$__.validationError.errors[path]) { return; } delete this.$__.validationError.errors[path]; if (Object.keys(this.$__.validationError.errors).length === 0) { this.$__.validationError = null; } }; /*! * ignore */ function _markValidSubpaths(doc, path) { if (!doc.$__.validationError) { return; } const keys = Object.keys(doc.$__.validationError.errors); for (const key of keys) { if (key.startsWith(path + '.')) { delete doc.$__.validationError.errors[key]; } } if (Object.keys(doc.$__.validationError.errors).length === 0) { doc.$__.validationError = null; } } /*! * ignore */ function _checkImmutableSubpaths(subdoc, schematype, priorVal) { const schema = schematype.schema; if (schema == null) { return; } for (const key of Object.keys(schema.paths)) { const path = schema.paths[key]; if (path.$immutableSetter == null) { continue; } const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key); // Calling immutableSetter with `oldVal` even though it expects `newVal` // is intentional. That's because `$immutableSetter` compares its param // to the current value. path.$immutableSetter.call(subdoc, oldVal); } } /** * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case. * * ####Example: * * product.sold = Date.now(); * product = await product.save(); * * If save is successful, the returned promise will fulfill with the document * saved. * * ####Example: * * const newProduct = await product.save(); * newProduct === product; // true * * @param {Object} [options] options optional options * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. * @param {Function} [fn] optional callback * @method save * @memberOf Document * @instance * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. * @api public * @see middleware http://mongoosejs.com/docs/middleware.html */ /** * Checks if a path is invalid * * @param {String|Array} path the field to check * @method $isValid * @memberOf Document * @instance * @api private */ Document.prototype.$isValid = function(path) { if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) { return true; } if (path == null) { return false; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(p => this.$__.validationError.errors[p] == null); } return this.$__.validationError.errors[path] == null; }; /** * Resets the internal modified state of this document. * * @api private * @return {Document} * @method $__reset * @memberOf Document * @instance */ Document.prototype.$__reset = function reset() { let _this = this; DocumentArray || (DocumentArray = require('./types/documentarray')); this.$__.activePaths .map('init', 'modify', function(i) { return _this.$__getValue(i); }) .filter(function(val) { return val && val instanceof Array && val.isMongooseDocumentArray && val.length; }) .forEach(function(array) { let i = array.length; while (i--) { const doc = array[i]; if (!doc) { continue; } doc.$__reset(); } _this.$__.activePaths.init(array.$path()); array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol]; array[arrayAtomicsSymbol] = {}; }); this.$__.activePaths. map('init', 'modify', function(i) { return _this.$__getValue(i); }). filter(function(val) { return val && val.$isSingleNested; }). forEach(function(doc) { doc.$__reset(); _this.$__.activePaths.init(doc.$basePath); }); // clear atomics this.$__dirty().forEach(function(dirt) { const type = dirt.value; if (type && type[arrayAtomicsSymbol]) { type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol]; type[arrayAtomicsSymbol] = {}; } }); this.$__.backup = {}; this.$__.backup.activePaths = { modify: Object.assign({}, this.$__.activePaths.states.modify), default: Object.assign({}, this.$__.activePaths.states.default) }; this.$__.backup.validationError = this.$__.validationError; this.$__.backup.errors = this.errors; // Clear 'dirty' cache this.$__.activePaths.clear('modify'); this.$__.activePaths.clear('default'); this.$__.validationError = undefined; this.errors = undefined; _this = this; this.schema.requiredPaths().forEach(function(path) { _this.$__.activePaths.require(path); }); return this; }; /*! * ignore */ Document.prototype.$__undoReset = function $__undoReset() { if (this.$__.backup == null || this.$__.backup.activePaths == null) { return; } this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify; this.$__.activePaths.states.default = this.$__.backup.activePaths.default; this.$__.validationError = this.$__.backup.validationError; this.errors = this.$__.backup.errors; for (const dirt of this.$__dirty()) { const type = dirt.value; if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) { type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; } } for (const subdoc of this.$__getAllSubdocs()) { subdoc.$__undoReset(); } }; /** * Returns this documents dirty paths / vals. * * @api private * @method $__dirty * @memberOf Document * @instance */ Document.prototype.$__dirty = function() { const _this = this; let all = this.$__.activePaths.map('modify', function(path) { return { path: path, value: _this.$__getValue(path), schema: _this.$__path(path) }; }); // gh-2558: if we had to set a default and the value is not undefined, // we have to save as well all = all.concat(this.$__.activePaths.map('default', function(path) { if (path === '_id' || _this.$__getValue(path) == null) { return; } return { path: path, value: _this.$__getValue(path), schema: _this.$__path(path) }; })); // Sort dirty paths in a flat hierarchy. all.sort(function(a, b) { return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); }); // Ignore "foo.a" if "foo" is dirty already. const minimal = []; let lastPath; let top; all.forEach(function(item) { if (!item) { return; } if (lastPath == null || item.path.indexOf(lastPath) !== 0) { lastPath = item.path + '.'; minimal.push(item); top = item; } else if (top != null && top.value != null && top.value[arrayAtomicsSymbol] != null && top.value.hasAtomics()) { // special case for top level MongooseArrays // the `top` array itself and a sub path of `top` are being modified. // the only way to honor all of both modifications is through a $set // of entire array. top.value[arrayAtomicsSymbol] = {}; top.value[arrayAtomicsSymbol].$set = top.value; } }); top = lastPath = null; return minimal; }; /** * Assigns/compiles `schema` into this documents prototype. * * @param {Schema} schema * @api private * @method $__setSchema * @memberOf Document * @instance */ Document.prototype.$__setSchema = function(schema) { schema.plugin(idGetter, { deduplicate: true }); compile(schema.tree, this, undefined, schema.options); // Apply default getters if virtual doesn't have any (gh-6262) for (const key of Object.keys(schema.virtuals)) { schema.virtuals[key]._applyDefaultGetters(); } this.schema = schema; this[documentSchemaSymbol] = schema; }; /** * Get active path that were changed and are arrays * * @api private * @method $__getArrayPathsToValidate * @memberOf Document * @instance */ Document.prototype.$__getArrayPathsToValidate = function() { DocumentArray || (DocumentArray = require('./types/documentarray')); // validate all document arrays. return this.$__.activePaths .map('init', 'modify', function(i) { return this.$__getValue(i); }.bind(this)) .filter(function(val) { return val && val instanceof Array && val.isMongooseDocumentArray && val.length; }).reduce(function(seed, array) { return seed.concat(array); }, []) .filter(function(doc) { return doc; }); }; /** * Get all subdocs (by bfs) * * @api private * @method $__getAllSubdocs * @memberOf Document * @instance */ Document.prototype.$__getAllSubdocs = function() { DocumentArray || (DocumentArray = require('./types/documentarray')); Embedded = Embedded || require('./types/embedded'); function docReducer(doc, seed, path) { let val = doc; if (path) { if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) { val = doc._doc[path]; } else { val = doc[path]; } } if (val instanceof Embedded) { seed.push(val); } else if (val instanceof Map) { seed = Array.from(val.keys()).reduce(function(seed, path) { return docReducer(val.get(path), seed, null); }, seed); } else if (val && val.$isSingleNested) { seed = Object.keys(val._doc).reduce(function(seed, path) { return docReducer(val._doc, seed, path); }, seed); seed.push(val); } else if (val && val.isMongooseDocumentArray) { val.forEach(function _docReduce(doc) { if (!doc || !doc._doc) { return; } seed = Object.keys(doc._doc).reduce(function(seed, path) { return docReducer(doc._doc, seed, path); }, seed); if (doc instanceof Embedded) { seed.push(doc); } }); } else if (val instanceof Document && val.$__isNested) { seed = Object.keys(val).reduce(function(seed, path) { return docReducer(val, seed, path); }, seed); } return seed; } const _this = this; const subDocs = Object.keys(this._doc).reduce(function(seed, path) { return docReducer(_this, seed, path); }, []); return subDocs; }; /*! * Runs queued functions */ function applyQueue(doc) { const q = doc.schema && doc.schema.callQueue; if (!q.length) { return; } for (const pair of q) { if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { doc[pair[0]].apply(doc, pair[1]); } } } /*! * ignore */ Document.prototype.$__handleReject = function handleReject(err) { // emit on the Model if listening if (this.listeners('error').length) { this.emit('error', err); } else if (this.constructor.listeners && this.constructor.listeners('error').length) { this.constructor.emit('error', err); } }; /** * Internal helper for toObject() and toJSON() that doesn't manipulate options * * @api private * @method $toObject * @memberOf Document * @instance */ Document.prototype.$toObject = function(options, json) { let defaultOptions = { transform: true, flattenDecimals: true }; const path = json ? 'toJSON' : 'toObject'; const baseOptions = get(this, 'constructor.base.options.' + path, {}); const schemaOptions = get(this, 'schema.options', {}); // merge base default options with Schema's set default options if available. // `clone` is necessary here because `utils.options` directly modifies the second input. defaultOptions = utils.options(defaultOptions, clone(baseOptions)); defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {})); // If options do not exist or is not an object, set it to empty object options = utils.isPOJO(options) ? clone(options) : {}; options._calledWithOptions = options._calledWithOptions || clone(options); if (!('flattenMaps' in options)) { options.flattenMaps = defaultOptions.flattenMaps; } let _minimize; if (options._calledWithOptions.minimize != null) { _minimize = options.minimize; } else if (defaultOptions.minimize != null) { _minimize = defaultOptions.minimize; } else { _minimize = schemaOptions.minimize; } // The original options that will be passed to `clone()`. Important because // `clone()` will recursively call `$toObject()` on embedded docs, so we // need the original options the user passed in, plus `_isNested` and // `_parentOptions` for checking whether we need to depopulate. const cloneOptions = Object.assign(utils.clone(options), { _isNested: true, json: json, minimize: _minimize }); if (utils.hasUserDefinedProperty(options, 'getters')) { cloneOptions.getters = options.getters; } if (utils.hasUserDefinedProperty(options, 'virtuals')) { cloneOptions.virtuals = options.virtuals; } const depopulate = options.depopulate || get(options, '_parentOptions.depopulate', false); // _isNested will only be true if this is not the top level document, we // should never depopulate if (depopulate && options._isNested && this.$__.wasPopulated) { // populated paths that we set to a document return clone(this._id, cloneOptions); } // merge default options with input options. options = utils.options(defaultOptions, options); options._isNested = true; options.json = json; options.minimize = _minimize; cloneOptions._parentOptions = options; cloneOptions._skipSingleNestedGetters = true; const gettersOptions = Object.assign({}, cloneOptions); gettersOptions._skipSingleNestedGetters = false; // remember the root transform function // to save it from being overwritten by sub-transform functions const originalTransform = options.transform; let ret = clone(this._doc, cloneOptions) || {}; if (options.getters) { applyGetters(this, ret, gettersOptions); if (options.minimize) { ret = minimize(ret) || {}; } } if (options.virtuals || (options.getters && options.virtuals !== false)) { applyVirtuals(this, ret, gettersOptions, options); } if (options.versionKey === false && this.schema.options.versionKey) { delete ret[this.schema.options.versionKey]; } let transform = options.transform; // In the case where a subdocument has its own transform function, we need to // check and see if the parent has a transform (options.transform) and if the // child schema has a transform (this.schema.options.toObject) In this case, // we need to adjust options.transform to be the child schema's transform and // not the parent schema's if (transform) { applySchemaTypeTransforms(this, ret); } if (options.useProjection) { omitDeselectedFields(this, ret); } if (transform === true || (schemaOptions.toObject && transform)) { const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject; if (opts) { transform = (typeof options.transform === 'function' ? options.transform : opts.transform); } } else { options.transform = originalTransform; } if (typeof transform === 'function') { const xformed = transform(this, ret, options); if (typeof xformed !== 'undefined') { ret = xformed; } } return ret; }; /** * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). * * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. * * ####Options: * * - `getters` apply all getters (path and virtual getters), defaults to false * - `aliases` apply all aliases if `virtuals=true`, defaults to true * - `virtuals` apply virtual getters (can override `getters` option), defaults to false * - `minimize` remove empty objects, defaults to true * - `transform` a transform function to apply to the resulting document before returning * - `depopulate` depopulate any populated paths, replacing them with their original refs, defaults to false * - `versionKey` whether to include the version key, defaults to true * - `flattenMaps` convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false * - `useProjection` set to `true` to omit fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. * * ####Getters/Virtuals * * Example of only applying path getters * * doc.toObject({ getters: true, virtuals: false }) * * Example of only applying virtual getters * * doc.toObject({ virtuals: true }) * * Example of applying both path and virtual getters * * doc.toObject({ getters: true }) * * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. * * schema.set('toObject', { virtuals: true }) * * ####Transform * * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. * * Transform functions receive three arguments * * function (doc, ret, options) {} * * - `doc` The mongoose document which is being converted * - `ret` The plain object representation which has been converted * - `options` The options in use (either schema options or the options passed inline) * * ####Example * * // specify the transform schema option * if (!schema.options.toObject) schema.options.toObject = {}; * schema.options.toObject.transform = function (doc, ret, options) { * // remove the _id of every document before returning the result * delete ret._id; * return ret; * } * * // without the transformation in the schema * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } * * // with the transformation * doc.toObject(); // { name: 'Wreck-it Ralph' } * * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: * * if (!schema.options.toObject) schema.options.toObject = {}; * schema.options.toObject.transform = function (doc, ret, options) { * return { movie: ret.name } * } * * // without the transformation in the schema * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } * * // with the transformation * doc.toObject(); // { movie: 'Wreck-it Ralph' } * * _Note: if a transform function returns `undefined`, the return value will be ignored._ * * Transformations may also be applied inline, overridding any transform set in the options: * * function xform (doc, ret, options) { * return { inline: ret.name, custom: true } * } * * // pass the transform as an inline option * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } * * If you want to skip transformations, use `transform: false`: * * schema.options.toObject.hide = '_id'; * schema.options.toObject.transform = function (doc, ret, options) { * if (options.hide) { * options.hide.split(' ').forEach(function (prop) { * delete ret[prop]; * }); * } * return ret; * } * * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } * * If you pass a transform in `toObject()` options, Mongoose will apply the transform * to [subdocuments](/docs/subdocs.html) in addition to the top-level document. * Similarly, `transform: false` skips transforms for all subdocuments. * Note that this is behavior is different for transforms defined in the schema: * if you define a transform in `schema.options.toObject.transform`, that transform * will **not** apply to subdocuments. * * const memberSchema = new Schema({ name: String, email: String }); * const groupSchema = new Schema({ members: [memberSchema], name: String, email }); * const Group = mongoose.model('Group', groupSchema); * * const doc = new Group({ * name: 'Engineering', * email: 'dev@mongoosejs.io', * members: [{ name: 'Val', email: 'val@mongoosejs.io' }] * }); * * // Removes `email` from both top-level document **and** array elements * // { name: 'Engineering', members: [{ name: 'Val' }] } * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } }); * * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions. * * See [schema options](/docs/guide.html#toObject) for some more details. * * _During save, no custom options are applied to the document before being sent to the database._ * * @param {Object} [options] * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. * @return {Object} js object * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html * @api public * @memberOf Document * @instance */ Document.prototype.toObject = function(options) { return this.$toObject(options); }; /*! * Minimizes an object, removing undefined values and empty objects * * @param {Object} object to minimize * @return {Object} */ function minimize(obj) { const keys = Object.keys(obj); let i = keys.length; let hasKeys; let key; let val; while (i--) { key = keys[i]; val = obj[key]; if (utils.isObject(val) && !Buffer.isBuffer(val)) { obj[key] = minimize(val); } if (undefined === obj[key]) { delete obj[key]; continue; } hasKeys = true; } return hasKeys ? obj : undefined; } /*! * Applies virtuals properties to `json`. */ function applyVirtuals(self, json, options, toObjectOptions) { const schema = self.schema; const paths = Object.keys(schema.virtuals); let i = paths.length; const numPaths = i; let path; let assignPath; let cur = self._doc; let v; const aliases = get(toObjectOptions, 'aliases', true); if (!cur) { return json; } options = options || {}; for (i = 0; i < numPaths; ++i) { path = paths[i]; // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })` if (!aliases && schema.aliases.hasOwnProperty(path)) { continue; } // We may be applying virtuals to a nested object, for example if calling // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`, // will be a trailing substring of the `path`. assignPath = path; if (options.path != null) { if (!path.startsWith(options.path + '.')) { continue; } assignPath = path.substr(options.path.length + 1); } const parts = assignPath.split('.'); v = clone(self.get(path), options); if (v === void 0) { continue; } const plen = parts.length; cur = json; for (let j = 0; j < plen - 1; ++j) { cur[parts[j]] = cur[parts[j]] || {}; cur = cur[parts[j]]; } cur[parts[plen - 1]] = v; } return json; } /*! * Applies virtuals properties to `json`. * * @param {Document} self * @param {Object} json * @return {Object} `json` */ function applyGetters(self, json, options) { const schema = self.schema; const paths = Object.keys(schema.paths); let i = paths.length; let path; let cur = self._doc; let v; if (!cur) { return json; } while (i--) { path = paths[i]; const parts = path.split('.'); const plen = parts.length; const last = plen - 1; let branch = json; let part; cur = self._doc; if (!self.isSelected(path)) { continue; } for (let ii = 0; ii < plen; ++ii) { part = parts[ii]; v = cur[part]; if (ii === last) { const val = self.get(path); branch[part] = clone(val, options); } else if (v == null) { if (part in cur) { branch[part] = v; } break; } else { branch = branch[part] || (branch[part] = {}); } cur = v; } } return json; } /*! * Applies schema type transforms to `json`. * * @param {Document} self * @param {Object} json * @return {Object} `json` */ function applySchemaTypeTransforms(self, json) { const schema = self.schema; const paths = Object.keys(schema.paths || {}); const cur = self._doc; if (!cur) { return json; } for (const path of paths) { const schematype = schema.paths[path]; if (typeof schematype.options.transform === 'function') { const val = self.get(path); const transformedValue = schematype.options.transform.call(self, val); throwErrorIfPromise(path, transformedValue); utils.setValue(path, transformedValue, json); } else if (schematype.$embeddedSchemaType != null && typeof schematype.$embeddedSchemaType.options.transform === 'function') { const vals = [].concat(self.get(path)); const transform = schematype.$embeddedSchemaType.options.transform; for (let i = 0; i < vals.length; ++i) { const transformedValue = transform.call(self, vals[i]); vals[i] = transformedValue; throwErrorIfPromise(path, transformedValue); } json[path] = vals; } } return json; } function throwErrorIfPromise(path, transformedValue) { if (isPromise(transformedValue)) { throw new Error('`transform` function must be synchronous, but the transform on path `' + path + '` returned a promise.'); } } /*! * ignore */ function omitDeselectedFields(self, json) { const schema = self.schema; const paths = Object.keys(schema.paths || {}); const cur = self._doc; if (!cur) { return json; } let selected = self.$__.selected; if (selected === void 0) { selected = {}; queryhelpers.applyPaths(selected, schema); } if (selected == null || Object.keys(selected).length === 0) { return json; } for (const path of paths) { if (selected[path] != null && !selected[path]) { delete json[path]; } } return json; } /** * The return value of this method is used in calls to JSON.stringify(doc). * * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. * * schema.set('toJSON', { virtuals: true }) * * See [schema options](/docs/guide.html#toJSON) for details. * * @param {Object} options * @return {Object} * @see Document#toObject #document_Document-toObject * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html * @api public * @memberOf Document * @instance */ Document.prototype.toJSON = function(options) { return this.$toObject(options, true); }; /** * If this document is a subdocument or populated document, returns the document's * parent. Returns `undefined` otherwise. * * @api public * @method parent * @memberOf Document * @instance */ Document.prototype.parent = function() { return this.$__.parent; }; /** * Alias for `parent()`. If this document is a subdocument or populated * document, returns the document's parent. Returns `undefined` otherwise. * * @api public * @method $parent * @memberOf Document * @instance */ Document.prototype.$parent = Document.prototype.parent; /** * Helper for console.log * * @api public * @method inspect * @memberOf Document * @instance */ Document.prototype.inspect = function(options) { const isPOJO = utils.isPOJO(options); let opts; if (isPOJO) { opts = options; opts.minimize = false; } const ret = this.toObject(opts); if (ret == null) { // If `toObject()` returns null, `this` is still an object, so if `inspect()` // prints out null this can cause some serious confusion. See gh-7942. return 'MongooseDocument { ' + ret + ' }'; } return ret; }; if (inspect.custom) { /*! * Avoid Node deprecation warning DEP0079 */ Document.prototype[inspect.custom] = Document.prototype.inspect; } /** * Helper for console.log * * @api public * @method toString * @memberOf Document * @instance */ Document.prototype.toString = function() { const ret = this.inspect(); if (typeof ret === 'string') { return ret; } return inspect(ret); }; /** * Returns true if this document is equal to another document. * * Documents are considered equal when they have matching `_id`s, unless neither * document has an `_id`, in which case this function falls back to using * `deepEqual()`. * * @param {Document} doc a document to compare * @return {Boolean} * @api public * @memberOf Document * @instance */ Document.prototype.equals = function(doc) { if (!doc) { return false; } const tid = this.$__getValue('_id'); const docid = doc.$__ != null ? doc.$__getValue('_id') : doc; if (!tid && !docid) { return deepEqual(this, doc); } return tid && tid.equals ? tid.equals(docid) : tid === docid; }; /** * Populates document references, executing the `callback` when complete. * If you want to use promises instead, use this function with * [`execPopulate()`](#document_Document-execPopulate) * * ####Example: * * doc * .populate('company') * .populate({ * path: 'notes', * match: /airline/, * select: 'text', * model: 'modelName' * options: opts * }, function (err, user) { * assert(doc._id === user._id) // the document itself is passed * }) * * // summary * doc.populate(path) // not executed * doc.populate(options); // not executed * doc.populate(path, callback) // executed * doc.populate(options, callback); // executed * doc.populate(callback); // executed * doc.populate(options).execPopulate() // executed, returns promise * * * ####NOTE: * * Population does not occur unless a `callback` is passed *or* you explicitly * call `execPopulate()`. * Passing the same path a second time will overwrite the previous path options. * See [Model.populate()](#model_Model.populate) for explaination of options. * * @see Model.populate #model_Model.populate * @see Document.execPopulate #document_Document-execPopulate * @param {String|Object} [path] The path to populate or an options object * @param {Function} [callback] When passed, population is invoked * @api public * @return {Document} this * @memberOf Document * @instance */ Document.prototype.populate = function populate() { if (arguments.length === 0) { return this; } const pop = this.$__.populate || (this.$__.populate = {}); const args = utils.args(arguments); let fn; if (typeof args[args.length - 1] === 'function') { fn = args.pop(); } // allow `doc.populate(callback)` if (args.length) { // use hash to remove duplicate paths const res = utils.populate.apply(null, args); for (const populateOptions of res) { pop[populateOptions.path] = populateOptions; } } if (fn) { const paths = utils.object.vals(pop); this.$__.populate = undefined; let topLevelModel = this.constructor; if (this.$__isNested) { topLevelModel = this.$__[scopeSymbol].constructor; const nestedPath = this.$__.nestedPath; paths.forEach(function(populateOptions) { populateOptions.path = nestedPath + '.' + populateOptions.path; }); } // Use `$session()` by default if the document has an associated session // See gh-6754 if (this.$session() != null) { const session = this.$session(); paths.forEach(path => { if (path.options == null) { path.options = { session: session }; return; } if (!('session' in path.options)) { path.options.session = session; } }); } topLevelModel.populate(this, paths, fn); } return this; }; /** * Explicitly executes population and returns a promise. Useful for promises integration. * * ####Example: * * const promise = doc. * populate('company'). * populate({ * path: 'notes', * match: /airline/, * select: 'text', * model: 'modelName' * options: opts * }). * execPopulate(); * * // summary * doc.execPopulate().then(resolve, reject); * * // you can also use doc.execPopulate(options) as a shorthand for * // doc.populate(options).execPopulate() * * * ####Example: * const promise = doc.execPopulate({ path: 'company', select: 'employees' }); * * // summary * promise.then(resolve,reject); * * @see Document.populate #document_Document-populate * @api public * @param {Function} [callback] optional callback. If specified, a promise will **not** be returned * @return {Promise} promise that resolves to the document when population is done * @memberOf Document * @instance */ Document.prototype.execPopulate = function(callback) { const isUsingShorthand = callback != null && typeof callback !== 'function'; if (isUsingShorthand) { return this.populate.apply(this, arguments).execPopulate(); } return promiseOrCallback(callback, cb => { this.populate(cb); }, this.constructor.events); }; /** * Gets _id(s) used during population of the given `path`. * * ####Example: * * Model.findOne().populate('author').exec(function (err, doc) { * console.log(doc.author.name) // Dr.Seuss * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' * }) * * If the path was not populated, returns `undefined`. * * @param {String} path * @return {Array|ObjectId|Number|Buffer|String|undefined} * @memberOf Document * @instance * @api public */ Document.prototype.populated = function(path, val, options) { // val and options are internal if (val === null || val === void 0) { if (!this.$__.populated) { return undefined; } const v = this.$__.populated[path]; if (v) { return v.value; } return undefined; } // internal if (val === true) { if (!this.$__.populated) { return undefined; } return this.$__.populated[path]; } this.$__.populated || (this.$__.populated = {}); this.$__.populated[path] = { value: val, options: options }; // If this was a nested populate, make sure each populated doc knows // about its populated children (gh-7685) const pieces = path.split('.'); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join('.'); const subdoc = this.get(subpath); if (subdoc != null && subdoc.$__ != null && this.populated(subpath)) { const rest = pieces.slice(i + 1).join('.'); subdoc.populated(rest, val, options); // No need to continue because the above recursion should take care of // marking the rest of the docs as populated break; } } return val; }; /** * Takes a populated field and returns it to its unpopulated state. * * ####Example: * * Model.findOne().populate('author').exec(function (err, doc) { * console.log(doc.author.name); // Dr.Seuss * console.log(doc.depopulate('author')); * console.log(doc.author); // '5144cf8050f071d979c118a7' * }) * * If the path was not populated, this is a no-op. * * @param {String} path * @return {Document} this * @see Document.populate #document_Document-populate * @api public * @memberOf Document * @instance */ Document.prototype.depopulate = function(path) { if (typeof path === 'string') { path = path.split(' '); } let populatedIds; const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; const populated = get(this, '$__.populated', {}); if (arguments.length === 0) { // Depopulate all for (const virtualKey of virtualKeys) { delete this.$$populatedVirtuals[virtualKey]; delete this._doc[virtualKey]; delete populated[virtualKey]; } const keys = Object.keys(populated); for (const key of keys) { populatedIds = this.populated(key); if (!populatedIds) { continue; } delete populated[key]; this.$set(key, populatedIds); } return this; } for (const singlePath of path) { populatedIds = this.populated(singlePath); delete populated[singlePath]; if (virtualKeys.indexOf(singlePath) !== -1) { delete this.$$populatedVirtuals[singlePath]; delete this._doc[singlePath]; } else if (populatedIds) { this.$set(singlePath, populatedIds); } } return this; }; /** * Returns the full path to this document. * * @param {String} [path] * @return {String} * @api private * @method $__fullPath * @memberOf Document * @instance */ Document.prototype.$__fullPath = function(path) { // overridden in SubDocuments return path || ''; }; /** * Returns the changes that happened to the document * in the format that will be sent to MongoDB. * * #### Example: * * const userSchema = new Schema({ * name: String, * age: Number, * country: String * }); * const User = mongoose.model('User', userSchema); * const user = await User.create({ * name: 'Hafez', * age: 25, * country: 'Egypt' * }); * * // returns an empty object, no changes happened yet * user.getChanges(); // { } * * user.country = undefined; * user.age = 26; * * user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } } * * await user.save(); * * user.getChanges(); // { } * * Modifying the object that `getChanges()` returns does not affect the document's * change tracking state. Even if you `delete user.getChanges().$set`, Mongoose * will still send a `$set` to the server. * * @return {Object} * @api public * @method getChanges * @memberOf Document * @instance */ Document.prototype.getChanges = function() { const delta = this.$__delta(); const changes = delta ? delta[1] : {}; return changes; }; /*! * Module exports. */ Document.ValidationError = ValidationError; module.exports = exports = Document; }).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) },{"../../is-buffer/index.js":255,"./error/index":278,"./error/objectExpected":283,"./error/objectParameter":284,"./error/parallelValidate":287,"./error/strict":288,"./error/validation":289,"./error/validator":290,"./helpers/common":294,"./helpers/document/cleanModifiedSubpaths":299,"./helpers/document/compile":300,"./helpers/document/getEmbeddedDiscriminatorPath":301,"./helpers/document/handleSpreadDoc":302,"./helpers/get":303,"./helpers/isPromise":309,"./helpers/projection/isDefiningProjection":313,"./helpers/projection/isExclusive":314,"./helpers/promiseOrCallback":315,"./helpers/symbols":326,"./internal":330,"./options":331,"./plugins/idGetter":345,"./queryhelpers":347,"./schema":348,"./schema/mixed":358,"./types/array":371,"./types/documentarray":375,"./types/embedded":376,"./utils":381,"./virtualtype":382,"_process":399,"events":253,"mpath":384,"util":414}],269:[function(require,module,exports){ 'use strict'; /* eslint-env browser */ /*! * Module dependencies. */ const Document = require('./document.js'); const BrowserDocument = require('./browserDocument.js'); let isBrowser = false; /** * Returns the Document constructor for the current context * * @api private */ module.exports = function() { if (isBrowser) { return BrowserDocument; } return Document; }; /*! * ignore */ module.exports.setBrowser = function(flag) { isBrowser = flag; }; },{"./browserDocument.js":260,"./document.js":268}],270:[function(require,module,exports){ 'use strict'; /*! * ignore */ let driver = null; module.exports.get = function() { return driver; }; module.exports.set = function(v) { driver = v; }; },{}],271:[function(require,module,exports){ /*! * ignore */ 'use strict'; module.exports = function() {}; },{}],272:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const Binary = require('bson').Binary; /*! * Module exports. */ module.exports = exports = Binary; },{"bson":96}],273:[function(require,module,exports){ /*! * ignore */ 'use strict'; module.exports = require('bson').Decimal128; },{"bson":96}],274:[function(require,module,exports){ /*! * Module exports. */ 'use strict'; exports.Binary = require('./binary'); exports.Collection = function() { throw new Error('Cannot create a collection from browser library'); }; exports.Decimal128 = require('./decimal128'); exports.ObjectId = require('./objectid'); exports.ReadPreference = require('./ReadPreference'); },{"./ReadPreference":271,"./binary":272,"./decimal128":273,"./objectid":275}],275:[function(require,module,exports){ /*! * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId * @constructor NodeMongoDbObjectId * @see ObjectId */ 'use strict'; const ObjectId = require('bson').ObjectID; /*! * Getter for convenience with populate, see gh-6115 */ Object.defineProperty(ObjectId.prototype, '_id', { enumerable: false, configurable: true, get: function() { return this; } }); /*! * ignore */ module.exports = exports = ObjectId; },{"bson":96}],276:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./mongooseError'); const get = require('../helpers/get'); const util = require('util'); /** * Casting Error constructor. * * @param {String} type * @param {String} value * @inherits MongooseError * @api private */ class CastError extends MongooseError { constructor(type, value, path, reason, schemaType) { // If no args, assume we'll `init()` later. if (arguments.length > 0) { const stringValue = getStringValue(value); const messageFormat = getMessageFormat(schemaType); const msg = formatMessage(null, type, stringValue, path, messageFormat); super(msg); this.init(type, value, path, reason, schemaType); } else { super(formatMessage()); } } /*! * ignore */ init(type, value, path, reason, schemaType) { this.stringValue = getStringValue(value); this.messageFormat = getMessageFormat(schemaType); this.kind = type; this.value = value; this.path = path; this.reason = reason; } /*! * ignore * @param {Readonly} other */ copy(other) { this.messageFormat = other.messageFormat; this.stringValue = other.stringValue; this.kind = other.kind; this.value = other.value; this.path = other.path; this.reason = other.reason; this.message = other.message; } /*! * ignore */ setModel(model) { this.model = model; this.message = formatMessage(model, this.kind, this.stringValue, this.path, this.messageFormat); } } Object.defineProperty(CastError.prototype, 'name', { value: 'CastError' }); function getStringValue(value) { let stringValue = util.inspect(value); stringValue = stringValue.replace(/^'|'$/g, '"'); if (!stringValue.startsWith('"')) { stringValue = '"' + stringValue + '"'; } return stringValue; } function getMessageFormat(schemaType) { const messageFormat = get(schemaType, 'options.cast', null); if (typeof messageFormat === 'string') { return messageFormat; } } /*! * ignore */ function formatMessage(model, kind, stringValue, path, messageFormat) { if (messageFormat != null) { let ret = messageFormat. replace('{KIND}', kind). replace('{VALUE}', stringValue). replace('{PATH}', path); if (model != null) { ret = ret.replace('{MODEL}', model.modelName); } return ret; } else { let ret = 'Cast to ' + kind + ' failed for value ' + stringValue + ' at path "' + path + '"'; if (model != null) { ret += ' for model "' + model.modelName + '"'; } return ret; } } /*! * exports */ module.exports = CastError; },{"../helpers/get":303,"./mongooseError":281,"util":414}],277:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class DivergentArrayError extends MongooseError { /*! * DivergentArrayError constructor. * @param {Array} paths */ constructor(paths) { const msg = 'For your own good, using `document.save()` to update an array ' + 'which was selected using an $elemMatch projection OR ' + 'populated using skip, limit, query conditions, or exclusion of ' + 'the _id field when the operation results in a $pop or $set of ' + 'the entire array is not supported. The following ' + 'path(s) would have been modified unsafely:\n' + ' ' + paths.join('\n ') + '\n' + 'Use Model.update() to update these arrays instead.'; // TODO write up a docs page (FAQ) and link to it super(msg); } } Object.defineProperty(DivergentArrayError.prototype, 'name', { value: 'DivergentArrayError' }); /*! * exports */ module.exports = DivergentArrayError; },{"./":278}],278:[function(require,module,exports){ 'use strict'; /** * MongooseError constructor. MongooseError is the base class for all * Mongoose-specific errors. * * ####Example: * const Model = mongoose.model('Test', new Schema({ answer: Number })); * const doc = new Model({ answer: 'not a number' }); * const err = doc.validateSync(); * * err instanceof mongoose.Error; // true * * @constructor Error * @param {String} msg Error message * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error */ const MongooseError = require('./mongooseError'); /** * The name of the error. The name uniquely identifies this Mongoose error. The * possible values are: * * - `MongooseError`: general Mongoose error * - `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property. * - `DisconnectedError`: This [connection](connections.html) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect. * - `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection * - `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api.html#mongoose_Mongoose-model) that was not defined * - `DocumentNotFoundError`: The document you tried to [`save()`](api.html#document_Document-save) was not found * - `ValidatorError`: error from an individual schema path's validator * - `ValidationError`: error returned from [`validate()`](api.html#document_Document-validate) or [`validateSync()`](api.html#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property. * - `MissingSchemaError`: You called `mongoose.Document()` without a schema * - `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide.html#strict). * - `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter * - `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api.html#mongoose_Mongoose-model) to re-define a model that was already defined. * - `ParallelSaveError`: Thrown when you call [`save()`](api.html#model_Model-save) on a document when the same document instance is already saving. * - `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide.html#strict) is set to `throw`. * - `VersionError`: Thrown when the [document is out of sync](guide.html#versionKey) * * @api public * @property {String} name * @memberOf Error * @instance */ /*! * Module exports. */ module.exports = exports = MongooseError; /** * The default built-in validator error messages. * * @see Error.messages #error_messages_MongooseError-messages * @api public * @memberOf Error * @static messages */ MongooseError.messages = require('./messages'); // backward compat MongooseError.Messages = MongooseError.messages; /** * An instance of this error class will be returned when `save()` fails * because the underlying * document was not found. The constructor takes one parameter, the * conditions that mongoose passed to `update()` when trying to update * the document. * * @api public * @memberOf Error * @static DocumentNotFoundError */ MongooseError.DocumentNotFoundError = require('./notFound'); /** * An instance of this error class will be returned when mongoose failed to * cast a value. * * @api public * @memberOf Error * @static CastError */ MongooseError.CastError = require('./cast'); /** * An instance of this error class will be returned when [validation](/docs/validation.html) failed. * The `errors` property contains an object whose keys are the paths that failed and whose values are * instances of CastError or ValidationError. * * @api public * @memberOf Error * @static ValidationError */ MongooseError.ValidationError = require('./validation'); /** * A `ValidationError` has a hash of `errors` that contain individual * `ValidatorError` instances. * * ####Example: * * const schema = Schema({ name: { type: String, required: true } }); * const Model = mongoose.model('Test', schema); * const doc = new Model({}); * * // Top-level error is a ValidationError, **not** a ValidatorError * const err = doc.validateSync(); * err instanceof mongoose.Error.ValidationError; // true * * // A ValidationError `err` has 0 or more ValidatorErrors keyed by the * // path in the `err.errors` property. * err.errors['name'] instanceof mongoose.Error.ValidatorError; * * err.errors['name'].kind; // 'required' * err.errors['name'].path; // 'name' * err.errors['name'].value; // undefined * * Instances of `ValidatorError` have the following properties: * * - `kind`: The validator's `type`, like `'required'` or `'regexp'` * - `path`: The path that failed validation * - `value`: The value that failed validation * * @api public * @memberOf Error * @static ValidatorError */ MongooseError.ValidatorError = require('./validator'); /** * An instance of this error class will be returned when you call `save()` after * the document in the database was changed in a potentially unsafe way. See * the [`versionKey` option](/docs/guide.html#versionKey) for more information. * * @api public * @memberOf Error * @static VersionError */ MongooseError.VersionError = require('./version'); /** * An instance of this error class will be returned when you call `save()` multiple * times on the same document in parallel. See the [FAQ](/docs/faq.html) for more * information. * * @api public * @memberOf Error * @static ParallelSaveError */ MongooseError.ParallelSaveError = require('./parallelSave'); /** * Thrown when a model with the given name was already registered on the connection. * See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error). * * @api public * @memberOf Error * @static OverwriteModelError */ MongooseError.OverwriteModelError = require('./overwriteModel'); /** * Thrown when you try to access a model that has not been registered yet * * @api public * @memberOf Error * @static MissingSchemaError */ MongooseError.MissingSchemaError = require('./missingSchema'); /** * An instance of this error will be returned if you used an array projection * and then modified the array in an unsafe way. * * @api public * @memberOf Error * @static DivergentArrayError */ MongooseError.DivergentArrayError = require('./divergentArray'); /** * Thrown when your try to pass values to model contrtuctor that * were not specified in schema or change immutable properties when * `strict` mode is `"throw"` * * @api public * @memberOf Error * @static StrictModeError */ MongooseError.StrictModeError = require('./strict'); },{"./cast":276,"./divergentArray":277,"./messages":279,"./missingSchema":280,"./mongooseError":281,"./notFound":282,"./overwriteModel":285,"./parallelSave":286,"./strict":288,"./validation":289,"./validator":290,"./version":291}],279:[function(require,module,exports){ /** * The default built-in validator error messages. These may be customized. * * // customize within each schema or globally like so * const mongoose = require('mongoose'); * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; * * As you might have noticed, error messages support basic templating * * - `{PATH}` is replaced with the invalid document path * - `{VALUE}` is replaced with the invalid value * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" * - `{MIN}` is replaced with the declared min value for the Number.min validator * - `{MAX}` is replaced with the declared max value for the Number.max validator * * Click the "show code" link below to see all defaults. * * @static messages * @receiver MongooseError * @api public */ 'use strict'; const msg = module.exports = exports = {}; msg.DocumentNotFoundError = null; msg.general = {}; msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; msg.general.required = 'Path `{PATH}` is required.'; msg.Number = {}; msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; msg.Number.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; msg.Date = {}; msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; msg.String = {}; msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; },{}],280:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class MissingSchemaError extends MongooseError { /*! * MissingSchema Error constructor. * @param {String} name */ constructor(name) { const msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + 'Use mongoose.model(name, schema)'; super(msg); } } Object.defineProperty(MissingSchemaError.prototype, 'name', { value: 'MissingSchemaError' }); /*! * exports */ module.exports = MissingSchemaError; },{"./":278}],281:[function(require,module,exports){ 'use strict'; /*! * ignore */ class MongooseError extends Error { } Object.defineProperty(MongooseError.prototype, 'name', { value: 'MongooseError' }); module.exports = MongooseError; },{}],282:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./'); const util = require('util'); class DocumentNotFoundError extends MongooseError { /*! * OverwriteModel Error constructor. */ constructor(filter, model, numAffected, result) { let msg; const messages = MongooseError.messages; if (messages.DocumentNotFoundError != null) { msg = typeof messages.DocumentNotFoundError === 'function' ? messages.DocumentNotFoundError(filter, model) : messages.DocumentNotFoundError; } else { msg = 'No document found for query "' + util.inspect(filter) + '" on model "' + model + '"'; } super(msg); this.result = result; this.numAffected = numAffected; this.filter = filter; // Backwards compat this.query = filter; } } Object.defineProperty(DocumentNotFoundError.prototype, 'name', { value: 'DocumentNotFoundError' }); /*! * exports */ module.exports = DocumentNotFoundError; },{"./":278,"util":414}],283:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class ObjectExpectedError extends MongooseError { /** * Strict mode error constructor * * @param {string} type * @param {string} value * @api private */ constructor(path, val) { const typeDescription = Array.isArray(val) ? 'array' : 'primitive value'; super('Tried to set nested object field `' + path + `\` to ${typeDescription} \`` + val + '` and strict mode is set to throw.'); this.path = path; } } Object.defineProperty(ObjectExpectedError.prototype, 'name', { value: 'ObjectExpectedError' }); module.exports = ObjectExpectedError; },{"./":278}],284:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class ObjectParameterError extends MongooseError { /** * Constructor for errors that happen when a parameter that's expected to be * an object isn't an object * * @param {Any} value * @param {String} paramName * @param {String} fnName * @api private */ constructor(value, paramName, fnName) { super('Parameter "' + paramName + '" to ' + fnName + '() must be an object, got ' + value.toString()); } } Object.defineProperty(ObjectParameterError.prototype, 'name', { value: 'ObjectParameterError' }); module.exports = ObjectParameterError; },{"./":278}],285:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class OverwriteModelError extends MongooseError { /*! * OverwriteModel Error constructor. * @param {String} name */ constructor(name) { super('Cannot overwrite `' + name + '` model once compiled.'); } } Object.defineProperty(OverwriteModelError.prototype, 'name', { value: 'OverwriteModelError' }); /*! * exports */ module.exports = OverwriteModelError; },{"./":278}],286:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./'); class ParallelSaveError extends MongooseError { /** * ParallelSave Error constructor. * * @param {Document} doc * @api private */ constructor(doc) { const msg = 'Can\'t save() the same doc multiple times in parallel. Document: '; super(msg + doc._id); } } Object.defineProperty(ParallelSaveError.prototype, 'name', { value: 'ParallelSaveError' }); /*! * exports */ module.exports = ParallelSaveError; },{"./":278}],287:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./mongooseError'); class ParallelValidateError extends MongooseError { /** * ParallelValidate Error constructor. * * @param {Document} doc * @api private */ constructor(doc) { const msg = 'Can\'t validate() the same doc multiple times in parallel. Document: '; super(msg + doc._id); } } Object.defineProperty(ParallelValidateError.prototype, 'name', { value: 'ParallelValidateError' }); /*! * exports */ module.exports = ParallelValidateError; },{"./mongooseError":281}],288:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class StrictModeError extends MongooseError { /** * Strict mode error constructor * * @param {String} path * @param {String} [msg] * @param {Boolean} [immutable] * @inherits MongooseError * @api private */ constructor(path, msg, immutable) { msg = msg || 'Field `' + path + '` is not in schema and strict ' + 'mode is set to throw.'; super(msg); this.isImmutableError = !!immutable; this.path = path; } } Object.defineProperty(StrictModeError.prototype, 'name', { value: 'StrictModeError' }); module.exports = StrictModeError; },{"./":278}],289:[function(require,module,exports){ /*! * Module requirements */ 'use strict'; const MongooseError = require('./mongooseError'); const util = require('util'); class ValidationError extends MongooseError { /** * Document Validation Error * * @api private * @param {Document} [instance] * @inherits MongooseError */ constructor(instance) { let _message; if (instance && instance.constructor.name === 'model') { _message = instance.constructor.modelName + ' validation failed'; } else { _message = 'Validation failed'; } super(_message); this.errors = {}; this._message = _message; if (instance) { instance.errors = this.errors; } } /** * Console.log helper */ toString() { return this.name + ': ' + _generateMessage(this); } /*! * inspect helper */ inspect() { return Object.assign(new Error(this.message), this); } /*! * add message */ addError(path, error) { this.errors[path] = error; this.message = this._message + ': ' + _generateMessage(this); } } if (util.inspect.custom) { /*! * Avoid Node deprecation warning DEP0079 */ ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect; } /*! * Helper for JSON.stringify */ Object.defineProperty(ValidationError.prototype, 'toJSON', { enumerable: false, writable: false, configurable: true, value: function() { return Object.assign({}, this, { message: this.message }); } }); Object.defineProperty(ValidationError.prototype, 'name', { value: 'ValidationError' }); /*! * ignore */ function _generateMessage(err) { const keys = Object.keys(err.errors || {}); const len = keys.length; const msgs = []; let key; for (let i = 0; i < len; ++i) { key = keys[i]; if (err === err.errors[key]) { continue; } msgs.push(key + ': ' + err.errors[key].message); } return msgs.join(', '); } /*! * Module exports */ module.exports = ValidationError; },{"./mongooseError":281,"util":414}],290:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); class ValidatorError extends MongooseError { /** * Schema validator error * * @param {Object} properties * @api private */ constructor(properties) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } const message = formatMessage(msg, properties); super(message); properties = Object.assign({}, properties, { message: message }); this.properties = properties; this.kind = properties.type; this.path = properties.path; this.value = properties.value; this.reason = properties.reason; } /*! * toString helper * TODO remove? This defaults to `${this.name}: ${this.message}` */ toString() { return this.message; } /*! * Ensure `name` and `message` show up in toJSON output re: gh-9296 */ toJSON() { return Object.assign({ name: this.name, message: this.message }, this); } } Object.defineProperty(ValidatorError.prototype, 'name', { value: 'ValidatorError' }); /*! * The object used to define this validator. Not enumerable to hide * it from `require('util').inspect()` output re: gh-3925 */ Object.defineProperty(ValidatorError.prototype, 'properties', { enumerable: false, writable: true, value: null }); // Exposed for testing ValidatorError.prototype.formatMessage = formatMessage; /*! * Formats error messages */ function formatMessage(msg, properties) { if (typeof msg === 'function') { return msg(properties); } const propertyNames = Object.keys(properties); for (const propertyName of propertyNames) { if (propertyName === 'message') { continue; } msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); } return msg; } /*! * exports */ module.exports = ValidatorError; },{"./":278}],291:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./'); class VersionError extends MongooseError { /** * Version Error constructor. * * @param {Document} doc * @param {Number} currentVersion * @param {Array} modifiedPaths * @api private */ constructor(doc, currentVersion, modifiedPaths) { const modifiedPathsStr = modifiedPaths.join(', '); super('No matching document found for id "' + doc._id + '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); this.version = currentVersion; this.modifiedPaths = modifiedPaths; } } Object.defineProperty(VersionError.prototype, 'name', { value: 'VersionError' }); /*! * exports */ module.exports = VersionError; },{"./":278}],292:[function(require,module,exports){ 'use strict'; module.exports = arrayDepth; function arrayDepth(arr) { if (!Array.isArray(arr)) { return { min: 0, max: 0, containsNonArrayItem: true }; } if (arr.length === 0) { return { min: 1, max: 1, containsNonArrayItem: false }; } const res = arrayDepth(arr[0]); for (let i = 1; i < arr.length; ++i) { const _res = arrayDepth(arr[i]); if (_res.min < res.min) { res.min = _res.min; } if (_res.max > res.max) { res.max = _res.max; } res.containsNonArrayItem = res.containsNonArrayItem || _res.containsNonArrayItem; } res.min = res.min + 1; res.max = res.max + 1; return res; } },{}],293:[function(require,module,exports){ 'use strict'; const cloneRegExp = require('regexp-clone'); const Decimal = require('../types/decimal128'); const ObjectId = require('../types/objectid'); const specialProperties = require('./specialProperties'); const isMongooseObject = require('./isMongooseObject'); const getFunctionName = require('./getFunctionName'); const isBsonType = require('./isBsonType'); const isObject = require('./isObject'); const symbols = require('./symbols'); const utils = require('../utils'); /*! * Object clone with Mongoose natives support. * * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. * * Functions are never cloned. * * @param {Object} obj the object to clone * @param {Object} options * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. * @return {Object} the cloned object * @api private */ function clone(obj, options, isArrayChild) { if (obj == null) { return obj; } if (Array.isArray(obj)) { return cloneArray(obj, options); } if (isMongooseObject(obj)) { // Single nested subdocs should apply getters later in `applyGetters()` // when calling `toObject()`. See gh-7442, gh-8295 if (options && options._skipSingleNestedGetters && obj.$isSingleNested) { options = Object.assign({}, options, { getters: false }); } if (utils.isPOJO(obj) && obj.$__ != null && obj._doc != null) { return obj._doc; } if (options && options.json && typeof obj.toJSON === 'function') { return obj.toJSON(options); } return obj.toObject(options); } if (obj.constructor) { switch (getFunctionName(obj.constructor)) { case 'Object': return cloneObject(obj, options, isArrayChild); case 'Date': return new obj.constructor(+obj); case 'RegExp': return cloneRegExp(obj); default: // ignore break; } } if (obj instanceof ObjectId) { return new ObjectId(obj.id); } if (isBsonType(obj, 'Decimal128')) { if (options && options.flattenDecimals) { return obj.toJSON(); } return Decimal.fromString(obj.toString()); } if (!obj.constructor && isObject(obj)) { // object created with Object.create(null) return cloneObject(obj, options, isArrayChild); } if (obj[symbols.schemaTypeSymbol]) { return obj.clone(); } // If we're cloning this object to go into a MongoDB command, // and there's a `toBSON()` function, assume this object will be // stored as a primitive in MongoDB and doesn't need to be cloned. if (options && options.bson && typeof obj.toBSON === 'function') { return obj; } if (obj.valueOf != null) { return obj.valueOf(); } return cloneObject(obj, options, isArrayChild); } module.exports = clone; /*! * ignore */ function cloneObject(obj, options, isArrayChild) { const minimize = options && options.minimize; const ret = {}; let hasKeys; for (const k in obj) { if (specialProperties.has(k)) { continue; } // Don't pass `isArrayChild` down const val = clone(obj[k], options); if (!minimize || (typeof val !== 'undefined')) { if (minimize === false && typeof val === 'undefined') { delete ret[k]; } else { hasKeys || (hasKeys = true); ret[k] = val; } } } return minimize && !isArrayChild ? hasKeys && ret : ret; } function cloneArray(arr, options) { const ret = []; for (const item of arr) { ret.push(clone(item, options, true)); } return ret; } },{"../types/decimal128":374,"../types/objectid":379,"../utils":381,"./getFunctionName":304,"./isBsonType":306,"./isMongooseObject":307,"./isObject":308,"./specialProperties":325,"./symbols":326,"regexp-clone":400}],294:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ const Binary = require('../driver').get().Binary; const Decimal128 = require('../types/decimal128'); const ObjectId = require('../types/objectid'); const isMongooseObject = require('./isMongooseObject'); exports.flatten = flatten; exports.modifiedPaths = modifiedPaths; /*! * ignore */ function flatten(update, path, options, schema) { let keys; if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { keys = Object.keys(update.toObject({ transform: false, virtuals: false })); } else { keys = Object.keys(update || {}); } const numKeys = keys.length; const result = {}; path = path ? path + '.' : ''; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; const val = update[key]; result[path + key] = val; // Avoid going into mixed paths if schema is specified const keySchema = schema && schema.path && schema.path(path + key); const isNested = schema && schema.nested && schema.nested[path + key]; if (keySchema && keySchema.instance === 'Mixed') continue; if (shouldFlatten(val)) { if (options && options.skipArrays && Array.isArray(val)) { continue; } const flat = flatten(val, path + key, options, schema); for (const k in flat) { result[k] = flat[k]; } if (Array.isArray(val)) { result[path + key] = val; } } if (isNested) { const paths = Object.keys(schema.paths); for (const p of paths) { if (p.startsWith(path + key + '.') && !result.hasOwnProperty(p)) { result[p] = void 0; } } } } return result; } /*! * ignore */ function modifiedPaths(update, path, result) { const keys = Object.keys(update || {}); const numKeys = keys.length; result = result || {}; path = path ? path + '.' : ''; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; let val = update[key]; result[path + key] = true; if (isMongooseObject(val) && !Buffer.isBuffer(val)) { val = val.toObject({ transform: false, virtuals: false }); } if (shouldFlatten(val)) { modifiedPaths(val, path + key, result); } } return result; } /*! * ignore */ function shouldFlatten(val) { return val && typeof val === 'object' && !(val instanceof Date) && !(val instanceof ObjectId) && (!Array.isArray(val) || val.length > 0) && !(val instanceof Buffer) && !(val instanceof Decimal128) && !(val instanceof Binary); } }).call(this,require("buffer").Buffer) },{"../driver":270,"../types/decimal128":374,"../types/objectid":379,"./isMongooseObject":307,"buffer":115}],295:[function(require,module,exports){ 'use strict'; module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) { const userProjectedInPath = Object.keys(userProjection). reduce((cur, key) => cur || key.startsWith(path + '.'), false); const _discriminatorKey = path + '.' + schema.options.discriminatorKey; if (!userProjectedInPath && addedPaths.length === 1 && addedPaths[0] === _discriminatorKey) { selected.splice(selected.indexOf(_discriminatorKey), 1); } }; },{}],296:[function(require,module,exports){ 'use strict'; const getDiscriminatorByValue = require('./getDiscriminatorByValue'); /*! * Find the correct constructor, taking into account discriminators */ module.exports = function getConstructor(Constructor, value) { const discriminatorKey = Constructor.schema.options.discriminatorKey; if (value != null && Constructor.discriminators && value[discriminatorKey] != null) { if (Constructor.discriminators[value[discriminatorKey]]) { Constructor = Constructor.discriminators[value[discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor, value[discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } return Constructor; }; },{"./getDiscriminatorByValue":297}],297:[function(require,module,exports){ 'use strict'; /*! * returns discriminator by discriminatorMapping.value * * @param {Model} model * @param {string} value */ module.exports = function getDiscriminatorByValue(model, value) { let discriminator = null; if (!model.discriminators) { return discriminator; } for (const name in model.discriminators) { const it = model.discriminators[name]; if ( it.schema && it.schema.discriminatorMapping && it.schema.discriminatorMapping.value == value ) { discriminator = it; break; } } return discriminator; }; },{}],298:[function(require,module,exports){ 'use strict'; /*! * returns discriminator by discriminatorMapping.value * * @param {Schema} schema * @param {string} value */ module.exports = function getSchemaDiscriminatorByValue(schema, value) { if (schema == null || schema.discriminators == null) { return null; } for (const key of Object.keys(schema.discriminators)) { const discriminatorSchema = schema.discriminators[key]; if (discriminatorSchema.discriminatorMapping == null) { continue; } if (discriminatorSchema.discriminatorMapping.value === value) { return discriminatorSchema; } } return null; }; },{}],299:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function cleanModifiedSubpaths(doc, path, options) { options = options || {}; const skipDocArrays = options.skipDocArrays; let deleted = 0; if (!doc) { return deleted; } for (const modifiedPath of Object.keys(doc.$__.activePaths.states.modify)) { if (skipDocArrays) { const schemaType = doc.schema.path(modifiedPath); if (schemaType && schemaType.$isMongooseDocumentArray) { continue; } } if (modifiedPath.startsWith(path + '.')) { delete doc.$__.activePaths.states.modify[modifiedPath]; ++deleted; } } return deleted; }; },{}],300:[function(require,module,exports){ 'use strict'; const documentSchemaSymbol = require('../../helpers/symbols').documentSchemaSymbol; const get = require('../../helpers/get'); const internalToObjectOptions = require('../../options').internalToObjectOptions; const utils = require('../../utils'); let Document; const getSymbol = require('../../helpers/symbols').getSymbol; const scopeSymbol = require('../../helpers/symbols').scopeSymbol; /*! * exports */ exports.compile = compile; exports.defineKey = defineKey; /*! * Compiles schemas. */ function compile(tree, proto, prefix, options) { Document = Document || require('../../document'); const keys = Object.keys(tree); const len = keys.length; let limb; let key; for (let i = 0; i < len; ++i) { key = keys[i]; limb = tree[key]; const hasSubprops = utils.isPOJO(limb) && Object.keys(limb).length && (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)); const subprops = hasSubprops ? limb : null; defineKey(key, subprops, proto, prefix, keys, options); } } /*! * Defines the accessor named prop on the incoming prototype. */ function defineKey(prop, subprops, prototype, prefix, keys, options) { Document = Document || require('../../document'); const path = (prefix ? prefix + '.' : '') + prop; prefix = prefix || ''; if (subprops) { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { const _this = this; if (!this.$__.getters) { this.$__.getters = {}; } if (!this.$__.getters[path]) { const nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); // save scope for nested getters/setters if (!prefix) { nested.$__[scopeSymbol] = this; } nested.$__.nestedPath = path; Object.defineProperty(nested, 'schema', { enumerable: false, configurable: true, writable: false, value: prototype.schema }); Object.defineProperty(nested, documentSchemaSymbol, { enumerable: false, configurable: true, writable: false, value: prototype.schema }); Object.defineProperty(nested, 'toObject', { enumerable: false, configurable: true, writable: false, value: function() { return utils.clone(_this.get(path, null, { virtuals: get(this, 'schema.options.toObject.virtuals', null) })); } }); Object.defineProperty(nested, '$__get', { enumerable: false, configurable: true, writable: false, value: function() { return _this.get(path, null, { virtuals: get(this, 'schema.options.toObject.virtuals', null) }); } }); Object.defineProperty(nested, 'toJSON', { enumerable: false, configurable: true, writable: false, value: function() { return _this.get(path, null, { virtuals: get(_this, 'schema.options.toJSON.virtuals', null) }); } }); Object.defineProperty(nested, '$__isNested', { enumerable: false, configurable: true, writable: false, value: true }); const _isEmptyOptions = Object.freeze({ minimize: true, virtuals: false, getters: false, transform: false }); Object.defineProperty(nested, '$isEmpty', { enumerable: false, configurable: true, writable: false, value: function() { return Object.keys(this.get(path, null, _isEmptyOptions) || {}).length === 0; } }); Object.defineProperty(nested, '$__parent', { enumerable: false, configurable: true, writable: false, value: this }); compile(subprops, nested, path, options); this.$__.getters[path] = nested; } return this.$__.getters[path]; }, set: function(v) { if (v != null && v.$__isNested) { // Convert top-level to POJO, but leave subdocs hydrated so `$set` // can handle them. See gh-9293. v = v.$__get(); } else if (v instanceof Document && !v.$__isNested) { v = v.toObject(internalToObjectOptions); } const doc = this.$__[scopeSymbol] || this; doc.$set(path, v); } }); } else { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { return this[getSymbol].call(this.$__[scopeSymbol] || this, path); }, set: function(v) { this.$set.call(this.$__[scopeSymbol] || this, path, v); } }); } } // gets descriptors for all properties of `object` // makes all properties non-enumerable to match previous behavior to #2211 function getOwnPropertyDescriptors(object) { const result = {}; Object.getOwnPropertyNames(object).forEach(function(key) { result[key] = Object.getOwnPropertyDescriptor(object, key); // Assume these are schema paths, ignore them re: #5470 if (result[key].get) { delete result[key]; return; } result[key].enumerable = [ 'isNew', '$__', 'errors', '_doc', '$locals', '$op', '__parentArray', '__index', '$isDocumentArrayElement' ].indexOf(key) === -1; }); return result; } },{"../../document":268,"../../helpers/get":303,"../../helpers/symbols":326,"../../options":331,"../../utils":381}],301:[function(require,module,exports){ 'use strict'; const get = require('../get'); /*! * Like `schema.path()`, except with a document, because impossible to * determine path type without knowing the embedded discriminator key. */ module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) { options = options || {}; const typeOnly = options.typeOnly; const parts = path.split('.'); let schema = null; let type = 'adhocOrUndefined'; for (let i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join('.'); schema = doc.schema.path(subpath); if (schema == null) { type = 'adhocOrUndefined'; continue; } if (schema.instance === 'Mixed') { return typeOnly ? 'real' : schema; } type = doc.schema.pathType(subpath); if ((schema.$isSingleNested || schema.$isMongooseDocumentArrayElement) && schema.schema.discriminators != null) { const discriminators = schema.schema.discriminators; const discriminatorKey = doc.get(subpath + '.' + get(schema, 'schema.options.discriminatorKey')); if (discriminatorKey == null || discriminators[discriminatorKey] == null) { continue; } const rest = parts.slice(i + 1).join('.'); return getEmbeddedDiscriminatorPath(doc.get(subpath), rest, options); } } // Are we getting the whole schema or just the type, 'real', 'nested', etc. return typeOnly ? type : schema; }; },{"../get":303}],302:[function(require,module,exports){ 'use strict'; const utils = require('../../utils'); /** * Using spread operator on a Mongoose document gives you a * POJO that has a tendency to cause infinite recursion. So * we use this function on `set()` to prevent that. */ module.exports = function handleSpreadDoc(v) { if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { return v._doc; } return v; }; },{"../../utils":381}],303:[function(require,module,exports){ 'use strict'; /*! * Simplified lodash.get to work around the annoying null quirk. See: * https://github.com/lodash/lodash/issues/3659 */ module.exports = function get(obj, path, def) { const parts = path.split('.'); let rest = path; let cur = obj; for (const part of parts) { if (cur == null) { return def; } // `lib/cast.js` depends on being able to get dotted paths in updates, // like `{ $set: { 'a.b': 42 } }` if (cur[rest] != null) { return cur[rest]; } cur = getProperty(cur, part); rest = rest.substr(part.length + 1); } return cur == null ? def : cur; }; function getProperty(obj, prop) { if (obj == null) { return obj; } if (obj instanceof Map) { return obj.get(prop); } return obj[prop]; } },{}],304:[function(require,module,exports){ 'use strict'; module.exports = function(fn) { if (fn.name) { return fn.name; } return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; }; },{}],305:[function(require,module,exports){ (function (process){ /*! * Centralize this so we can more easily work around issues with people * stubbing out `process.nextTick()` in tests using sinon: * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time * See gh-6074 */ 'use strict'; module.exports = function immediate(cb) { return process.nextTick(cb); }; }).call(this,require('_process')) },{"_process":399}],306:[function(require,module,exports){ 'use strict'; const get = require('./get'); /*! * Get the bson type, if it exists */ function isBsonType(obj, typename) { return get(obj, '_bsontype', void 0) === typename; } module.exports = isBsonType; },{"./get":303}],307:[function(require,module,exports){ 'use strict'; /*! * Returns if `v` is a mongoose object that has a `toObject()` method we can use. * * This is for compatibility with libs like Date.js which do foolish things to Natives. * * @param {any} v * @api private */ module.exports = function(v) { if (v == null) { return false; } return v.$__ != null || // Document v.isMongooseArray || // Array or Document Array v.isMongooseBuffer || // Buffer v.$isMongooseMap; // Map }; },{}],308:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Determines if `arg` is an object. * * @param {Object|Array|String|Function|RegExp|any} arg * @api private * @return {Boolean} */ module.exports = function(arg) { if (Buffer.isBuffer(arg)) { return true; } return Object.prototype.toString.call(arg) === '[object Object]'; }; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255}],309:[function(require,module,exports){ 'use strict'; function isPromise(val) { return !!val && (typeof val === 'object' || typeof val === 'function') && typeof val.then === 'function'; } module.exports = isPromise; },{}],310:[function(require,module,exports){ 'use strict'; const symbols = require('../../schema/symbols'); const promiseOrCallback = require('../promiseOrCallback'); /*! * ignore */ module.exports = applyHooks; /*! * ignore */ applyHooks.middlewareFunctions = [ 'deleteOne', 'save', 'validate', 'remove', 'updateOne', 'init' ]; /*! * Register hooks for this model * * @param {Model} model * @param {Schema} schema */ function applyHooks(model, schema, options) { options = options || {}; const kareemOptions = { useErrorHandlers: true, numCallbackParams: 1, nullResultByDefault: true, contextParameter: true }; const objToDecorate = options.decorateDoc ? model : model.prototype; model.$appliedHooks = true; for (const key of Object.keys(schema.paths)) { const type = schema.paths[key]; let childModel = null; if (type.$isSingleNested) { childModel = type.caster; } else if (type.$isMongooseDocumentArray) { childModel = type.Constructor; } else { continue; } if (childModel.$appliedHooks) { continue; } applyHooks(childModel, type.schema, options); if (childModel.discriminators != null) { const keys = Object.keys(childModel.discriminators); for (const key of keys) { applyHooks(childModel.discriminators[key], childModel.discriminators[key].schema, options); } } } // Built-in hooks rely on hooking internal functions in order to support // promises and make it so that `doc.save.toString()` provides meaningful // information. const middleware = schema.s.hooks. filter(hook => { if (hook.name === 'updateOne' || hook.name === 'deleteOne') { return !!hook['document']; } if (hook.name === 'remove' || hook.name === 'init') { return hook['document'] == null || !!hook['document']; } if (hook.query != null || hook.document != null) { return hook.document !== false; } return true; }). filter(hook => { // If user has overwritten the method, don't apply built-in middleware if (schema.methods[hook.name]) { return !hook.fn[symbols.builtInMiddleware]; } return true; }); model._middleware = middleware; objToDecorate.$__originalValidate = objToDecorate.$__originalValidate || objToDecorate.$__validate; for (const method of ['save', 'validate', 'remove', 'deleteOne']) { const toWrap = method === 'validate' ? '$__originalValidate' : `$__${method}`; const wrapped = middleware. createWrapper(method, objToDecorate[toWrap], null, kareemOptions); objToDecorate[`$__${method}`] = wrapped; } objToDecorate.$__init = middleware. createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); // Support hooks for custom methods const customMethods = Object.keys(schema.methods); const customMethodOptions = Object.assign({}, kareemOptions, { // Only use `checkForPromise` for custom methods, because mongoose // query thunks are not as consistent as I would like about returning // a nullish value rather than the query. If a query thunk returns // a query, `checkForPromise` causes infinite recursion checkForPromise: true }); for (const method of customMethods) { if (!middleware.hasHooks(method)) { // Don't wrap if there are no hooks for the custom method to avoid // surprises. Also, `createWrapper()` enforces consistent async, // so wrapping a sync method would break it. continue; } const originalMethod = objToDecorate[method]; objToDecorate[method] = function() { const args = Array.prototype.slice.call(arguments); const cb = args.slice(-1).pop(); const argsWithoutCallback = typeof cb === 'function' ? args.slice(0, args.length - 1) : args; return promiseOrCallback(cb, callback => { return this[`$__${method}`].apply(this, argsWithoutCallback.concat([callback])); }, model.events); }; objToDecorate[`$__${method}`] = middleware. createWrapper(method, originalMethod, null, customMethodOptions); } } },{"../../schema/symbols":368,"../promiseOrCallback":315}],311:[function(require,module,exports){ 'use strict'; const Mixed = require('../../schema/mixed'); const defineKey = require('../document/compile').defineKey; const get = require('../get'); const utils = require('../../utils'); const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { toJSON: true, toObject: true, _id: true, id: true }; /*! * ignore */ module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) { if (!(schema && schema.instanceOfSchema)) { throw new Error('You must pass a valid discriminator Schema'); } if (model.schema.discriminatorMapping && !model.schema.discriminatorMapping.isRoot) { throw new Error('Discriminator "' + name + '" can only be a discriminator of the root model'); } if (applyPlugins) { const applyPluginsToDiscriminators = get(model.base, 'options.applyPluginsToDiscriminators', false); // Even if `applyPluginsToDiscriminators` isn't set, we should still apply // global plugins to schemas embedded in the discriminator schema (gh-7370) model.base._applyPlugins(schema, { skipTopLevel: !applyPluginsToDiscriminators }); } const key = model.schema.options.discriminatorKey; const existingPath = model.schema.path(key); if (existingPath != null) { if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) { existingPath.options.select = true; } existingPath.options.$skipDiscriminatorCheck = true; } else { const baseSchemaAddition = {}; baseSchemaAddition[key] = { default: void 0, select: true, $skipDiscriminatorCheck: true }; baseSchemaAddition[key][model.schema.options.typeKey] = String; model.schema.add(baseSchemaAddition); defineKey(key, null, model.prototype, null, [key], model.schema.options); } if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { throw new Error('Discriminator "' + name + '" cannot have field with name "' + key + '"'); } let value = name; if (typeof tiedValue == 'string' && tiedValue.length) { value = tiedValue; } function merge(schema, baseSchema) { // Retain original schema before merging base schema schema._baseSchema = baseSchema; if (baseSchema.paths._id && baseSchema.paths._id.options && !baseSchema.paths._id.options.auto) { schema.remove('_id'); } // Find conflicting paths: if something is a path in the base schema // and a nested path in the child schema, overwrite the base schema path. // See gh-6076 const baseSchemaPaths = Object.keys(baseSchema.paths); const conflictingPaths = []; for (const path of baseSchemaPaths) { if (schema.nested[path]) { conflictingPaths.push(path); continue; } if (path.indexOf('.') === -1) { continue; } const sp = path.split('.').slice(0, -1); let cur = ''; for (const piece of sp) { cur += (cur.length ? '.' : '') + piece; if (schema.paths[cur] instanceof Mixed || schema.singleNestedPaths[cur] instanceof Mixed) { conflictingPaths.push(path); } } } utils.merge(schema, baseSchema, { isDiscriminatorSchemaMerge: true, omit: { discriminators: true, base: true }, omitNested: conflictingPaths.reduce((cur, path) => { cur['tree.' + path] = true; return cur; }, {}) }); // Clean up conflicting paths _after_ merging re: gh-6076 for (const conflictingPath of conflictingPaths) { delete schema.paths[conflictingPath]; } // Rebuild schema models because schemas may have been merged re: #7884 schema.childSchemas.forEach(obj => { obj.model.prototype.$__setSchema(obj.schema); }); const obj = {}; obj[key] = { default: value, select: true, set: function(newName) { if (newName === value) { return value; } throw new Error('Can\'t set discriminator key "' + key + '"'); }, $skipDiscriminatorCheck: true }; obj[key][schema.options.typeKey] = existingPath ? existingPath.instance : String; schema.add(obj); schema.discriminatorMapping = { key: key, value: value, isRoot: false }; if (baseSchema.options.collection) { schema.options.collection = baseSchema.options.collection; } const toJSON = schema.options.toJSON; const toObject = schema.options.toObject; const _id = schema.options._id; const id = schema.options.id; const keys = Object.keys(schema.options); schema.options.discriminatorKey = baseSchema.options.discriminatorKey; for (const _key of keys) { if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { // Special case: compiling a model sets `pluralization = true` by default. Avoid throwing an error // for that case. See gh-9238 if (_key === 'pluralization' && schema.options[_key] == true && baseSchema.options[_key] == null) { continue; } if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) { throw new Error('Can\'t customize discriminator option ' + _key + ' (can only modify ' + Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') + ')'); } } } schema.options = utils.clone(baseSchema.options); if (toJSON) schema.options.toJSON = toJSON; if (toObject) schema.options.toObject = toObject; if (typeof _id !== 'undefined') { schema.options._id = _id; } schema.options.id = id; schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks); schema.plugins = Array.prototype.slice.call(baseSchema.plugins); schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema } // merges base schema into new discriminator schema and sets new type field. merge(schema, model.schema); if (!model.discriminators) { model.discriminators = {}; } if (!model.schema.discriminatorMapping) { model.schema.discriminatorMapping = { key: key, value: null, isRoot: true }; } if (!model.schema.discriminators) { model.schema.discriminators = {}; } model.schema.discriminators[name] = schema; if (model.discriminators[name]) { throw new Error('Discriminator with name "' + name + '" already exists'); } return schema; }; },{"../../schema/mixed":358,"../../utils":381,"../document/compile":300,"../get":303}],312:[function(require,module,exports){ 'use strict'; const MongooseError = require('../../error/mongooseError'); const util = require('util'); module.exports = validateRef; function validateRef(ref, path) { if (typeof ref === 'string') { return; } if (typeof ref === 'function') { return; } throw new MongooseError('Invalid ref at path "' + path + '". Got ' + util.inspect(ref, { depth: 0 })); } },{"../../error/mongooseError":281,"util":414}],313:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function isDefiningProjection(val) { if (val == null) { // `undefined` or `null` become exclusive projections return true; } if (typeof val === 'object') { // Only cases where a value does **not** define whether the whole projection // is inclusive or exclusive are `$meta` and `$slice`. return !('$meta' in val) && !('$slice' in val); } return true; }; },{}],314:[function(require,module,exports){ 'use strict'; const isDefiningProjection = require('./isDefiningProjection'); /*! * ignore */ module.exports = function isExclusive(projection) { const keys = Object.keys(projection); let ki = keys.length; let exclude = null; if (ki === 1 && keys[0] === '_id') { exclude = !!projection[keys[ki]]; } else { while (ki--) { // Does this projection explicitly define inclusion/exclusion? // Explicitly avoid `$meta` and `$slice` if (keys[ki] !== '_id' && isDefiningProjection(projection[keys[ki]])) { exclude = !projection[keys[ki]]; break; } } } return exclude; }; },{"./isDefiningProjection":313}],315:[function(require,module,exports){ (function (process){ 'use strict'; const PromiseProvider = require('../promise_provider'); const emittedSymbol = Symbol.for('mongoose:emitted'); module.exports = function promiseOrCallback(callback, fn, ee, Promise) { if (typeof callback === 'function') { return fn(function(error) { if (error != null) { if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { error[emittedSymbol] = true; ee.emit('error', error); } try { callback(error); } catch (error) { return process.nextTick(() => { throw error; }); } return; } callback.apply(this, arguments); }); } Promise = Promise || PromiseProvider.get(); return new Promise((resolve, reject) => { fn(function(error, res) { if (error != null) { if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { error[emittedSymbol] = true; ee.emit('error', error); } return reject(error); } if (arguments.length > 2) { return resolve(Array.prototype.slice.call(arguments, 1)); } resolve(res); }); }); }; }).call(this,require('_process')) },{"../promise_provider":346,"_process":399}],316:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = applyQueryMiddleware; /*! * ignore */ applyQueryMiddleware.middlewareFunctions = [ 'count', 'countDocuments', 'deleteMany', 'deleteOne', 'distinct', 'estimatedDocumentCount', 'find', 'findOne', 'findOneAndDelete', 'findOneAndRemove', 'findOneAndReplace', 'findOneAndUpdate', 'remove', 'replaceOne', 'update', 'updateMany', 'updateOne', 'validate' ]; /*! * Apply query middleware * * @param {Query} query constructor * @param {Model} model */ function applyQueryMiddleware(Query, model) { const kareemOptions = { useErrorHandlers: true, numCallbackParams: 1, nullResultByDefault: true }; const middleware = model.hooks.filter(hook => { const contexts = _getContexts(hook); if (hook.name === 'updateOne') { return contexts.query == null || !!contexts.query; } if (hook.name === 'deleteOne') { return !!contexts.query || Object.keys(contexts).length === 0; } if (hook.name === 'validate' || hook.name === 'remove') { return !!contexts.query; } if (hook.query != null || hook.document != null) { return !!hook.query; } return true; }); // `update()` thunk has a different name because `_update` was already taken Query.prototype._execUpdate = middleware.createWrapper('update', Query.prototype._execUpdate, null, kareemOptions); // `distinct()` thunk has a different name because `_distinct` was already taken Query.prototype.__distinct = middleware.createWrapper('distinct', Query.prototype.__distinct, null, kareemOptions); // `validate()` doesn't have a thunk because it doesn't execute a query. Query.prototype.validate = middleware.createWrapper('validate', Query.prototype.validate, null, kareemOptions); applyQueryMiddleware.middlewareFunctions. filter(v => v !== 'update' && v !== 'distinct' && v !== 'validate'). forEach(fn => { Query.prototype[`_${fn}`] = middleware.createWrapper(fn, Query.prototype[`_${fn}`], null, kareemOptions); }); } function _getContexts(hook) { const ret = {}; if (hook.hasOwnProperty('query')) { ret.query = hook.query; } if (hook.hasOwnProperty('document')) { ret.document = hook.document; } return ret; } },{}],317:[function(require,module,exports){ 'use strict'; const specialKeys = new Set([ '$ref', '$id', '$db' ]); module.exports = function isOperator(path) { return path.startsWith('$') && !specialKeys.has(path); }; },{}],318:[function(require,module,exports){ 'use strict'; module.exports = function addAutoId(schema) { const _obj = { _id: { auto: true } }; _obj._id[schema.options.typeKey] = 'ObjectId'; schema.add(_obj); }; },{}],319:[function(require,module,exports){ 'use strict'; /** * For consistency's sake, we replace positional operator `$` and array filters * `$[]` and `$[foo]` with `0` when looking up schema paths. */ module.exports = function cleanPositionalOperators(path) { return path. replace(/\.\$(\[[^\]]*\])?\./g, '.0.'). replace(/\.(\[[^\]]*\])?\$$/g, '.0'); }; },{}],320:[function(require,module,exports){ 'use strict'; const get = require('../get'); const helperIsObject = require('../isObject'); /*! * Gather all indexes defined in the schema, including single nested, * document arrays, and embedded discriminators. */ module.exports = function getIndexes(schema) { let indexes = []; const schemaStack = new WeakMap(); const indexTypes = schema.constructor.indexTypes; const indexByName = new Map(); collectIndexes(schema); return indexes; function collectIndexes(schema, prefix, baseSchema) { // Ignore infinitely nested schemas, if we've already seen this schema // along this path there must be a cycle if (schemaStack.has(schema)) { return; } schemaStack.set(schema, true); prefix = prefix || ''; const keys = Object.keys(schema.paths); for (const key of keys) { const path = schema.paths[key]; if (baseSchema != null && baseSchema.paths[key]) { // If looking at an embedded discriminator schema, don't look at paths // that the continue; } if (path.$isMongooseDocumentArray || path.$isSingleNested) { if (get(path, 'options.excludeIndexes') !== true && get(path, 'schemaOptions.excludeIndexes') !== true && get(path, 'schema.options.excludeIndexes') !== true) { collectIndexes(path.schema, prefix + key + '.'); } if (path.schema.discriminators != null) { const discriminators = path.schema.discriminators; const discriminatorKeys = Object.keys(discriminators); for (const discriminatorKey of discriminatorKeys) { collectIndexes(discriminators[discriminatorKey], prefix + key + '.', path.schema); } } // Retained to minimize risk of backwards breaking changes due to // gh-6113 if (path.$isMongooseDocumentArray) { continue; } } const index = path._index || (path.caster && path.caster._index); if (index !== false && index !== null && index !== undefined) { const field = {}; const isObject = helperIsObject(index); const options = isObject ? index : {}; const type = typeof index === 'string' ? index : isObject ? index.type : false; if (type && indexTypes.indexOf(type) !== -1) { field[prefix + key] = type; } else if (options.text) { field[prefix + key] = 'text'; delete options.text; } else { const isDescendingIndex = Number(index) === -1; field[prefix + key] = isDescendingIndex ? -1 : 1; } delete options.type; if (!('background' in options)) { options.background = true; } if (schema.options.autoIndex != null) { options._autoIndex = schema.options.autoIndex; } const indexName = options && options.name; if (typeof indexName === 'string') { if (indexByName.has(indexName)) { Object.assign(indexByName.get(indexName), field); } else { indexes.push([field, options]); indexByName.set(indexName, field); } } else { indexes.push([field, options]); indexByName.set(indexName, field); } } } schemaStack.delete(schema); if (prefix) { fixSubIndexPaths(schema, prefix); } else { schema._indexes.forEach(function(index) { if (!('background' in index[1])) { index[1].background = true; } }); indexes = indexes.concat(schema._indexes); } } /*! * Checks for indexes added to subdocs using Schema.index(). * These indexes need their paths prefixed properly. * * schema._indexes = [ [indexObj, options], [indexObj, options] ..] */ function fixSubIndexPaths(schema, prefix) { const subindexes = schema._indexes; const len = subindexes.length; for (let i = 0; i < len; ++i) { const indexObj = subindexes[i][0]; const indexOptions = subindexes[i][1]; const keys = Object.keys(indexObj); const klen = keys.length; const newindex = {}; // use forward iteration, order matters for (let j = 0; j < klen; ++j) { const key = keys[j]; newindex[prefix + key] = indexObj[key]; } const newIndexOptions = Object.assign({}, indexOptions); if (indexOptions != null && indexOptions.partialFilterExpression != null) { newIndexOptions.partialFilterExpression = {}; const partialFilterExpression = indexOptions.partialFilterExpression; for (const key of Object.keys(partialFilterExpression)) { newIndexOptions.partialFilterExpression[prefix + key] = partialFilterExpression[key]; } } indexes.push([newindex, newIndexOptions]); } } }; },{"../get":303,"../isObject":308}],321:[function(require,module,exports){ 'use strict'; const addAutoId = require('./addAutoId'); module.exports = function handleIdOption(schema, options) { if (options == null || options._id == null) { return schema; } schema = schema.clone(); if (!options._id) { schema.remove('_id'); schema.options._id = false; } else if (!schema.paths['_id']) { addAutoId(schema); schema.options._id = true; } return schema; }; },{"./addAutoId":318}],322:[function(require,module,exports){ 'use strict'; module.exports = handleTimestampOption; /*! * ignore */ function handleTimestampOption(arg, prop) { if (arg == null) { return null; } if (typeof arg === 'boolean') { return prop; } if (typeof arg[prop] === 'boolean') { return arg[prop] ? prop : null; } if (!(prop in arg)) { return prop; } return arg[prop]; } },{}],323:[function(require,module,exports){ 'use strict'; module.exports = function merge(s1, s2) { s1.add(s2.tree || {}); s1.callQueue = s1.callQueue.concat(s2.callQueue); s1.method(s2.methods); s1.static(s2.statics); for (const query in s2.query) { s1.query[query] = s2.query[query]; } for (const virtual in s2.virtuals) { s1.virtuals[virtual] = s2.virtuals[virtual].clone(); } s1.s.hooks.merge(s2.s.hooks, false); }; },{}],324:[function(require,module,exports){ 'use strict'; const StrictModeError = require('../../error/strict'); /*! * ignore */ module.exports = function(schematype) { if (schematype.$immutable) { schematype.$immutableSetter = createImmutableSetter(schematype.path, schematype.options.immutable); schematype.set(schematype.$immutableSetter); } else if (schematype.$immutableSetter) { schematype.setters = schematype.setters. filter(fn => fn !== schematype.$immutableSetter); delete schematype.$immutableSetter; } }; function createImmutableSetter(path, immutable) { return function immutableSetter(v) { if (this == null || this.$__ == null) { return v; } if (this.isNew) { return v; } const _immutable = typeof immutable === 'function' ? immutable.call(this, this) : immutable; if (!_immutable) { return v; } const _value = this.$__getValue(path); if (this.$__.strictMode === 'throw' && v !== _value) { throw new StrictModeError(path, 'Path `' + path + '` is immutable ' + 'and strict mode is set to throw.', true); } return _value; }; } },{"../../error/strict":288}],325:[function(require,module,exports){ 'use strict'; module.exports = new Set(['__proto__', 'constructor', 'prototype']); },{}],326:[function(require,module,exports){ 'use strict'; exports.arrayAtomicsSymbol = Symbol('mongoose#Array#_atomics'); exports.arrayParentSymbol = Symbol('mongoose#Array#_parent'); exports.arrayPathSymbol = Symbol('mongoose#Array#_path'); exports.arraySchemaSymbol = Symbol('mongoose#Array#_schema'); exports.documentArrayParent = Symbol('mongoose:documentArrayParent'); exports.documentIsSelected = Symbol('mongoose#Document#isSelected'); exports.documentIsModified = Symbol('mongoose#Document#isModified'); exports.documentModifiedPaths = Symbol('mongoose#Document#modifiedPaths'); exports.documentSchemaSymbol = Symbol('mongoose#Document#schema'); exports.getSymbol = Symbol('mongoose#Document#get'); exports.modelSymbol = Symbol('mongoose#Model'); exports.objectIdSymbol = Symbol('mongoose#ObjectId'); exports.populateModelSymbol = Symbol('mongoose.PopulateOptions#Model'); exports.schemaTypeSymbol = Symbol('mongoose#schemaType'); exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments'); exports.scopeSymbol = Symbol('mongoose#Document#scope'); exports.validatorErrorSymbol = Symbol('mongoose:validatorError'); },{}],327:[function(require,module,exports){ 'use strict'; const applyTimestampsToChildren = require('../update/applyTimestampsToChildren'); const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate'); const get = require('../get'); const handleTimestampOption = require('../schema/handleTimestampOption'); const symbols = require('../../schema/symbols'); module.exports = function setupTimestamps(schema, timestamps) { const childHasTimestamp = schema.childSchemas.find(withTimestamp); function withTimestamp(s) { const ts = s.schema.options.timestamps; return !!ts; } if (!timestamps && !childHasTimestamp) { return; } const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ? timestamps.currentTime : null; const schemaAdditions = {}; schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; if (updatedAt && !schema.paths[updatedAt]) { schemaAdditions[updatedAt] = Date; } if (createdAt && !schema.paths[createdAt]) { schemaAdditions[createdAt] = Date; } schema.add(schemaAdditions); schema.pre('save', function(next) { const timestampOption = get(this, '$__.saveOptions.timestamps'); if (timestampOption === false) { return next(); } const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false; const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false; const defaultTimestamp = currentTime != null ? currentTime() : (this.ownerDocument ? this.ownerDocument() : this).constructor.base.now(); const auto_id = this._id && this._id.auto; if (!skipCreatedAt && createdAt && !this.get(createdAt) && this.isSelected(createdAt)) { this.$set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp); } if (!skipUpdatedAt && updatedAt && (this.isNew || this.isModified())) { let ts = defaultTimestamp; if (this.isNew) { if (createdAt != null) { ts = this.$__getValue(createdAt); } else if (auto_id) { ts = this._id.getTimestamp(); } } this.$set(updatedAt, ts); } next(); }); schema.methods.initializeTimestamps = function() { const ts = currentTime != null ? currentTime() : this.constructor.base.now(); if (createdAt && !this.get(createdAt)) { this.$set(createdAt, ts); } if (updatedAt && !this.get(updatedAt)) { this.$set(updatedAt, ts); } return this; }; _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; const opts = { query: true, model: false }; schema.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate); schema.pre('replaceOne', opts, _setTimestampsOnUpdate); schema.pre('update', opts, _setTimestampsOnUpdate); schema.pre('updateOne', opts, _setTimestampsOnUpdate); schema.pre('updateMany', opts, _setTimestampsOnUpdate); function _setTimestampsOnUpdate(next) { const now = currentTime != null ? currentTime() : this.model.base.now(); applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(), this.options, this.schema); applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); next(); } }; },{"../../schema/symbols":368,"../get":303,"../schema/handleTimestampOption":322,"../update/applyTimestampsToChildren":328,"../update/applyTimestampsToUpdate":329}],328:[function(require,module,exports){ 'use strict'; const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); const handleTimestampOption = require('../schema/handleTimestampOption'); module.exports = applyTimestampsToChildren; /*! * ignore */ function applyTimestampsToChildren(now, update, schema) { if (update == null) { return; } const keys = Object.keys(update); const hasDollarKey = keys.some(key => key.startsWith('$')); if (hasDollarKey) { if (update.$push) { for (const key of Object.keys(update.$push)) { const $path = schema.path(key); if (update.$push[key] && $path && $path.$isMongooseDocumentArray && $path.schema.options.timestamps) { const timestamps = $path.schema.options.timestamps; const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (update.$push[key].$each) { update.$push[key].$each.forEach(function(subdoc) { if (updatedAt != null) { subdoc[updatedAt] = now; } if (createdAt != null) { subdoc[createdAt] = now; } }); } else { if (updatedAt != null) { update.$push[key][updatedAt] = now; } if (createdAt != null) { update.$push[key][createdAt] = now; } } } } } if (update.$set != null) { const keys = Object.keys(update.$set); for (const key of keys) { applyTimestampsToUpdateKey(schema, key, update.$set, now); } } } const updateKeys = Object.keys(update).filter(key => !key.startsWith('$')); for (const key of updateKeys) { applyTimestampsToUpdateKey(schema, key, update, now); } } function applyTimestampsToDocumentArray(arr, schematype, now) { const timestamps = schematype.schema.options.timestamps; if (!timestamps) { return; } const len = arr.length; const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); for (let i = 0; i < len; ++i) { if (updatedAt != null) { arr[i][updatedAt] = now; } if (createdAt != null) { arr[i][createdAt] = now; } applyTimestampsToChildren(now, arr[i], schematype.schema); } } function applyTimestampsToSingleNested(subdoc, schematype, now) { const timestamps = schematype.schema.options.timestamps; if (!timestamps) { return; } const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (updatedAt != null) { subdoc[updatedAt] = now; } if (createdAt != null) { subdoc[createdAt] = now; } applyTimestampsToChildren(now, subdoc, schematype.schema); } function applyTimestampsToUpdateKey(schema, key, update, now) { // Replace positional operator `$` and array filters `$[]` and `$[.*]` const keyToSearch = cleanPositionalOperators(key); const path = schema.path(keyToSearch); if (!path) { return; } const parentSchemaTypes = []; const pieces = keyToSearch.split('.'); for (let i = pieces.length - 1; i > 0; --i) { const s = schema.path(pieces.slice(0, i).join('.')); if (s != null && (s.$isMongooseDocumentArray || s.$isSingleNested)) { parentSchemaTypes.push({ parentPath: key.split('.').slice(0, i).join('.'), parentSchemaType: s }); } } if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { applyTimestampsToDocumentArray(update[key], path, now); } else if (update[key] && path.$isSingleNested) { applyTimestampsToSingleNested(update[key], path, now); } else if (parentSchemaTypes.length > 0) { for (const item of parentSchemaTypes) { const parentPath = item.parentPath; const parentSchemaType = item.parentSchemaType; const timestamps = parentSchemaType.schema.options.timestamps; const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (!timestamps || updatedAt == null) { continue; } if (parentSchemaType.$isSingleNested) { // Single nested is easy update[parentPath + '.' + updatedAt] = now; } else if (parentSchemaType.$isMongooseDocumentArray) { let childPath = key.substr(parentPath.length + 1); if (/^\d+$/.test(childPath)) { update[parentPath + '.' + childPath][updatedAt] = now; continue; } const firstDot = childPath.indexOf('.'); childPath = firstDot !== -1 ? childPath.substr(0, firstDot) : childPath; update[parentPath + '.' + childPath + '.' + updatedAt] = now; } } } else if (path.schema != null && path.schema != schema && update[key]) { const timestamps = path.schema.options.timestamps; const createdAt = handleTimestampOption(timestamps, 'createdAt'); const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (!timestamps) { return; } if (updatedAt != null) { update[key][updatedAt] = now; } if (createdAt != null) { update[key][createdAt] = now; } } } },{"../schema/cleanPositionalOperators":319,"../schema/handleTimestampOption":322}],329:[function(require,module,exports){ 'use strict'; /*! * ignore */ const get = require('../get'); module.exports = applyTimestampsToUpdate; /*! * ignore */ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) { const updates = currentUpdate; let _updates = updates; const overwrite = get(options, 'overwrite', false); const timestamps = get(options, 'timestamps', true); // Support skipping timestamps at the query level, see gh-6980 if (!timestamps || updates == null) { return currentUpdate; } const skipCreatedAt = timestamps != null && timestamps.createdAt === false; const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false; if (overwrite) { if (currentUpdate && currentUpdate.$set) { currentUpdate = currentUpdate.$set; updates.$set = {}; _updates = updates.$set; } if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) { _updates[updatedAt] = now; } if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) { _updates[createdAt] = now; } return updates; } currentUpdate = currentUpdate || {}; if (Array.isArray(updates)) { // Update with aggregation pipeline updates.push({ $set: { updatedAt: now } }); return updates; } updates.$set = updates.$set || {}; if (!skipUpdatedAt && updatedAt && (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { let timestampSet = false; if (updatedAt.indexOf('.') !== -1) { const pieces = updatedAt.split('.'); for (let i = 1; i < pieces.length; ++i) { const remnant = pieces.slice(-i).join('.'); const start = pieces.slice(0, -i).join('.'); if (currentUpdate[start] != null) { currentUpdate[start][remnant] = now; timestampSet = true; break; } else if (currentUpdate.$set && currentUpdate.$set[start]) { currentUpdate.$set[start][remnant] = now; timestampSet = true; break; } } } if (!timestampSet) { updates.$set[updatedAt] = now; } if (updates.hasOwnProperty(updatedAt)) { delete updates[updatedAt]; } } if (!skipCreatedAt && createdAt) { if (currentUpdate[createdAt]) { delete currentUpdate[createdAt]; } if (currentUpdate.$set && currentUpdate.$set[createdAt]) { delete currentUpdate.$set[createdAt]; } let timestampSet = false; if (createdAt.indexOf('.') !== -1) { const pieces = createdAt.split('.'); for (let i = 1; i < pieces.length; ++i) { const remnant = pieces.slice(-i).join('.'); const start = pieces.slice(0, -i).join('.'); if (currentUpdate[start] != null) { currentUpdate[start][remnant] = now; timestampSet = true; break; } else if (currentUpdate.$set && currentUpdate.$set[start]) { currentUpdate.$set[start][remnant] = now; timestampSet = true; break; } } } if (!timestampSet) { updates.$setOnInsert = updates.$setOnInsert || {}; updates.$setOnInsert[createdAt] = now; } } if (Object.keys(updates.$set).length === 0) { delete updates.$set; } return updates; } },{"../get":303}],330:[function(require,module,exports){ /*! * Dependencies */ 'use strict'; const StateMachine = require('./statemachine'); const ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); module.exports = exports = InternalCache; function InternalCache() { this.strictMode = undefined; this.selected = undefined; this.shardval = undefined; this.saveError = undefined; this.validationError = undefined; this.adhocPaths = undefined; this.removing = undefined; this.inserting = undefined; this.saving = undefined; this.version = undefined; this.getters = {}; this._id = undefined; this.populate = undefined; // what we want to populate in this doc this.populated = undefined;// the _ids that have been populated this.wasPopulated = false; // if this doc was the result of a population this.scope = undefined; this.activePaths = new ActiveRoster; this.pathsToScopes = {}; this.cachedRequired = {}; this.session = null; this.$setCalled = new Set(); // embedded docs this.ownerDocument = undefined; this.fullPath = undefined; } },{"./statemachine":370}],331:[function(require,module,exports){ 'use strict'; /*! * ignore */ exports.internalToObjectOptions = { transform: false, virtuals: false, getters: false, _skipDepopulateTopLevel: true, depopulate: true, flattenDecimals: false }; },{}],332:[function(require,module,exports){ 'use strict'; const clone = require('../helpers/clone'); class PopulateOptions { constructor(obj) { this._docs = {}; this._childDocs = []; if (obj == null) { return; } obj = clone(obj); Object.assign(this, obj); if (typeof obj.subPopulate === 'object') { this.populate = obj.subPopulate; } if (obj.perDocumentLimit != null && obj.limit != null) { throw new Error('Can not use `limit` and `perDocumentLimit` at the same time. Path: `' + obj.path + '`.'); } } } /** * The connection used to look up models by name. If not specified, Mongoose * will default to using the connection associated with the model in * `PopulateOptions#model`. * * @memberOf PopulateOptions * @property {Connection} connection * @api public */ module.exports = PopulateOptions; },{"../helpers/clone":293}],333:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on an Array schematype. * * ####Example: * * const schema = new Schema({ tags: [String] }); * schema.path('tags').options; // SchemaArrayOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaArrayOptions */ class SchemaArrayOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If this is an array of strings, an array of allowed values for this path. * Throws an error if this array isn't an array of strings. * * @api public * @property enum * @memberOf SchemaArrayOptions * @type Array * @instance */ Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts); /** * If set, specifies the type of this array's values. Equivalent to setting * `type` to an array whose first element is `of`. * * ####Example: * * // `arr` is an array of numbers. * new Schema({ arr: [Number] }); * // Equivalent way to define `arr` as an array of numbers * new Schema({ arr: { type: Array, of: Number } }); * * @api public * @property of * @memberOf SchemaArrayOptions * @type Function|String * @instance */ Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts); /*! * ignore */ module.exports = SchemaArrayOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],334:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Buffer schematype. * * ####Example: * * const schema = new Schema({ bitmap: Buffer }); * schema.path('bitmap').options; // SchemaBufferOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaBufferOptions */ class SchemaBufferOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * Set the default subtype for this buffer. * * @api public * @property subtype * @memberOf SchemaBufferOptions * @type Number * @instance */ Object.defineProperty(SchemaBufferOptions.prototype, 'subtype', opts); /*! * ignore */ module.exports = SchemaBufferOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],335:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Date schematype. * * ####Example: * * const schema = new Schema({ startedAt: Date }); * schema.path('startedAt').options; // SchemaDateOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaDateOptions */ class SchemaDateOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If set, Mongoose adds a validator that checks that this path is after the * given `min`. * * @api public * @property min * @memberOf SchemaDateOptions * @type Date * @instance */ Object.defineProperty(SchemaDateOptions.prototype, 'min', opts); /** * If set, Mongoose adds a validator that checks that this path is before the * given `max`. * * @api public * @property max * @memberOf SchemaDateOptions * @type Date * @instance */ Object.defineProperty(SchemaDateOptions.prototype, 'max', opts); /** * If set, Mongoose creates a TTL index on this path. * * @api public * @property expires * @memberOf SchemaDateOptions * @type Date * @instance */ Object.defineProperty(SchemaDateOptions.prototype, 'expires', opts); /*! * ignore */ module.exports = SchemaDateOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],336:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on an Document Array schematype. * * ####Example: * * const schema = new Schema({ users: [{ name: string }] }); * schema.path('users').options; // SchemaDocumentArrayOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaDocumentOptions */ class SchemaDocumentArrayOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If `true`, Mongoose will skip building any indexes defined in this array's schema. * If not set, Mongoose will build all indexes defined in this array's schema. * * ####Example: * * const childSchema = Schema({ name: { type: String, index: true } }); * // If `excludeIndexes` is `true`, Mongoose will skip building an index * // on `arr.name`. Otherwise, Mongoose will build an index on `arr.name`. * const parentSchema = Schema({ * arr: { type: [childSchema], excludeIndexes: true } * }); * * @api public * @property excludeIndexes * @memberOf SchemaDocumentArrayOptions * @type Array * @instance */ Object.defineProperty(SchemaDocumentArrayOptions.prototype, 'excludeIndexes', opts); /** * If set, overwrites the child schema's `_id` option. * * ####Example: * * const childSchema = Schema({ name: String }); * const parentSchema = Schema({ * child: { type: childSchema, _id: false } * }); * parentSchema.path('child').schema.options._id; // false * * @api public * @property _id * @memberOf SchemaDocumentArrayOptions * @type Array * @instance */ Object.defineProperty(SchemaDocumentArrayOptions.prototype, '_id', opts); /*! * ignore */ module.exports = SchemaDocumentArrayOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],337:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Map schematype. * * ####Example: * * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); * schema.path('socialMediaHandles').options; // SchemaMapOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaMapOptions */ class SchemaMapOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If set, specifies the type of this map's values. Mongoose will cast * this map's values to the given type. * * If not set, Mongoose will not cast the map's values. * * ####Example: * * // Mongoose will cast `socialMediaHandles` values to strings * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); * schema.path('socialMediaHandles').options.of; // String * * @api public * @property of * @memberOf SchemaMapOptions * @type Function|string * @instance */ Object.defineProperty(SchemaMapOptions.prototype, 'of', opts); module.exports = SchemaMapOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],338:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a Number schematype. * * ####Example: * * const schema = new Schema({ count: Number }); * schema.path('count').options; // SchemaNumberOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaNumberOptions */ class SchemaNumberOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If set, Mongoose adds a validator that checks that this path is at least the * given `min`. * * @api public * @property min * @memberOf SchemaNumberOptions * @type Number * @instance */ Object.defineProperty(SchemaNumberOptions.prototype, 'min', opts); /** * If set, Mongoose adds a validator that checks that this path is less than the * given `max`. * * @api public * @property max * @memberOf SchemaNumberOptions * @type Number * @instance */ Object.defineProperty(SchemaNumberOptions.prototype, 'max', opts); /** * If set, Mongoose adds a validator that checks that this path is strictly * equal to one of the given values. * * ####Example: * const schema = new Schema({ * favoritePrime: { * type: Number, * enum: [3, 5, 7] * } * }); * schema.path('favoritePrime').options.enum; // [3, 5, 7] * * @api public * @property enum * @memberOf SchemaNumberOptions * @type Array * @instance */ Object.defineProperty(SchemaNumberOptions.prototype, 'enum', opts); /** * Sets default [populate options](/docs/populate.html#query-conditions). * * ####Example: * const schema = new Schema({ * child: { * type: Number, * ref: 'Child', * populate: { select: 'name' } * } * }); * const Parent = mongoose.model('Parent', schema); * * // Automatically adds `.select('name')` * Parent.findOne().populate('child'); * * @api public * @property populate * @memberOf SchemaNumberOptions * @type Object * @instance */ Object.defineProperty(SchemaNumberOptions.prototype, 'populate', opts); /*! * ignore */ module.exports = SchemaNumberOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],339:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on an ObjectId schematype. * * ####Example: * * const schema = new Schema({ testId: mongoose.ObjectId }); * schema.path('testId').options; // SchemaObjectIdOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaObjectIdOptions */ class SchemaObjectIdOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If truthy, uses Mongoose's default built-in ObjectId path. * * @api public * @property auto * @memberOf SchemaObjectIdOptions * @type Boolean * @instance */ Object.defineProperty(SchemaObjectIdOptions.prototype, 'auto', opts); /** * Sets default [populate options](/docs/populate.html#query-conditions). * * ####Example: * const schema = new Schema({ * child: { * type: 'ObjectId', * ref: 'Child', * populate: { select: 'name' } * } * }); * const Parent = mongoose.model('Parent', schema); * * // Automatically adds `.select('name')` * Parent.findOne().populate('child'); * * @api public * @property populate * @memberOf SchemaObjectIdOptions * @type Object * @instance */ Object.defineProperty(SchemaObjectIdOptions.prototype, 'populate', opts); /*! * ignore */ module.exports = SchemaObjectIdOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],340:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a single nested schematype. * * ####Example: * * const schema = Schema({ child: Schema({ name: String }) }); * schema.path('child').options; // SchemaSingleNestedOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaSingleNestedOptions */ class SchemaSingleNestedOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * If set, overwrites the child schema's `_id` option. * * ####Example: * * const childSchema = Schema({ name: String }); * const parentSchema = Schema({ * child: { type: childSchema, _id: false } * }); * parentSchema.path('child').schema.options._id; // false * * @api public * @property of * @memberOf SchemaSingleNestedOptions * @type Function|string * @instance */ Object.defineProperty(SchemaSingleNestedOptions.prototype, '_id', opts); module.exports = SchemaSingleNestedOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],341:[function(require,module,exports){ 'use strict'; const SchemaTypeOptions = require('./SchemaTypeOptions'); /** * The options defined on a string schematype. * * ####Example: * * const schema = new Schema({ name: String }); * schema.path('name').options; // SchemaStringOptions instance * * @api public * @inherits SchemaTypeOptions * @constructor SchemaStringOptions */ class SchemaStringOptions extends SchemaTypeOptions {} const opts = require('./propertyOptions'); /** * Array of allowed values for this path * * @api public * @property enum * @memberOf SchemaStringOptions * @type Array * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'enum', opts); /** * Attach a validator that succeeds if the data string matches the given regular * expression, and fails otherwise. * * @api public * @property match * @memberOf SchemaStringOptions * @type RegExp * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'match', opts); /** * If truthy, Mongoose will add a custom setter that lowercases this string * using JavaScript's built-in `String#toLowerCase()`. * * @api public * @property lowercase * @memberOf SchemaStringOptions * @type Boolean * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'lowercase', opts); /** * If truthy, Mongoose will add a custom setter that removes leading and trailing * whitespace using JavaScript's built-in `String#trim()`. * * @api public * @property trim * @memberOf SchemaStringOptions * @type Boolean * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'trim', opts); /** * If truthy, Mongoose will add a custom setter that uppercases this string * using JavaScript's built-in `String#toUpperCase()`. * * @api public * @property uppercase * @memberOf SchemaStringOptions * @type Boolean * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'uppercase', opts); /** * If set, Mongoose will add a custom validator that ensures the given * string's `length` is at least the given number. * * Mongoose supports two different spellings for this option: `minLength` and `minlength`. * `minLength` is the recommended way to specify this option, but Mongoose also supports * `minlength` (lowercase "l"). * * @api public * @property minLength * @memberOf SchemaStringOptions * @type Number * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'minLength', opts); Object.defineProperty(SchemaStringOptions.prototype, 'minlength', opts); /** * If set, Mongoose will add a custom validator that ensures the given * string's `length` is at most the given number. * * Mongoose supports two different spellings for this option: `maxLength` and `maxlength`. * `maxLength` is the recommended way to specify this option, but Mongoose also supports * `maxlength` (lowercase "l"). * * @api public * @property maxLength * @memberOf SchemaStringOptions * @type Number * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'maxLength', opts); Object.defineProperty(SchemaStringOptions.prototype, 'maxlength', opts); /** * Sets default [populate options](/docs/populate.html#query-conditions). * * @api public * @property populate * @memberOf SchemaStringOptions * @type Object * @instance */ Object.defineProperty(SchemaStringOptions.prototype, 'populate', opts); /*! * ignore */ module.exports = SchemaStringOptions; },{"./SchemaTypeOptions":342,"./propertyOptions":344}],342:[function(require,module,exports){ 'use strict'; const clone = require('../helpers/clone'); /** * The options defined on a schematype. * * ####Example: * * const schema = new Schema({ name: String }); * schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true * * @api public * @constructor SchemaTypeOptions */ class SchemaTypeOptions { constructor(obj) { if (obj == null) { return this; } Object.assign(this, clone(obj)); } } const opts = require('./propertyOptions'); /** * The type to cast this path to. * * @api public * @property type * @memberOf SchemaTypeOptions * @type Function|String|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'type', opts); /** * Function or object describing how to validate this schematype. * * @api public * @property validate * @memberOf SchemaTypeOptions * @type Function|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'validate', opts); /** * Allows overriding casting logic for this individual path. If a string, the * given string overwrites Mongoose's default cast error message. * * ####Example: * * const schema = new Schema({ * num: { * type: Number, * cast: '{VALUE} is not a valid number' * } * }); * * // Throws 'CastError: "bad" is not a valid number' * schema.path('num').cast('bad'); * * const Model = mongoose.model('Test', schema); * const doc = new Model({ num: 'fail' }); * const err = doc.validateSync(); * * err.errors['num']; // 'CastError: "fail" is not a valid number' * * @api public * @property cast * @memberOf SchemaTypeOptions * @type String * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'cast', opts); /** * If true, attach a required validator to this path, which ensures this path * path cannot be set to a nullish value. If a function, Mongoose calls the * function and only checks for nullish values if the function returns a truthy value. * * @api public * @property required * @memberOf SchemaTypeOptions * @type Function|Boolean * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'required', opts); /** * The default value for this path. If a function, Mongoose executes the function * and uses the return value as the default. * * @api public * @property default * @memberOf SchemaTypeOptions * @type Function|Any * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'default', opts); /** * The model that `populate()` should use if populating this path. * * @api public * @property ref * @memberOf SchemaTypeOptions * @type Function|String * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'ref', opts); /** * Whether to include or exclude this path by default when loading documents * using `find()`, `findOne()`, etc. * * @api public * @property select * @memberOf SchemaTypeOptions * @type Boolean|Number * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'select', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will * build an index on this path when the model is compiled. * * @api public * @property index * @memberOf SchemaTypeOptions * @type Boolean|Number|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'index', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose * will build a unique index on this path when the * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator). * * @api public * @property unique * @memberOf SchemaTypeOptions * @type Boolean|Number * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'unique', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will * disallow changes to this path once the document * is saved to the database for the first time. Read more about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html). * * @api public * @property immutable * @memberOf SchemaTypeOptions * @type Function|Boolean * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'immutable', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will * build a sparse index on this path. * * @api public * @property sparse * @memberOf SchemaTypeOptions * @type Boolean|Number * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'sparse', opts); /** * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose * will build a text index on this path. * * @api public * @property text * @memberOf SchemaTypeOptions * @type Boolean|Number|Object * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'text', opts); /** * Define a transform function for this individual schema type. * Only called when calling `toJSON()` or `toObject()`. * * ####Example: * * const schema = Schema({ * myDate: { * type: Date, * transform: v => v.getFullYear() * } * }); * const Model = mongoose.model('Test', schema); * * const doc = new Model({ myDate: new Date('2019/06/01') }); * doc.myDate instanceof Date; // true * * const res = doc.toObject({ transform: true }); * res.myDate; // 2019 * * @api public * @property transform * @memberOf SchemaTypeOptions * @type Function * @instance */ Object.defineProperty(SchemaTypeOptions.prototype, 'transform', opts); module.exports = SchemaTypeOptions; },{"../helpers/clone":293,"./propertyOptions":344}],343:[function(require,module,exports){ 'use strict'; const opts = require('./propertyOptions'); class VirtualOptions { constructor(obj) { Object.assign(this, obj); if (obj != null && obj.options != null) { this.options = Object.assign({}, obj.options); } } } /** * Marks this virtual as a populate virtual, and specifies the model to * use for populate. * * @api public * @property ref * @memberOf VirtualOptions * @type String|Model|Function * @instance */ Object.defineProperty(VirtualOptions.prototype, 'ref', opts); /** * Marks this virtual as a populate virtual, and specifies the path that * contains the name of the model to populate * * @api public * @property refPath * @memberOf VirtualOptions * @type String|Function * @instance */ Object.defineProperty(VirtualOptions.prototype, 'refPath', opts); /** * The name of the property in the local model to match to `foreignField` * in the foreign model. * * @api public * @property localField * @memberOf VirtualOptions * @type String|Function * @instance */ Object.defineProperty(VirtualOptions.prototype, 'localField', opts); /** * The name of the property in the foreign model to match to `localField` * in the local model. * * @api public * @property foreignField * @memberOf VirtualOptions * @type String|Function * @instance */ Object.defineProperty(VirtualOptions.prototype, 'foreignField', opts); /** * Whether to populate this virtual as a single document (true) or an * array of documents (false). * * @api public * @property justOne * @memberOf VirtualOptions * @type Boolean * @instance */ Object.defineProperty(VirtualOptions.prototype, 'justOne', opts); /** * If true, populate just the number of documents where `localField` * matches `foreignField`, as opposed to the documents themselves. * * If `count` is set, it overrides `justOne`. * * @api public * @property count * @memberOf VirtualOptions * @type Boolean * @instance */ Object.defineProperty(VirtualOptions.prototype, 'count', opts); /** * Add an additional filter to populate, in addition to `localField` * matches `foreignField`. * * @api public * @property match * @memberOf VirtualOptions * @type Object|Function * @instance */ Object.defineProperty(VirtualOptions.prototype, 'match', opts); /** * Additional options to pass to the query used to `populate()`: * * - `sort` * - `skip` * - `limit` * * @api public * @property options * @memberOf VirtualOptions * @type Object * @instance */ Object.defineProperty(VirtualOptions.prototype, 'options', opts); /** * If true, add a `skip` to the query used to `populate()`. * * @api public * @property skip * @memberOf VirtualOptions * @type Number * @instance */ Object.defineProperty(VirtualOptions.prototype, 'skip', opts); /** * If true, add a `limit` to the query used to `populate()`. * * @api public * @property limit * @memberOf VirtualOptions * @type Number * @instance */ Object.defineProperty(VirtualOptions.prototype, 'limit', opts); /** * The `limit` option for `populate()` has [some unfortunate edge cases](/docs/populate.html#query-conditions) * when working with multiple documents, like `.find().populate()`. The * `perDocumentLimit` option makes `populate()` execute a separate query * for each document returned from `find()` to ensure each document * gets up to `perDocumentLimit` populated docs if possible. * * @api public * @property perDocumentLimit * @memberOf VirtualOptions * @type Number * @instance */ Object.defineProperty(VirtualOptions.prototype, 'perDocumentLimit', opts); module.exports = VirtualOptions; },{"./propertyOptions":344}],344:[function(require,module,exports){ 'use strict'; module.exports = Object.freeze({ enumerable: true, configurable: true, writable: true, value: void 0 }); },{}],345:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function(schema) { // ensure the documents receive an id getter unless disabled const autoIdGetter = !schema.paths['id'] && (!schema.options.noVirtualId && schema.options.id); if (!autoIdGetter) { return; } schema.virtual('id').get(idGetter); }; /*! * Returns this documents _id cast to a string. */ function idGetter() { if (this._id != null) { return String(this._id); } return null; } },{}],346:[function(require,module,exports){ (function (global){ /*! * ignore */ 'use strict'; const assert = require('assert'); const mquery = require('mquery'); /** * Helper for multiplexing promise implementations * * @api private */ const store = { _promise: null }; /** * Get the current promise constructor * * @api private */ store.get = function() { return store._promise; }; /** * Set the current promise constructor * * @api private */ store.set = function(lib) { assert.ok(typeof lib === 'function', `mongoose.Promise must be a function, got ${lib}`); store._promise = lib; mquery.Promise = lib; }; /*! * Use native promises by default */ store.set(global.Promise); module.exports = store; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"assert":89,"mquery":391}],347:[function(require,module,exports){ 'use strict'; /*! * Module dependencies */ const checkEmbeddedDiscriminatorKeyProjection = require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection'); const get = require('./helpers/get'); const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue'); const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); const clone = require('./helpers/clone'); /*! * Prepare a set of path options for query population. * * @param {Query} query * @param {Object} options * @return {Array} */ exports.preparePopulationOptions = function preparePopulationOptions(query, options) { const _populate = query.options.populate; const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); // lean options should trickle through all queries if (options.lean != null) { pop. filter(p => get(p, 'options.lean') == null). forEach(makeLean(options.lean)); } return pop; }; /*! * Prepare a set of path options for query population. This is the MongooseQuery * version * * @param {Query} query * @param {Object} options * @return {Array} */ exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { const _populate = query._mongooseOptions.populate; const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); // lean options should trickle through all queries if (options.lean != null) { pop. filter(p => get(p, 'options.lean') == null). forEach(makeLean(options.lean)); } const session = get(query, 'options.session', null); if (session != null) { pop.forEach(path => { if (path.options == null) { path.options = { session: session }; return; } if (!('session' in path.options)) { path.options.session = session; } }); } const projection = query._fieldsForExec(); pop.forEach(p => { p._queryProjection = projection; }); return pop; }; /*! * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, * it returns an instance of the given model. * * @param {Model} model * @param {Object} doc * @param {Object} fields * * @return {Document} */ exports.createModel = function createModel(model, doc, fields, userProvidedFields) { model.hooks.execPreSync('createModel', doc); const discriminatorMapping = model.schema ? model.schema.discriminatorMapping : null; const key = discriminatorMapping && discriminatorMapping.isRoot ? discriminatorMapping.key : null; const value = doc[key]; if (key && value && model.discriminators) { const discriminator = model.discriminators[value] || getDiscriminatorByValue(model, value); if (discriminator) { const _fields = clone(userProvidedFields); exports.applyPaths(_fields, discriminator.schema); return new discriminator(undefined, _fields, true); } } return new model(undefined, fields, { skipId: true, isNew: false, willInit: true }); }; /*! * ignore */ exports.applyPaths = function applyPaths(fields, schema) { // determine if query is selecting or excluding fields let exclude; let keys; let keyIndex; if (fields) { keys = Object.keys(fields); keyIndex = keys.length; while (keyIndex--) { if (keys[keyIndex][0] === '+') { continue; } const field = fields[keys[keyIndex]]; // Skip `$meta` and `$slice` if (!isDefiningProjection(field)) { continue; } exclude = !field; break; } } // if selecting, apply default schematype select:true fields // if excluding, apply schematype select:false fields const selected = []; const excluded = []; const stack = []; analyzeSchema(schema); switch (exclude) { case true: for (const fieldName of excluded) { fields[fieldName] = 0; } break; case false: if (schema && schema.paths['_id'] && schema.paths['_id'].options && schema.paths['_id'].options.select === false) { fields._id = 0; } for (const fieldName of selected) { fields[fieldName] = fields[fieldName] || 1; } break; case undefined: if (fields == null) { break; } // Any leftover plus paths must in the schema, so delete them (gh-7017) for (const key of Object.keys(fields || {})) { if (key.startsWith('+')) { delete fields[key]; } } // user didn't specify fields, implies returning all fields. // only need to apply excluded fields and delete any plus paths for (const fieldName of excluded) { fields[fieldName] = 0; } break; } function analyzeSchema(schema, prefix) { prefix || (prefix = ''); // avoid recursion if (stack.indexOf(schema) !== -1) { return []; } stack.push(schema); const addedPaths = []; schema.eachPath(function(path, type) { if (prefix) path = prefix + '.' + path; const addedPath = analyzePath(path, type); if (addedPath != null) { addedPaths.push(addedPath); } // nested schemas if (type.schema) { const _addedPaths = analyzeSchema(type.schema, path); // Special case: if discriminator key is the only field that would // be projected in, remove it. if (exclude === false) { checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema, selected, _addedPaths); } } }); stack.pop(); return addedPaths; } function analyzePath(path, type) { const plusPath = '+' + path; const hasPlusPath = fields && plusPath in fields; if (hasPlusPath) { // forced inclusion delete fields[plusPath]; } if (typeof type.selected !== 'boolean') return; if (hasPlusPath) { // forced inclusion delete fields[plusPath]; // if there are other fields being included, add this one // if no other included fields, leave this out (implied inclusion) if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { fields[path] = 1; } return; } // check for parent exclusions const pieces = path.split('.'); let cur = ''; for (let i = 0; i < pieces.length; ++i) { cur += cur.length ? '.' + pieces[i] : pieces[i]; if (excluded.indexOf(cur) !== -1) { return; } } // Special case: if user has included a parent path of a discriminator key, // don't explicitly project in the discriminator key because that will // project out everything else under the parent path if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) { let cur = ''; for (let i = 0; i < pieces.length; ++i) { cur += (cur.length === 0 ? '' : '.') + pieces[i]; const projection = get(fields, cur, false) || get(fields, cur + '.$', false); if (projection && typeof projection !== 'object') { return; } } } (type.selected ? selected : excluded).push(path); return path; } }; /*! * Set each path query option to lean * * @param {Object} option */ function makeLean(val) { return function(option) { option.options || (option.options = {}); if (val != null && Array.isArray(val.virtuals)) { val = Object.assign({}, val); val.virtuals = val.virtuals. filter(path => typeof path === 'string' && path.startsWith(option.path + '.')). map(path => path.slice(option.path.length + 1)); } option.options.lean = val; }; } /*! * Handle the `WriteOpResult` from the server */ exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) { return function _handleDeleteWriteOpResult(error, res) { if (error) { return callback(error); } const mongooseResult = Object.assign({}, res.result); if (get(res, 'result.n', null) != null) { mongooseResult.deletedCount = res.result.n; } if (res.deletedCount != null) { mongooseResult.deletedCount = res.deletedCount; } return callback(null, mongooseResult); }; }; },{"./helpers/clone":293,"./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection":295,"./helpers/discriminator/getDiscriminatorByValue":297,"./helpers/get":303,"./helpers/projection/isDefiningProjection":313}],348:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ const EventEmitter = require('events').EventEmitter; const Kareem = require('kareem'); const MongooseError = require('./error/mongooseError'); const SchemaType = require('./schematype'); const SchemaTypeOptions = require('./options/SchemaTypeOptions'); const VirtualOptions = require('./options/VirtualOptions'); const VirtualType = require('./virtualtype'); const addAutoId = require('./helpers/schema/addAutoId'); const arrayParentSymbol = require('./helpers/symbols').arrayParentSymbol; const get = require('./helpers/get'); const getIndexes = require('./helpers/schema/getIndexes'); const merge = require('./helpers/schema/merge'); const mpath = require('mpath'); const readPref = require('./driver').get().ReadPreference; const setupTimestamps = require('./helpers/timestamps/setupTimestamps'); const util = require('util'); const utils = require('./utils'); const validateRef = require('./helpers/populate/validateRef'); let MongooseTypes; const queryHooks = require('./helpers/query/applyQueryMiddleware'). middlewareFunctions; const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions; const hookNames = queryHooks.concat(documentHooks). reduce((s, hook) => s.add(hook), new Set()); let id = 0; /** * Schema constructor. * * ####Example: * * const child = new Schema({ name: String }); * const schema = new Schema({ name: String, age: Number, children: [child] }); * const Tree = mongoose.model('Tree', schema); * * // setting schema options * new Schema({ name: String }, { _id: false, autoIndex: false }) * * ####Options: * * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option) * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out. * - [capped](/docs/guide.html#capped): bool - defaults to false * - [collection](/docs/guide.html#collection): string - no default * - [id](/docs/guide.html#id): bool - defaults to true * - [_id](/docs/guide.html#_id): bool - defaults to true * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true * - [read](/docs/guide.html#read): string * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/) * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null` * - [strict](/docs/guide.html#strict): bool - defaults to true * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false * - [toJSON](/docs/guide.html#toJSON) - object - no default * - [toObject](/docs/guide.html#toObject) - object - no default * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' * - [typePojoToMixed](/docs/guide.html#typePojoToMixed) - boolean - defaults to true. Determines whether a type set to a POJO becomes a Mixed path or a Subdocument * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v" * - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html). * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true` * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you. * - [storeSubdocValidationError](/docs/guide.html#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path. * * ####Options for Nested Schemas: * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths. * * ####Note: * * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ * * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas * @param {Object} [options] * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter * @event `init`: Emitted after the schema is compiled into a `Model`. * @api public */ function Schema(obj, options) { if (!(this instanceof Schema)) { return new Schema(obj, options); } this.obj = obj; this.paths = {}; this.aliases = {}; this.subpaths = {}; this.virtuals = {}; this.singleNestedPaths = {}; this.nested = {}; this.inherits = {}; this.callQueue = []; this._indexes = []; this.methods = {}; this.methodOptions = {}; this.statics = {}; this.tree = {}; this.query = {}; this.childSchemas = []; this.plugins = []; // For internal debugging. Do not use this to try to save a schema in MDB. this.$id = ++id; this.s = { hooks: new Kareem() }; this.options = this.defaultOptions(options); // build paths if (Array.isArray(obj)) { for (const definition of obj) { this.add(definition); } } else if (obj) { this.add(obj); } // check if _id's value is a subdocument (gh-2276) const _idSubDoc = obj && obj._id && utils.isObject(obj._id); // ensure the documents get an auto _id unless disabled const auto_id = !this.paths['_id'] && (!this.options.noId && this.options._id) && !_idSubDoc; if (auto_id) { addAutoId(this); } this.setupTimestamp(this.options.timestamps); } /*! * Create virtual properties with alias field */ function aliasFields(schema, paths) { paths = paths || Object.keys(schema.paths); for (const path of paths) { const options = get(schema.paths[path], 'options'); if (options == null) { continue; } const prop = schema.paths[path].path; const alias = options.alias; if (!alias) { continue; } if (typeof alias !== 'string') { throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias); } schema.aliases[alias] = prop; schema. virtual(alias). get((function(p) { return function() { if (typeof this.get === 'function') { return this.get(p); } return this[p]; }; })(prop)). set((function(p) { return function(v) { return this.$set(p, v); }; })(prop)); } } /*! * Inherit from EventEmitter. */ Schema.prototype = Object.create(EventEmitter.prototype); Schema.prototype.constructor = Schema; Schema.prototype.instanceOfSchema = true; /*! * ignore */ Object.defineProperty(Schema.prototype, '$schemaType', { configurable: false, enumerable: false, writable: true }); /** * Array of child schemas (from document arrays and single nested subdocs) * and their corresponding compiled models. Each element of the array is * an object with 2 properties: `schema` and `model`. * * This property is typically only useful for plugin authors and advanced users. * You do not need to interact with this property at all to use mongoose. * * @api public * @property childSchemas * @memberOf Schema * @instance */ Object.defineProperty(Schema.prototype, 'childSchemas', { configurable: false, enumerable: true, writable: true }); /** * The original object passed to the schema constructor * * ####Example: * * const schema = new Schema({ a: String }).add({ b: String }); * schema.obj; // { a: String } * * @api public * @property obj * @memberOf Schema * @instance */ Schema.prototype.obj; /** * The paths defined on this schema. The keys are the top-level paths * in this schema, and the values are instances of the SchemaType class. * * ####Example: * const schema = new Schema({ name: String }, { _id: false }); * schema.paths; // { name: SchemaString { ... } } * * schema.add({ age: Number }); * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } } * * @api public * @property paths * @memberOf Schema * @instance */ Schema.prototype.paths; /** * Schema as a tree * * ####Example: * { * '_id' : ObjectId * , 'nested' : { * 'key' : String * } * } * * @api private * @property tree * @memberOf Schema * @instance */ Schema.prototype.tree; /** * Returns a deep copy of the schema * * ####Example: * * const schema = new Schema({ name: String }); * const clone = schema.clone(); * clone === schema; // false * clone.path('name'); // SchemaString { ... } * * @return {Schema} the cloned schema * @api public * @memberOf Schema * @instance */ Schema.prototype.clone = function() { const Constructor = this.base == null ? Schema : this.base.Schema; const s = new Constructor({}, this._userProvidedOptions); s.base = this.base; s.obj = this.obj; s.options = utils.clone(this.options); s.callQueue = this.callQueue.map(function(f) { return f; }); s.methods = utils.clone(this.methods); s.methodOptions = utils.clone(this.methodOptions); s.statics = utils.clone(this.statics); s.query = utils.clone(this.query); s.plugins = Array.prototype.slice.call(this.plugins); s._indexes = utils.clone(this._indexes); s.s.hooks = this.s.hooks.clone(); s.tree = utils.clone(this.tree); s.paths = utils.clone(this.paths); s.nested = utils.clone(this.nested); s.subpaths = utils.clone(this.subpaths); s.singleNestedPaths = utils.clone(this.singleNestedPaths); s.childSchemas = gatherChildSchemas(s); s.virtuals = utils.clone(this.virtuals); s.$globalPluginsApplied = this.$globalPluginsApplied; s.$isRootDiscriminator = this.$isRootDiscriminator; s.$implicitlyCreated = this.$implicitlyCreated; if (this.discriminatorMapping != null) { s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); } if (this.discriminators != null) { s.discriminators = Object.assign({}, this.discriminators); } s.aliases = Object.assign({}, this.aliases); // Bubble up `init` for backwards compat s.on('init', v => this.emit('init', v)); return s; }; /** * Returns a new schema that has the picked `paths` from this schema. * * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas. * * ####Example: * * const schema = Schema({ name: String, age: Number }); * // Creates a new schema with the same `name` path as `schema`, * // but no `age` path. * const newSchema = schema.pick(['name']); * * newSchema.path('name'); // SchemaString { ... } * newSchema.path('age'); // undefined * * @param {Array} paths list of paths to pick * @param {Object} [options] options to pass to the schema constructor. Defaults to `this.options` if not set. * @return {Schema} * @api public */ Schema.prototype.pick = function(paths, options) { const newSchema = new Schema({}, options || this.options); if (!Array.isArray(paths)) { throw new MongooseError('Schema#pick() only accepts an array argument, ' + 'got "' + typeof paths + '"'); } for (const path of paths) { if (this.nested[path]) { newSchema.add({ [path]: get(this.tree, path) }); } else { const schematype = this.path(path); if (schematype == null) { throw new MongooseError('Path `' + path + '` is not in the schema'); } newSchema.add({ [path]: schematype }); } } return newSchema; }; /** * Returns default options for this schema, merged with `options`. * * @param {Object} options * @return {Object} * @api private */ Schema.prototype.defaultOptions = function(options) { if (options && options.safe === false) { options.safe = { w: 0 }; } if (options && options.safe && options.safe.w === 0) { // if you turn off safe writes, then versioning goes off as well options.versionKey = false; } this._userProvidedOptions = options == null ? {} : utils.clone(options); const baseOptions = get(this, 'base.options', {}); options = utils.options({ strict: 'strict' in baseOptions ? baseOptions.strict : true, strictQuery: 'strictQuery' in baseOptions ? baseOptions.strictQuery : false, bufferCommands: true, capped: false, // { size, max, autoIndexId } versionKey: '__v', optimisticConcurrency: false, discriminatorKey: '__t', minimize: true, autoIndex: null, shardKey: null, read: null, validateBeforeSave: true, // the following are only applied at construction time noId: false, // deprecated, use { _id: false } _id: true, noVirtualId: false, // deprecated, use { id: false } id: true, typeKey: 'type', typePojoToMixed: 'typePojoToMixed' in baseOptions ? baseOptions.typePojoToMixed : true }, utils.clone(options)); if (options.read) { options.read = readPref(options.read); } if (options.optimisticConcurrency && !options.versionKey) { throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`'); } return options; }; /** * Adds key path / schema type pairs to this schema. * * ####Example: * * const ToySchema = new Schema(); * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); * * const TurboManSchema = new Schema(); * // You can also `add()` another schema and copy over all paths, virtuals, * // getters, setters, indexes, methods, and statics. * TurboManSchema.add(ToySchema).add({ year: Number }); * * @param {Object|Schema} obj plain object with paths to add, or another schema * @param {String} [prefix] path to prefix the newly added paths with * @return {Schema} the Schema instance * @api public */ Schema.prototype.add = function add(obj, prefix) { if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) { merge(this, obj); return this; } // Special case: setting top-level `_id` to false should convert to disabling // the `_id` option. This behavior never worked before 5.4.11 but numerous // codebases use it (see gh-7516, gh-7512). if (obj._id === false && prefix == null) { this.options._id = false; } prefix = prefix || ''; const keys = Object.keys(obj); for (const key of keys) { const fullPath = prefix + key; if (obj[key] == null) { throw new TypeError('Invalid value for schema path `' + fullPath + '`, got value "' + obj[key] + '"'); } // Retain `_id: false` but don't set it as a path, re: gh-8274. if (key === '_id' && obj[key] === false) { continue; } if (obj[key] instanceof VirtualType || get(obj[key], 'constructor.name', null) === 'VirtualType') { this.virtual(obj[key]); continue; } if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { throw new TypeError('Invalid value for schema Array path `' + fullPath + '`, got value "' + obj[key][0] + '"'); } if (!(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions)) { // Special-case: Non-options definitely a path so leaf at this node // Examples: Schema instances, SchemaType instances if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(prefix + key, obj[key]); } else if (Object.keys(obj[key]).length < 1) { // Special-case: {} always interpreted as Mixed path so leaf at this node if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(fullPath, obj[key]); // mixed type } else if (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type)) { // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse // nested object { last: { name: String }} this.nested[fullPath] = true; this.add(obj[key], fullPath + '.'); } else { // There IS a bona-fide type key that may also be a POJO if (!this.options.typePojoToMixed && utils.isPOJO(obj[key][this.options.typeKey])) { // If a POJO is the value of a type key, make it a subdocument if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } // Propage `typePojoToMixed` to implicitly created schemas const opts = { typePojoToMixed: false }; const _schema = new Schema(obj[key][this.options.typeKey], opts); const schemaWrappedPath = Object.assign({}, obj[key], { [this.options.typeKey]: _schema }); this.path(prefix + key, schemaWrappedPath); } else { // Either the type is non-POJO or we interpret it as Mixed anyway if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(prefix + key, obj[key]); } } } const addedKeys = Object.keys(obj). map(key => prefix ? prefix + key : key); aliasFields(this, addedKeys); return this; }; /** * Reserved document keys. * * Keys in this object are names that are rejected in schema declarations * because they conflict with Mongoose functionality. If you create a schema * using `new Schema()` with one of these property names, Mongoose will throw * an error. * * - _posts * - _pres * - collection * - emit * - errors * - get * - init * - isModified * - isNew * - listeners * - modelName * - on * - once * - populated * - prototype * - remove * - removeListener * - save * - schema * - toObject * - validate * * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. * * const schema = new Schema(..); * schema.methods.init = function () {} // potentially breaking */ Schema.reserved = Object.create(null); Schema.prototype.reserved = Schema.reserved; const reserved = Schema.reserved; // Core object reserved['prototype'] = // EventEmitter reserved.emit = reserved.listeners = reserved.on = reserved.removeListener = // document properties and functions reserved.collection = reserved.errors = reserved.get = reserved.init = reserved.isModified = reserved.isNew = reserved.populated = reserved.remove = reserved.save = reserved.schema = reserved.toObject = reserved.validate = 1; /** * Gets/sets schema paths. * * Sets a path (if arity 2) * Gets a path (if arity 1) * * ####Example * * schema.path('name') // returns a SchemaType * schema.path('name', Number) // changes the schemaType of `name` to Number * * @param {String} path * @param {Object} constructor * @api public */ Schema.prototype.path = function(path, obj) { // Convert to '.$' to check subpaths re: gh-6405 const cleanPath = _pathToPositionalSyntax(path); if (obj === undefined) { let schematype = _getPath(this, path, cleanPath); if (schematype != null) { return schematype; } // Look for maps const mapPath = getMapPath(this, path); if (mapPath != null) { return mapPath; } // Look if a parent of this path is mixed schematype = this.hasMixedParent(cleanPath); if (schematype != null) { return schematype; } // subpaths? return /\.\d+\.?.*$/.test(path) ? getPositionalPath(this, path) : undefined; } // some path names conflict with document methods const firstPieceOfPath = path.split('.')[0]; if (reserved[firstPieceOfPath]) { throw new Error('`' + firstPieceOfPath + '` may not be used as a schema pathname'); } if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) { validateRef(obj.ref, path); } // update the tree const subpaths = path.split(/\./); const last = subpaths.pop(); let branch = this.tree; let fullPath = ''; for (const sub of subpaths) { fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub; if (!branch[sub]) { this.nested[fullPath] = true; branch[sub] = {}; } if (typeof branch[sub] !== 'object') { const msg = 'Cannot set nested path `' + path + '`. ' + 'Parent path `' + fullPath + '` already set to type ' + branch[sub].name + '.'; throw new Error(msg); } branch = branch[sub]; } branch[last] = utils.clone(obj); this.paths[path] = this.interpretAsType(path, obj, this.options); const schemaType = this.paths[path]; if (schemaType.$isSchemaMap) { // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key" // The '$' is to imply this path should never be stored in MongoDB so we // can easily build a regexp out of this path, and '*' to imply "any key." const mapPath = path + '.$*'; let _mapType = { type: {} }; if (utils.hasUserDefinedProperty(obj, 'of')) { const isInlineSchema = utils.isPOJO(obj.of) && Object.keys(obj.of).length > 0 && !utils.hasUserDefinedProperty(obj.of, this.options.typeKey); _mapType = isInlineSchema ? new Schema(obj.of) : obj.of; } this.paths[mapPath] = this.interpretAsType(mapPath, _mapType, this.options); schemaType.$__schemaType = this.paths[mapPath]; } if (schemaType.$isSingleNested) { for (const key in schemaType.schema.paths) { this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key]; } for (const key in schemaType.schema.singleNestedPaths) { this.singleNestedPaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key]; } for (const key in schemaType.schema.subpaths) { this.singleNestedPaths[path + '.' + key] = schemaType.schema.subpaths[key]; } for (const key in schemaType.schema.nested) { this.singleNestedPaths[path + '.' + key] = 'nested'; } Object.defineProperty(schemaType.schema, 'base', { configurable: true, enumerable: false, writable: false, value: this.base }); schemaType.caster.base = this.base; this.childSchemas.push({ schema: schemaType.schema, model: schemaType.caster }); } else if (schemaType.$isMongooseDocumentArray) { Object.defineProperty(schemaType.schema, 'base', { configurable: true, enumerable: false, writable: false, value: this.base }); schemaType.casterConstructor.base = this.base; this.childSchemas.push({ schema: schemaType.schema, model: schemaType.casterConstructor }); } if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) { let arrayPath = path; let _schemaType = schemaType; const toAdd = []; while (_schemaType.$isMongooseArray) { arrayPath = arrayPath + '.$'; // Skip arrays of document arrays if (_schemaType.$isMongooseDocumentArray) { _schemaType.$embeddedSchemaType._arrayPath = arrayPath; _schemaType.$embeddedSchemaType._arrayParentPath = path; _schemaType = _schemaType.$embeddedSchemaType.clone(); } else { _schemaType.caster._arrayPath = arrayPath; _schemaType.caster._arrayParentPath = path; _schemaType = _schemaType.caster.clone(); } _schemaType.path = arrayPath; toAdd.push(_schemaType); } for (const _schemaType of toAdd) { this.subpaths[_schemaType.path] = _schemaType; } } if (schemaType.$isMongooseDocumentArray) { for (const key of Object.keys(schemaType.schema.paths)) { this.subpaths[path + '.' + key] = schemaType.schema.paths[key]; schemaType.schema.paths[key].$isUnderneathDocArray = true; } for (const key of Object.keys(schemaType.schema.subpaths)) { this.subpaths[path + '.' + key] = schemaType.schema.subpaths[key]; schemaType.schema.subpaths[key].$isUnderneathDocArray = true; } for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { if (typeof schemaType.schema.singleNestedPaths[cleanPath] !== 'object') { continue; } this.subpaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key]; schemaType.schema.singleNestedPaths[key].$isUnderneathDocArray = true; } } return this; }; /*! * ignore */ function gatherChildSchemas(schema) { const childSchemas = []; for (const path of Object.keys(schema.paths)) { const schematype = schema.paths[path]; if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { childSchemas.push({ schema: schematype.schema, model: schematype.caster }); } } return childSchemas; } /*! * ignore */ function _getPath(schema, path, cleanPath) { if (schema.paths.hasOwnProperty(path)) { return schema.paths[path]; } if (schema.subpaths.hasOwnProperty(cleanPath)) { return schema.subpaths[cleanPath]; } if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') { return schema.singleNestedPaths[cleanPath]; } return null; } /*! * ignore */ function _pathToPositionalSyntax(path) { if (!/\.\d+/.test(path)) { return path; } return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$'); } /*! * ignore */ function getMapPath(schema, path) { for (const _path of Object.keys(schema.paths)) { if (!_path.includes('.$*')) { continue; } const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$'); if (re.test(path)) { return schema.paths[_path]; } } return null; } /** * The Mongoose instance this schema is associated with * * @property base * @api private */ Object.defineProperty(Schema.prototype, 'base', { configurable: true, enumerable: false, writable: true, value: null }); /** * Converts type arguments into Mongoose Types. * * @param {String} path * @param {Object} obj constructor * @api private */ Schema.prototype.interpretAsType = function(path, obj, options) { if (obj instanceof SchemaType) { if (obj.path === path) { return obj; } const clone = obj.clone(); clone.path = path; return clone; } // If this schema has an associated Mongoose object, use the Mongoose object's // copy of SchemaTypes re: gh-7158 gh-6933 const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types; if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { const constructorName = utils.getFunctionName(obj.constructor); if (constructorName !== 'Object') { const oldObj = obj; obj = {}; obj[options.typeKey] = oldObj; } } // Get the type making sure to allow keys named "type" // and default to mixed if not specified. // { type: { type: String, default: 'freshcut' } } let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) ? obj[options.typeKey] : {}; let name; if (utils.isPOJO(type) || type === 'mixed') { return new MongooseTypes.Mixed(path, obj); } if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) { // if it was specified through { type } look for `cast` let cast = (type === Array || type === 'array') ? obj.cast || obj.of : type[0]; if (cast && cast.instanceOfSchema) { return new MongooseTypes.DocumentArray(path, cast, obj); } if (cast && cast[options.typeKey] && cast[options.typeKey].instanceOfSchema) { return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast); } if (Array.isArray(cast)) { return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj); } if (typeof cast === 'string') { cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) && utils.isPOJO(cast)) { if (Object.keys(cast).length) { // The `minimize` and `typeKey` options propagate to child schemas // declared inline, like `{ arr: [{ val: { $type: String } }] }`. // See gh-3560 const childSchemaOptions = { minimize: options.minimize }; if (options.typeKey) { childSchemaOptions.typeKey = options.typeKey; } // propagate 'strict' option to child schema if (options.hasOwnProperty('strict')) { childSchemaOptions.strict = options.strict; } if (options.hasOwnProperty('typePojoToMixed')) { childSchemaOptions.typePojoToMixed = options.typePojoToMixed; } if (this._userProvidedOptions.hasOwnProperty('_id')) { childSchemaOptions._id = this._userProvidedOptions._id; } else if (Schema.Types.DocumentArray.defaultOptions && Schema.Types.DocumentArray.defaultOptions._id != null) { childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id; } const childSchema = new Schema(cast, childSchemaOptions); childSchema.$implicitlyCreated = true; return new MongooseTypes.DocumentArray(path, childSchema, obj); } else { // Special case: empty object becomes mixed return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj); } } if (cast) { type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type) ? cast[options.typeKey] : cast; name = typeof type === 'string' ? type : type.schemaName || utils.getFunctionName(type); if (!MongooseTypes.hasOwnProperty(name)) { throw new TypeError('Invalid schema configuration: ' + `\`${name}\` is not a valid type within the array \`${path}\`.` + 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.'); } } return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); } if (type && type.instanceOfSchema) { return new MongooseTypes.Embedded(type, path, obj); } if (Buffer.isBuffer(type)) { name = 'Buffer'; } else if (typeof type === 'function' || typeof type === 'object') { name = type.schemaName || utils.getFunctionName(type); } else { name = type == null ? '' + type : type.toString(); } if (name) { name = name.charAt(0).toUpperCase() + name.substring(1); } // Special case re: gh-7049 because the bson `ObjectID` class' capitalization // doesn't line up with Mongoose's. if (name === 'ObjectID') { name = 'ObjectId'; } if (MongooseTypes[name] == null) { throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` + `a valid type at path \`${path}\`. See ` + 'http://bit.ly/mongoose-schematypes for a list of valid schema types.'); } return new MongooseTypes[name](path, obj); }; /** * Iterates the schemas paths similar to Array#forEach. * * The callback is passed the pathname and the schemaType instance. * * ####Example: * * const userSchema = new Schema({ name: String, registeredAt: Date }); * userSchema.eachPath((pathname, schematype) => { * // Prints twice: * // name SchemaString { ... } * // registeredAt SchemaDate { ... } * console.log(pathname, schematype); * }); * * @param {Function} fn callback function * @return {Schema} this * @api public */ Schema.prototype.eachPath = function(fn) { const keys = Object.keys(this.paths); const len = keys.length; for (let i = 0; i < len; ++i) { fn(keys[i], this.paths[keys[i]]); } return this; }; /** * Returns an Array of path strings that are required by this schema. * * ####Example: * const s = new Schema({ * name: { type: String, required: true }, * age: { type: String, required: true }, * notes: String * }); * s.requiredPaths(); // [ 'age', 'name' ] * * @api public * @param {Boolean} invalidate refresh the cache * @return {Array} */ Schema.prototype.requiredPaths = function requiredPaths(invalidate) { if (this._requiredpaths && !invalidate) { return this._requiredpaths; } const paths = Object.keys(this.paths); let i = paths.length; const ret = []; while (i--) { const path = paths[i]; if (this.paths[path].isRequired) { ret.push(path); } } this._requiredpaths = ret; return this._requiredpaths; }; /** * Returns indexes from fields and schema-level indexes (cached). * * @api private * @return {Array} */ Schema.prototype.indexedPaths = function indexedPaths() { if (this._indexedpaths) { return this._indexedpaths; } this._indexedpaths = this.indexes(); return this._indexedpaths; }; /** * Returns the pathType of `path` for this schema. * * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. * * ####Example: * const s = new Schema({ name: String, nested: { foo: String } }); * s.virtual('foo').get(() => 42); * s.pathType('name'); // "real" * s.pathType('nested'); // "nested" * s.pathType('foo'); // "virtual" * s.pathType('fail'); // "adhocOrUndefined" * * @param {String} path * @return {String} * @api public */ Schema.prototype.pathType = function(path) { // Convert to '.$' to check subpaths re: gh-6405 const cleanPath = _pathToPositionalSyntax(path); if (this.paths.hasOwnProperty(path)) { return 'real'; } if (this.virtuals.hasOwnProperty(path)) { return 'virtual'; } if (this.nested.hasOwnProperty(path)) { return 'nested'; } if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) { return 'real'; } const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path); if (singleNestedPath) { return singleNestedPath === 'nested' ? 'nested' : 'real'; } // Look for maps const mapPath = getMapPath(this, path); if (mapPath != null) { return 'real'; } if (/\.\d+\.|\.\d+$/.test(path)) { return getPositionalPathType(this, path); } return 'adhocOrUndefined'; }; /** * Returns true iff this path is a child of a mixed schema. * * @param {String} path * @return {Boolean} * @api private */ Schema.prototype.hasMixedParent = function(path) { const subpaths = path.split(/\./g); path = ''; for (let i = 0; i < subpaths.length; ++i) { path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; if (path in this.paths && this.paths[path] instanceof MongooseTypes.Mixed) { return this.paths[path]; } } return null; }; /** * Setup updatedAt and createdAt timestamps to documents if enabled * * @param {Boolean|Object} timestamps timestamps options * @api private */ Schema.prototype.setupTimestamp = function(timestamps) { return setupTimestamps(this, timestamps); }; /*! * ignore. Deprecated re: #6405 */ function getPositionalPathType(self, path) { const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); if (subpaths.length < 2) { return self.paths.hasOwnProperty(subpaths[0]) ? self.paths[subpaths[0]] : 'adhocOrUndefined'; } let val = self.path(subpaths[0]); let isNested = false; if (!val) { return 'adhocOrUndefined'; } const last = subpaths.length - 1; for (let i = 1; i < subpaths.length; ++i) { isNested = false; const subpath = subpaths[i]; if (i === last && val && !/\D/.test(subpath)) { if (val.$isMongooseDocumentArray) { val = val.$embeddedSchemaType; } else if (val instanceof MongooseTypes.Array) { // StringSchema, NumberSchema, etc val = val.caster; } else { val = undefined; } break; } // ignore if its just a position segment: path.0.subpath if (!/\D/.test(subpath)) { // Nested array if (val instanceof MongooseTypes.Array && i !== last) { val = val.caster; } continue; } if (!(val && val.schema)) { val = undefined; break; } const type = val.schema.pathType(subpath); isNested = (type === 'nested'); val = val.schema.path(subpath); } self.subpaths[path] = val; if (val) { return 'real'; } if (isNested) { return 'nested'; } return 'adhocOrUndefined'; } /*! * ignore */ function getPositionalPath(self, path) { getPositionalPathType(self, path); return self.subpaths[path]; } /** * Adds a method call to the queue. * * ####Example: * * schema.methods.print = function() { console.log(this); }; * schema.queue('print', []); // Print the doc every one is instantiated * * const Model = mongoose.model('Test', schema); * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }' * * @param {String} name name of the document method to call later * @param {Array} args arguments to pass to the method * @api public */ Schema.prototype.queue = function(name, args) { this.callQueue.push([name, args]); return this; }; /** * Defines a pre hook for the model. * * ####Example * * const toySchema = new Schema({ name: String, created: Date }); * * toySchema.pre('save', function(next) { * if (!this.created) this.created = new Date; * next(); * }); * * toySchema.pre('validate', function(next) { * if (this.name !== 'Woody') this.name = 'Woody'; * next(); * }); * * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`. * toySchema.pre(/^find/, function(next) { * console.log(this.getFilter()); * }); * * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`. * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) { * console.log(this.getFilter()); * }); * * toySchema.pre('deleteOne', function() { * // Runs when you call `Toy.deleteOne()` * }); * * toySchema.pre('deleteOne', { document: true }, function() { * // Runs when you call `doc.deleteOne()` * }); * * @param {String|RegExp} The method name or regular expression to match method name * @param {Object} [options] * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`. * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. * @param {Function} callback * @api public */ Schema.prototype.pre = function(name) { if (name instanceof RegExp) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const fn of hookNames) { if (name.test(fn)) { this.pre.apply(this, [fn].concat(remainingArgs)); } } return this; } if (Array.isArray(name)) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const el of name) { this.pre.apply(this, [el].concat(remainingArgs)); } return this; } this.s.hooks.pre.apply(this.s.hooks, arguments); return this; }; /** * Defines a post hook for the document * * const schema = new Schema(..); * schema.post('save', function (doc) { * console.log('this fired after a document was saved'); * }); * * schema.post('find', function(docs) { * console.log('this fired after you ran a find query'); * }); * * schema.post(/Many$/, function(res) { * console.log('this fired after you ran `updateMany()` or `deleteMany()`); * }); * * const Model = mongoose.model('Model', schema); * * const m = new Model(..); * m.save(function(err) { * console.log('this fires after the `post` hook'); * }); * * m.find(function(err, docs) { * console.log('this fires after the post find hook'); * }); * * @param {String|RegExp} The method name or regular expression to match method name * @param {Object} [options] * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. * @param {Function} fn callback * @see middleware http://mongoosejs.com/docs/middleware.html * @see kareem http://npmjs.org/package/kareem * @api public */ Schema.prototype.post = function(name) { if (name instanceof RegExp) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const fn of hookNames) { if (name.test(fn)) { this.post.apply(this, [fn].concat(remainingArgs)); } } return this; } if (Array.isArray(name)) { const remainingArgs = Array.prototype.slice.call(arguments, 1); for (const el of name) { this.post.apply(this, [el].concat(remainingArgs)); } return this; } this.s.hooks.post.apply(this.s.hooks, arguments); return this; }; /** * Registers a plugin for this schema. * * ####Example: * * const s = new Schema({ name: String }); * s.plugin(schema => console.log(schema.path('name').path)); * mongoose.model('Test', s); // Prints 'name' * * @param {Function} plugin callback * @param {Object} [opts] * @see plugins * @api public */ Schema.prototype.plugin = function(fn, opts) { if (typeof fn !== 'function') { throw new Error('First param to `schema.plugin()` must be a function, ' + 'got "' + (typeof fn) + '"'); } if (opts && opts.deduplicate) { for (const plugin of this.plugins) { if (plugin.fn === fn) { return this; } } } this.plugins.push({ fn: fn, opts: opts }); fn(this, opts); return this; }; /** * Adds an instance method to documents constructed from Models compiled from this schema. * * ####Example * * const schema = kittySchema = new Schema(..); * * schema.method('meow', function () { * console.log('meeeeeoooooooooooow'); * }) * * const Kitty = mongoose.model('Kitty', schema); * * const fizz = new Kitty; * fizz.meow(); // meeeeeooooooooooooow * * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. * * schema.method({ * purr: function () {} * , scratch: function () {} * }); * * // later * fizz.purr(); * fizz.scratch(); * * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](./guide.html#methods) * * @param {String|Object} method name * @param {Function} [fn] * @api public */ Schema.prototype.method = function(name, fn, options) { if (typeof name !== 'string') { for (const i in name) { this.methods[i] = name[i]; this.methodOptions[i] = utils.clone(options); } } else { this.methods[name] = fn; this.methodOptions[name] = utils.clone(options); } return this; }; /** * Adds static "class" methods to Models compiled from this schema. * * ####Example * * const schema = new Schema(..); * // Equivalent to `schema.statics.findByName = function(name) {}`; * schema.static('findByName', function(name) { * return this.find({ name: name }); * }); * * const Drink = mongoose.model('Drink', schema); * await Drink.findByName('LaCroix'); * * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. * * @param {String|Object} name * @param {Function} [fn] * @api public * @see Statics /docs/guide.html#statics */ Schema.prototype.static = function(name, fn) { if (typeof name !== 'string') { for (const i in name) { this.statics[i] = name[i]; } } else { this.statics[name] = fn; } return this; }; /** * Defines an index (most likely compound) for this schema. * * ####Example * * schema.index({ first: 1, last: -1 }) * * @param {Object} fields * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. * @api public */ Schema.prototype.index = function(fields, options) { fields || (fields = {}); options || (options = {}); if (options.expires) { utils.expires(options); } this._indexes.push([fields, options]); return this; }; /** * Sets a schema option. * * ####Example * * schema.set('strict'); // 'true' by default * schema.set('strict', false); // Sets 'strict' to false * schema.set('strict'); // 'false' * * @param {String} key option name * @param {Object} [value] if not passed, the current option value is returned * @see Schema ./ * @api public */ Schema.prototype.set = function(key, value, _tags) { if (arguments.length === 1) { return this.options[key]; } switch (key) { case 'read': this.options[key] = readPref(value, _tags); this._userProvidedOptions[key] = this.options[key]; break; case 'safe': setSafe(this.options, value); this._userProvidedOptions[key] = this.options[key]; break; case 'timestamps': this.setupTimestamp(value); this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; break; case '_id': this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; if (value && !this.paths['_id']) { addAutoId(this); } else if (!value && this.paths['_id'] != null && this.paths['_id'].auto) { this.remove('_id'); } break; default: this.options[key] = value; this._userProvidedOptions[key] = this.options[key]; break; } return this; }; /*! * ignore */ const safeDeprecationWarning = 'Mongoose: The `safe` option for schemas is ' + 'deprecated. Use the `writeConcern` option instead: ' + 'http://bit.ly/mongoose-write-concern'; const setSafe = util.deprecate(function setSafe(options, value) { options.safe = value === false ? { w: 0 } : value; }, safeDeprecationWarning); /** * Gets a schema option. * * ####Example: * * schema.get('strict'); // true * schema.set('strict', false); * schema.get('strict'); // false * * @param {String} key option name * @api public * @return {Any} the option's value */ Schema.prototype.get = function(key) { return this.options[key]; }; /** * The allowed index types * * @receiver Schema * @static indexTypes * @api public */ const indexTypes = '2d 2dsphere hashed text'.split(' '); Object.defineProperty(Schema, 'indexTypes', { get: function() { return indexTypes; }, set: function() { throw new Error('Cannot overwrite Schema.indexTypes'); } }); /** * Returns a list of indexes that this schema declares, via `schema.index()` * or by `index: true` in a path's options. * * ####Example: * * const userSchema = new Schema({ * email: { type: String, required: true, unique: true }, * registeredAt: { type: Date, index: true } * }); * * // [ [ { email: 1 }, { unique: true, background: true } ], * // [ { registeredAt: 1 }, { background: true } ] ] * userSchema.indexes(); * * @api public * @return {Array} list of indexes defined in the schema */ Schema.prototype.indexes = function() { return getIndexes(this); }; /** * Creates a virtual type with the given name. * * @param {String} name * @param {Object} [options] * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](populate.html#populate-virtuals). * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array. * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`. * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc. * @return {VirtualType} */ Schema.prototype.virtual = function(name, options) { if (name instanceof VirtualType || (name != null && name.constructor.name === 'VirtualType')) { return this.virtual(name.path, name.options); } options = new VirtualOptions(options); if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) { if (options.localField == null) { throw new Error('Reference virtuals require `localField` option'); } if (options.foreignField == null) { throw new Error('Reference virtuals require `foreignField` option'); } this.pre('init', function(obj) { if (mpath.has(name, obj)) { const _v = mpath.get(name, obj); if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } if (options.justOne || options.count) { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; } else { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v : _v == null ? [] : [_v]; } mpath.unset(name, obj); } }); const virtual = this.virtual(name); virtual.options = options; virtual. set(function(_v) { if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } if (options.justOne || options.count) { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; if (typeof this.$$populatedVirtuals[name] !== 'object') { this.$$populatedVirtuals[name] = options.count ? _v : null; } } else { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v : _v == null ? [] : [_v]; this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) { return doc && typeof doc === 'object'; }); } }); if (typeof options.get === 'function') { virtual.get(options.get); } return virtual; } const virtuals = this.virtuals; const parts = name.split('.'); if (this.pathType(name) === 'real') { throw new Error('Virtual path "' + name + '"' + ' conflicts with a real path in the schema'); } virtuals[name] = parts.reduce(function(mem, part, i) { mem[part] || (mem[part] = (i === parts.length - 1) ? new VirtualType(options, name) : {}); return mem[part]; }, this.tree); // Workaround for gh-8198: if virtual is under document array, make a fake // virtual. See gh-8210 let cur = parts[0]; for (let i = 0; i < parts.length - 1; ++i) { if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) { const remnant = parts.slice(i + 1).join('.'); const v = this.paths[cur].schema.virtual(remnant); v.get((v, virtual, doc) => { const parent = doc.__parentArray[arrayParentSymbol]; const path = cur + '.' + doc.__index + '.' + remnant; return parent.get(path); }); break; } cur += '.' + parts[i + 1]; } return virtuals[name]; }; /** * Returns the virtual type with the given `name`. * * @param {String} name * @return {VirtualType} */ Schema.prototype.virtualpath = function(name) { return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; }; /** * Removes the given `path` (or [`paths`]). * * ####Example: * * const schema = new Schema({ name: String, age: Number }); * schema.remove('name'); * schema.path('name'); // Undefined * schema.path('age'); // SchemaNumber { ... } * * @param {String|Array} path * @return {Schema} the Schema instance * @api public */ Schema.prototype.remove = function(path) { if (typeof path === 'string') { path = [path]; } if (Array.isArray(path)) { path.forEach(function(name) { if (this.path(name) == null && !this.nested[name]) { return; } if (this.nested[name]) { const allKeys = Object.keys(this.paths). concat(Object.keys(this.nested)); for (const path of allKeys) { if (path.startsWith(name + '.')) { delete this.paths[path]; delete this.nested[path]; _deletePath(this, path); } } delete this.nested[name]; _deletePath(this, name); return; } delete this.paths[name]; _deletePath(this, name); }, this); } return this; }; /*! * ignore */ function _deletePath(schema, name) { const pieces = name.split('.'); const last = pieces.pop(); let branch = schema.tree; for (const piece of pieces) { branch = branch[piece]; } delete branch[last]; } /** * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), * [statics](http://mongoosejs.com/docs/guide.html#statics), and * [methods](http://mongoosejs.com/docs/guide.html#methods). * * ####Example: * * ```javascript * const md5 = require('md5'); * const userSchema = new Schema({ email: String }); * class UserClass { * // `gravatarImage` becomes a virtual * get gravatarImage() { * const hash = md5(this.email.toLowerCase()); * return `https://www.gravatar.com/avatar/${hash}`; * } * * // `getProfileUrl()` becomes a document method * getProfileUrl() { * return `https://mysite.com/${this.email}`; * } * * // `findByEmail()` becomes a static * static findByEmail(email) { * return this.findOne({ email }); * } * } * * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method, * // and a `findByEmail()` static * userSchema.loadClass(UserClass); * ``` * * @param {Function} model * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics */ Schema.prototype.loadClass = function(model, virtualsOnly) { if (model === Object.prototype || model === Function.prototype || model.prototype.hasOwnProperty('$isMongooseModelPrototype')) { return this; } this.loadClass(Object.getPrototypeOf(model)); // Add static methods if (!virtualsOnly) { Object.getOwnPropertyNames(model).forEach(function(name) { if (name.match(/^(length|name|prototype)$/)) { return; } const method = Object.getOwnPropertyDescriptor(model, name); if (typeof method.value === 'function') { this.static(name, method.value); } }, this); } // Add methods and virtuals Object.getOwnPropertyNames(model.prototype).forEach(function(name) { if (name.match(/^(constructor)$/)) { return; } const method = Object.getOwnPropertyDescriptor(model.prototype, name); if (!virtualsOnly) { if (typeof method.value === 'function') { this.method(name, method.value); } } if (typeof method.get === 'function') { this.virtual(name).get(method.get); } if (typeof method.set === 'function') { this.virtual(name).set(method.set); } }, this); return this; }; /*! * ignore */ Schema.prototype._getSchema = function(path) { const _this = this; const pathschema = _this.path(path); const resultPath = []; if (pathschema) { pathschema.$fullPath = path; return pathschema; } function search(parts, schema) { let p = parts.length + 1; let foundschema; let trypath; while (p--) { trypath = parts.slice(0, p).join('.'); foundschema = schema.path(trypath); if (foundschema) { resultPath.push(trypath); if (foundschema.caster) { // array of Mixed? if (foundschema.caster instanceof MongooseTypes.Mixed) { foundschema.caster.$fullPath = resultPath.join('.'); return foundschema.caster; } // Now that we found the array, we need to check if there // are remaining document paths to look up for casting. // Also we need to handle array.$.path since schema.path // doesn't work for that. // If there is no foundschema.schema we are dealing with // a path like array.$ if (p !== parts.length) { if (foundschema.schema) { let ret; if (parts[p] === '$' || isArrayFilter(parts[p])) { if (p + 1 === parts.length) { // comments.$ return foundschema; } // comments.$.comments.$.title ret = search(parts.slice(p + 1), foundschema.schema); if (ret) { ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || !foundschema.schema.$isSingleNested; } return ret; } // this is the last path of the selector ret = search(parts.slice(p), foundschema.schema); if (ret) { ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || !foundschema.schema.$isSingleNested; } return ret; } } } else if (foundschema.$isSchemaMap) { if (p + 1 >= parts.length) { return foundschema.$__schemaType; } const ret = search(parts.slice(p + 1), foundschema.$__schemaType.schema); return ret; } foundschema.$fullPath = resultPath.join('.'); return foundschema; } } } // look for arrays const parts = path.split('.'); for (let i = 0; i < parts.length; ++i) { if (parts[i] === '$' || isArrayFilter(parts[i])) { // Re: gh-5628, because `schema.path()` doesn't take $ into account. parts[i] = '0'; } } return search(parts, _this); }; /*! * ignore */ Schema.prototype._getPathType = function(path) { const _this = this; const pathschema = _this.path(path); if (pathschema) { return 'real'; } function search(parts, schema) { let p = parts.length + 1, foundschema, trypath; while (p--) { trypath = parts.slice(0, p).join('.'); foundschema = schema.path(trypath); if (foundschema) { if (foundschema.caster) { // array of Mixed? if (foundschema.caster instanceof MongooseTypes.Mixed) { return { schema: foundschema, pathType: 'mixed' }; } // Now that we found the array, we need to check if there // are remaining document paths to look up for casting. // Also we need to handle array.$.path since schema.path // doesn't work for that. // If there is no foundschema.schema we are dealing with // a path like array.$ if (p !== parts.length && foundschema.schema) { if (parts[p] === '$' || isArrayFilter(parts[p])) { if (p === parts.length - 1) { return { schema: foundschema, pathType: 'nested' }; } // comments.$.comments.$.title return search(parts.slice(p + 1), foundschema.schema); } // this is the last path of the selector return search(parts.slice(p), foundschema.schema); } return { schema: foundschema, pathType: foundschema.$isSingleNested ? 'nested' : 'array' }; } return { schema: foundschema, pathType: 'real' }; } else if (p === parts.length && schema.nested[trypath]) { return { schema: schema, pathType: 'nested' }; } } return { schema: foundschema || schema, pathType: 'undefined' }; } // look for arrays return search(path.split('.'), _this); }; /*! * ignore */ function isArrayFilter(piece) { return piece.startsWith('$[') && piece.endsWith(']'); } /*! * Module exports. */ module.exports = exports = Schema; // require down here because of reference issues /** * The various built-in Mongoose Schema Types. * * ####Example: * * const mongoose = require('mongoose'); * const ObjectId = mongoose.Schema.Types.ObjectId; * * ####Types: * * - [String](#schema-string-js) * - [Number](#schema-number-js) * - [Boolean](#schema-boolean-js) | Bool * - [Array](#schema-array-js) * - [Buffer](#schema-buffer-js) * - [Date](#schema-date-js) * - [ObjectId](#schema-objectid-js) | Oid * - [Mixed](#schema-mixed-js) * * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. * * const Mixed = mongoose.Schema.Types.Mixed; * new mongoose.Schema({ _user: Mixed }) * * @api public */ Schema.Types = MongooseTypes = require('./schema/index'); /*! * ignore */ exports.ObjectId = MongooseTypes.ObjectId; }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":255,"./driver":270,"./error/mongooseError":281,"./helpers/get":303,"./helpers/model/applyHooks":310,"./helpers/populate/validateRef":312,"./helpers/query/applyQueryMiddleware":316,"./helpers/schema/addAutoId":318,"./helpers/schema/getIndexes":320,"./helpers/schema/merge":323,"./helpers/symbols":326,"./helpers/timestamps/setupTimestamps":327,"./options/SchemaTypeOptions":342,"./options/VirtualOptions":343,"./schema/index":356,"./schematype":369,"./utils":381,"./virtualtype":382,"events":253,"kareem":256,"mpath":384,"util":414}],349:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const CastError = require('../error/cast'); const EventEmitter = require('events').EventEmitter; const ObjectExpectedError = require('../error/objectExpected'); const SchemaSingleNestedOptions = require('../options/SchemaSingleNestedOptions'); const SchemaType = require('../schematype'); const $exists = require('./operators/exists'); const castToNumber = require('./operators/helpers').castToNumber; const discriminator = require('../helpers/model/discriminator'); const geospatial = require('./operators/geospatial'); const get = require('../helpers/get'); const getConstructor = require('../helpers/discriminator/getConstructor'); const handleIdOption = require('../helpers/schema/handleIdOption'); const internalToObjectOptions = require('../options').internalToObjectOptions; let Subdocument; module.exports = SingleNestedPath; /** * Single nested subdocument SchemaType constructor. * * @param {Schema} schema * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SingleNestedPath(schema, path, options) { schema = handleIdOption(schema, options); this.caster = _createConstructor(schema); this.caster.path = path; this.caster.prototype.$basePath = path; this.schema = schema; this.$isSingleNested = true; SchemaType.call(this, path, options, 'Embedded'); } /*! * ignore */ SingleNestedPath.prototype = Object.create(SchemaType.prototype); SingleNestedPath.prototype.constructor = SingleNestedPath; SingleNestedPath.prototype.OptionsConstructor = SchemaSingleNestedOptions; /*! * ignore */ function _createConstructor(schema, baseClass) { // lazy load Subdocument || (Subdocument = require('../types/subdocument')); const _embedded = function SingleNested(value, path, parent) { const _this = this; this.$__parent = parent; Subdocument.apply(this, arguments); this.$session(this.ownerDocument().$session()); if (parent) { parent.on('save', function() { _this.emit('save', _this); _this.constructor.emit('save', _this); }); parent.on('isNew', function(val) { _this.isNew = val; _this.emit('isNew', val); _this.constructor.emit('isNew', val); }); } }; const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; _embedded.prototype = Object.create(proto); _embedded.prototype.$__setSchema(schema); _embedded.prototype.constructor = _embedded; _embedded.schema = schema; _embedded.$isSingleNested = true; _embedded.events = new EventEmitter(); _embedded.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; // apply methods for (const i in schema.methods) { _embedded.prototype[i] = schema.methods[i]; } // apply statics for (const i in schema.statics) { _embedded[i] = schema.statics[i]; } for (const i in EventEmitter.prototype) { _embedded[i] = EventEmitter.prototype[i]; } return _embedded; } /*! * Special case for when users use a common location schema to represent * locations for use with $geoWithin. * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ * * @param {Object} val * @api private */ SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { return { $geometry: this.castForQuery(val.$geometry) }; }; /*! * ignore */ SingleNestedPath.prototype.$conditionalHandlers.$near = SingleNestedPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; SingleNestedPath.prototype.$conditionalHandlers.$within = SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; SingleNestedPath.prototype.$conditionalHandlers.$geoIntersects = geospatial.cast$geoIntersects; SingleNestedPath.prototype.$conditionalHandlers.$minDistance = castToNumber; SingleNestedPath.prototype.$conditionalHandlers.$maxDistance = castToNumber; SingleNestedPath.prototype.$conditionalHandlers.$exists = $exists; /** * Casts contents * * @param {Object} value * @api private */ SingleNestedPath.prototype.cast = function(val, doc, init, priorVal) { if (val && val.$isSingleNested && val.parent === doc) { return val; } if (val != null && (typeof val !== 'object' || Array.isArray(val))) { throw new ObjectExpectedError(this.path, val); } const Constructor = getConstructor(this.caster, val); let subdoc; // Only pull relevant selected paths and pull out the base path const parentSelected = get(doc, '$__.selected', {}); const path = this.path; const selected = Object.keys(parentSelected).reduce((obj, key) => { if (key.startsWith(path + '.')) { obj[key.substr(path.length + 1)] = parentSelected[key]; } return obj; }, {}); if (init) { subdoc = new Constructor(void 0, selected, doc); subdoc.init(val); } else { if (Object.keys(val).length === 0) { return new Constructor({}, selected, doc, undefined, { priorDoc: priorVal }); } return new Constructor(val, selected, doc, undefined, { priorDoc: priorVal }); } return subdoc; }; /** * Casts contents for query * * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) * @param {any} value * @api private */ SingleNestedPath.prototype.castForQuery = function($conditional, val, options) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional); } return handler.call(this, val); } val = $conditional; if (val == null) { return val; } if (this.options.runSetters) { val = this._applySetters(val); } const Constructor = getConstructor(this.caster, val); const overrideStrict = options != null && options.strict != null ? options.strict : void 0; try { val = new Constructor(val, overrideStrict); } catch (error) { // Make sure we always wrap in a CastError (gh-6803) if (!(error instanceof CastError)) { throw new CastError('Embedded', val, this.path, error, this); } throw error; } return val; }; /** * Async validation on this single nested doc. * * @api private */ SingleNestedPath.prototype.doValidate = function(value, fn, scope, options) { const Constructor = getConstructor(this.caster, value); if (options && options.skipSchemaValidators) { if (!(value instanceof Constructor)) { value = new Constructor(value, null, scope); } return value.validate(fn); } SchemaType.prototype.doValidate.call(this, value, function(error) { if (error) { return fn(error); } if (!value) { return fn(null); } value.validate(fn); }, scope, options); }; /** * Synchronously validate this single nested doc * * @api private */ SingleNestedPath.prototype.doValidateSync = function(value, scope, options) { if (!options || !options.skipSchemaValidators) { const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); if (schemaTypeError) { return schemaTypeError; } } if (!value) { return; } return value.validateSync(); }; /** * Adds a discriminator to this single nested subdocument. * * ####Example: * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); * const schema = Schema({ shape: shapeSchema }); * * const singleNestedPath = parentSchema.path('shape'); * singleNestedPath.discriminator('Circle', Schema({ radius: Number })); * * @param {String} name * @param {Schema} schema fields to add to the schema for instances of this sub-class * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model * @see discriminators /docs/discriminators.html * @api public */ SingleNestedPath.prototype.discriminator = function(name, schema, value) { schema = discriminator(this.caster, name, schema, value); this.caster.discriminators[name] = _createConstructor(schema, this.caster); return this.caster.discriminators[name]; }; /** * Sets a default option for all SingleNestedPath instances. * * ####Example: * * // Make all numbers have option `min` equal to 0. * mongoose.Schema.Embedded.set('required', true); * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SingleNestedPath.defaultOptions = {}; SingleNestedPath.set = SchemaType.set; /*! * ignore */ SingleNestedPath.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.schema, this.path, options); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) { schematype.requiredValidator = this.requiredValidator; } schematype.caster.discriminators = Object.assign({}, this.caster.discriminators); return schematype; }; },{"../error/cast":276,"../error/objectExpected":283,"../helpers/discriminator/getConstructor":296,"../helpers/get":303,"../helpers/model/discriminator":311,"../helpers/schema/handleIdOption":321,"../options":331,"../options/SchemaSingleNestedOptions":340,"../schematype":369,"../types/subdocument":380,"./operators/exists":362,"./operators/geospatial":363,"./operators/helpers":364,"events":253}],350:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const $exists = require('./operators/exists'); const $type = require('./operators/type'); const MongooseError = require('../error/mongooseError'); const SchemaArrayOptions = require('../options/SchemaArrayOptions'); const SchemaType = require('../schematype'); const CastError = SchemaType.CastError; const Mixed = require('./mixed'); const arrayDepth = require('../helpers/arrayDepth'); const cast = require('../cast'); const get = require('../helpers/get'); const isOperator = require('../helpers/query/isOperator'); const util = require('util'); const utils = require('../utils'); const castToNumber = require('./operators/helpers').castToNumber; const geospatial = require('./operators/geospatial'); const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue'); let MongooseArray; let EmbeddedDoc; const isNestedArraySymbol = Symbol('mongoose#isNestedArray'); /** * Array SchemaType constructor * * @param {String} key * @param {SchemaType} cast * @param {Object} options * @inherits SchemaType * @api public */ function SchemaArray(key, cast, options, schemaOptions) { // lazy load EmbeddedDoc || (EmbeddedDoc = require('../types').Embedded); let typeKey = 'type'; if (schemaOptions && schemaOptions.typeKey) { typeKey = schemaOptions.typeKey; } this.schemaOptions = schemaOptions; if (cast) { let castOptions = {}; if (utils.isPOJO(cast)) { if (cast[typeKey]) { // support { type: Woot } castOptions = utils.clone(cast); // do not alter user arguments delete castOptions[typeKey]; cast = cast[typeKey]; } else { cast = Mixed; } } if (cast === Object) { cast = Mixed; } // support { type: 'String' } const name = typeof cast === 'string' ? cast : utils.getFunctionName(cast); const Types = require('./index.js'); const caster = Types.hasOwnProperty(name) ? Types[name] : cast; this.casterConstructor = caster; if (this.casterConstructor instanceof SchemaArray) { this.casterConstructor[isNestedArraySymbol] = true; } if (typeof caster === 'function' && !caster.$isArraySubdocument && !caster.$isSchemaMap) { this.caster = new caster(null, castOptions); } else { this.caster = caster; } this.$embeddedSchemaType = this.caster; if (!(this.caster instanceof EmbeddedDoc)) { this.caster.path = key; } } this.$isMongooseArray = true; SchemaType.call(this, key, options, 'Array'); let defaultArr; let fn; if (this.defaultValue != null) { defaultArr = this.defaultValue; fn = typeof defaultArr === 'function'; } if (!('defaultValue' in this) || this.defaultValue !== void 0) { const defaultFn = function() { let arr = []; if (fn) { arr = defaultArr.call(this); } else if (defaultArr != null) { arr = arr.concat(defaultArr); } // Leave it up to `cast()` to convert the array return arr; }; defaultFn.$runBeforeSetters = !fn; this.default(defaultFn); } } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaArray.schemaName = 'Array'; /** * Options for all arrays. * * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. * * @static options * @api public */ SchemaArray.options = { castNonArrays: true }; SchemaArray.defaultOptions = {}; /** * Sets a default option for all Array instances. * * ####Example: * * // Make all Array instances have `required` of true by default. * mongoose.Schema.Array.set('required', true); * * const User = mongoose.model('User', new Schema({ test: Array })); * new User({ }).validateSync().errors.test.message; // Path `test` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaArray.set = SchemaType.set; /*! * Inherits from SchemaType. */ SchemaArray.prototype = Object.create(SchemaType.prototype); SchemaArray.prototype.constructor = SchemaArray; SchemaArray.prototype.OptionsConstructor = SchemaArrayOptions; /*! * ignore */ SchemaArray._checkRequired = SchemaType.prototype.checkRequired; /** * Override the function the required validator uses to check whether an array * passes the `required` check. * * ####Example: * * // Require non-empty array to pass `required` check * mongoose.Schema.Types.Array.checkRequired(v => Array.isArray(v) && v.length); * * const M = mongoose.model({ arr: { type: Array, required: true } }); * new M({ arr: [] }).validateSync(); // `null`, validation fails! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaArray.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies the `required` validator. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaArray.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaArray.checkRequired(); return _checkRequired(value); }; /** * Adds an enum validator if this is an array of strings or numbers. Equivalent to * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()` * * @param {String|Object} [args...] enumeration values * @return {SchemaArray} this */ SchemaArray.prototype.enum = function() { let arr = this; while (true) { const instance = get(arr, 'caster.instance'); if (instance === 'Array') { arr = arr.caster; continue; } if (instance !== 'String' && instance !== 'Number') { throw new Error('`enum` can only be set on an array of strings or numbers ' + ', not ' + instance); } break; } let enumArray = arguments; if (!Array.isArray(arguments) && utils.isObject(arguments)) { enumArray = utils.object.vals(enumArray); } arr.caster.enum.apply(arr.caster, enumArray); return this; }; /** * Overrides the getters application for the population special-case * * @param {Object} value * @param {Object} scope * @api private */ SchemaArray.prototype.applyGetters = function(value, scope) { if (this.caster.options && this.caster.options.ref) { // means the object id was populated return value; } return SchemaType.prototype.applyGetters.call(this, value, scope); }; SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) { if (this.casterConstructor instanceof SchemaArray && SchemaArray.options.castNonArrays && !this[isNestedArraySymbol]) { // Check nesting levels and wrap in array if necessary let depth = 0; let arr = this; while (arr != null && arr instanceof SchemaArray && !arr.$isMongooseDocumentArray) { ++depth; arr = arr.casterConstructor; } // No need to wrap empty arrays if (value != null && value.length > 0) { const valueDepth = arrayDepth(value); if (valueDepth.min === valueDepth.max && valueDepth.max < depth && valueDepth.containsNonArrayItem) { for (let i = valueDepth.max; i < depth; ++i) { value = [value]; } } } } return SchemaType.prototype._applySetters.call(this, value, scope, init, priorVal); }; /** * Casts values for set(). * * @param {Object} value * @param {Document} doc document that triggers the casting * @param {Boolean} init whether this is an initialization cast * @api private */ SchemaArray.prototype.cast = function(value, doc, init, prev, options) { // lazy load MongooseArray || (MongooseArray = require('../types').Array); let i; let l; if (Array.isArray(value)) { if (!value.length && doc) { const indexes = doc.schema.indexedPaths(); const arrayPath = this.path; for (i = 0, l = indexes.length; i < l; ++i) { const pathIndex = indexes[i][0][arrayPath]; if (pathIndex === '2dsphere' || pathIndex === '2d') { return; } } // Special case: if this index is on the parent of what looks like // GeoJSON, skip setting the default to empty array re: #1668, #3233 const arrayGeojsonPath = this.path.endsWith('.coordinates') ? this.path.substr(0, this.path.lastIndexOf('.')) : null; if (arrayGeojsonPath != null) { for (i = 0, l = indexes.length; i < l; ++i) { const pathIndex = indexes[i][0][arrayGeojsonPath]; if (pathIndex === '2dsphere') { return; } } } } if (!(value && value.isMongooseArray)) { value = MongooseArray(value, this._arrayPath || this.path, doc, this); } else if (value && value.isMongooseArray) { // We need to create a new array, otherwise change tracking will // update the old doc (gh-4449) value = MongooseArray(value, this._arrayPath || this.path, doc, this); } const isPopulated = doc != null && doc.$__ != null && doc.populated(this.path); if (isPopulated) { return value; } const caster = this.caster; if (caster && this.casterConstructor !== Mixed) { try { const len = value.length; for (i = 0; i < len; i++) { // Special case: number arrays disallow undefined. // Re: gh-840 // See commit 1298fe92d2c790a90594bd08199e45a4a09162a6 if (caster.instance === 'Number' && value[i] === void 0) { throw new MongooseError('Mongoose number arrays disallow storing undefined'); } const opts = {}; // Perf: creating `arrayPath` is expensive for large arrays. // We only need `arrayPath` if this is a nested array, so // skip if possible. if (caster.$isMongooseArray) { if (options != null && options.arrayPath != null) { opts.arrayPath = options.arrayPath + '.' + i; } else if (this.caster._arrayParentPath != null) { opts.arrayPath = this.caster._arrayParentPath + '.' + i; } } value[i] = caster.applySetters(value[i], doc, init, void 0, opts); } } catch (e) { // rethrow throw new CastError('[' + e.kind + ']', util.inspect(value), this.path + '.' + i, e, this); } } return value; } if (init || SchemaArray.options.castNonArrays) { // gh-2442: if we're loading this from the db and its not an array, mark // the whole array as modified. if (!!doc && !!init) { doc.markModified(this.path); } return this.cast([value], doc, init); } throw new CastError('Array', util.inspect(value), this.path, null, this); }; /*! * Ignore */ SchemaArray.prototype.discriminator = function(name, schema) { let arr = this; // eslint-disable-line consistent-this while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { arr = arr.casterConstructor; if (arr == null || typeof arr === 'function') { throw new MongooseError('You can only add an embedded discriminator on ' + 'a document array, ' + this.path + ' is a plain array'); } } return arr.discriminator(name, schema); }; /*! * ignore */ SchemaArray.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, this.caster, options, this.schemaOptions); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) { schematype.requiredValidator = this.requiredValidator; } return schematype; }; /** * Casts values for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaArray.prototype.castForQuery = function($conditional, value) { let handler; let val; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with Array.'); } val = handler.call(this, value); } else { val = $conditional; let Constructor = this.casterConstructor; if (val && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } const proto = this.casterConstructor.prototype; let method = proto && (proto.castForQuery || proto.cast); if (!method && Constructor.castForQuery) { method = Constructor.castForQuery; } const caster = this.caster; if (Array.isArray(val)) { this.setters.reverse().forEach(setter => { val = setter.call(this, val, this); }); val = val.map(function(v) { if (utils.isObject(v) && v.$elemMatch) { return v; } if (method) { v = method.call(caster, v); return v; } if (v != null) { v = new Constructor(v); return v; } return v; }); } else if (method) { val = method.call(caster, val); } else if (val != null) { val = new Constructor(val); } } return val; }; function cast$all(val) { if (!Array.isArray(val)) { val = [val]; } val = val.map(function(v) { if (utils.isObject(v)) { const o = {}; o[this.path] = v; return cast(this.casterConstructor.schema, o)[this.path]; } return v; }, this); return this.castForQuery(val); } function cast$elemMatch(val) { const keys = Object.keys(val); const numKeys = keys.length; for (let i = 0; i < numKeys; ++i) { const key = keys[i]; const value = val[key]; if (isOperator(key) && value != null) { val[key] = this.castForQuery(key, value); } } // Is this an embedded discriminator and is the discriminator key set? // If so, use the discriminator schema. See gh-7449 const discriminatorKey = get(this, 'casterConstructor.schema.options.discriminatorKey'); const discriminators = get(this, 'casterConstructor.schema.discriminators', {}); if (discriminatorKey != null && val[discriminatorKey] != null && discriminators[val[discriminatorKey]] != null) { return cast(discriminators[val[discriminatorKey]], val); } return cast(this.casterConstructor.schema, val); } const handle = SchemaArray.prototype.$conditionalHandlers = {}; handle.$all = cast$all; handle.$options = String; handle.$elemMatch = cast$elemMatch; handle.$geoIntersects = geospatial.cast$geoIntersects; handle.$or = createLogicalQueryOperatorHandler('$or'); handle.$and = createLogicalQueryOperatorHandler('$and'); handle.$nor = createLogicalQueryOperatorHandler('$nor'); function createLogicalQueryOperatorHandler(op) { return function logicalQueryOperatorHandler(val) { if (!Array.isArray(val)) { throw new TypeError('conditional ' + op + ' requires an array'); } const ret = []; for (const obj of val) { ret.push(cast(this.casterConstructor.schema, obj)); } return ret; }; } handle.$near = handle.$nearSphere = geospatial.cast$near; handle.$within = handle.$geoWithin = geospatial.cast$within; handle.$size = handle.$minDistance = handle.$maxDistance = castToNumber; handle.$exists = $exists; handle.$type = $type; handle.$eq = handle.$gt = handle.$gte = handle.$lt = handle.$lte = handle.$ne = handle.$regex = SchemaArray.prototype.castForQuery; // `$in` is special because you can also include an empty array in the query // like `$in: [1, []]`, see gh-5913 handle.$nin = SchemaType.prototype.$conditionalHandlers.$nin; handle.$in = SchemaType.prototype.$conditionalHandlers.$in; /*! * Module exports. */ module.exports = SchemaArray; },{"../cast":261,"../error/mongooseError":281,"../helpers/arrayDepth":292,"../helpers/discriminator/getDiscriminatorByValue":297,"../helpers/get":303,"../helpers/query/isOperator":317,"../options/SchemaArrayOptions":333,"../schematype":369,"../types":377,"../utils":381,"./index.js":356,"./mixed":358,"./operators/exists":362,"./operators/geospatial":363,"./operators/helpers":364,"./operators/type":366,"util":414}],351:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const CastError = require('../error/cast'); const SchemaType = require('../schematype'); const castBoolean = require('../cast/boolean'); const utils = require('../utils'); /** * Boolean SchemaType constructor. * * @param {String} path * @param {Object} options * @inherits SchemaType * @api public */ function SchemaBoolean(path, options) { SchemaType.call(this, path, options, 'Boolean'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaBoolean.schemaName = 'Boolean'; SchemaBoolean.defaultOptions = {}; /*! * Inherits from SchemaType. */ SchemaBoolean.prototype = Object.create(SchemaType.prototype); SchemaBoolean.prototype.constructor = SchemaBoolean; /*! * ignore */ SchemaBoolean._cast = castBoolean; /** * Sets a default option for all Boolean instances. * * ####Example: * * // Make all booleans have `default` of false. * mongoose.Schema.Boolean.set('default', false); * * const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); * new Order({ }).isPaid; // false * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaBoolean.set = SchemaType.set; /** * Get/set the function used to cast arbitrary values to booleans. * * ####Example: * * // Make Mongoose cast empty string '' to false. * const original = mongoose.Schema.Boolean.cast(); * mongoose.Schema.Boolean.cast(v => { * if (v === '') { * return false; * } * return original(v); * }); * * // Or disable casting entirely * mongoose.Schema.Boolean.cast(false); * * @param {Function} caster * @return {Function} * @function get * @static * @api public */ SchemaBoolean.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ SchemaBoolean._defaultCaster = v => { if (v != null && typeof v !== 'boolean') { throw new Error(); } return v; }; /*! * ignore */ SchemaBoolean._checkRequired = v => v === true || v === false; /** * Override the function the required validator uses to check whether a boolean * passes the `required` check. * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaBoolean.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. For a boolean * to satisfy a required validator, it must be strictly equal to true or to * false. * * @param {Any} value * @return {Boolean} * @api public */ SchemaBoolean.prototype.checkRequired = function(value) { return this.constructor._checkRequired(value); }; /** * Configure which values get casted to `true`. * * ####Example: * * const M = mongoose.model('Test', new Schema({ b: Boolean })); * new M({ b: 'affirmative' }).b; // undefined * mongoose.Schema.Boolean.convertToTrue.add('affirmative'); * new M({ b: 'affirmative' }).b; // true * * @property convertToTrue * @type Set * @api public */ Object.defineProperty(SchemaBoolean, 'convertToTrue', { get: () => castBoolean.convertToTrue, set: v => { castBoolean.convertToTrue = v; } }); /** * Configure which values get casted to `false`. * * ####Example: * * const M = mongoose.model('Test', new Schema({ b: Boolean })); * new M({ b: 'nay' }).b; // undefined * mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); * new M({ b: 'nay' }).b; // false * * @property convertToFalse * @type Set * @api public */ Object.defineProperty(SchemaBoolean, 'convertToFalse', { get: () => castBoolean.convertToFalse, set: v => { castBoolean.convertToFalse = v; } }); /** * Casts to boolean * * @param {Object} value * @param {Object} model - this value is optional * @api private */ SchemaBoolean.prototype.cast = function(value) { let castBoolean; if (typeof this._castFunction === 'function') { castBoolean = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castBoolean = this.constructor.cast(); } else { castBoolean = SchemaBoolean.cast(); } try { return castBoolean(value); } catch (error) { throw new CastError('Boolean', value, this.path, error, this); } }; SchemaBoolean.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, {}); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} val * @api private */ SchemaBoolean.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = SchemaBoolean.$conditionalHandlers[$conditional]; if (handler) { return handler.call(this, val); } return this._castForQuery(val); } return this._castForQuery($conditional); }; /** * * @api private */ SchemaBoolean.prototype._castNullish = function _castNullish(v) { if (typeof v === 'undefined' && this.$$context != null && this.$$context._mongooseOptions != null && this.$$context._mongooseOptions.omitUndefined) { return v; } const castBoolean = typeof this.constructor.cast === 'function' ? this.constructor.cast() : SchemaBoolean.cast(); if (castBoolean == null) { return v; } if (castBoolean.convertToFalse instanceof Set && castBoolean.convertToFalse.has(v)) { return false; } if (castBoolean.convertToTrue instanceof Set && castBoolean.convertToTrue.has(v)) { return true; } return v; }; /*! * Module exports. */ module.exports = SchemaBoolean; },{"../cast/boolean":262,"../error/cast":276,"../schematype":369,"../utils":381}],352:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ 'use strict'; const MongooseBuffer = require('../types/buffer'); const SchemaBufferOptions = require('../options/SchemaBufferOptions'); const SchemaType = require('../schematype'); const handleBitwiseOperator = require('./operators/bitwise'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const Binary = MongooseBuffer.Binary; const CastError = SchemaType.CastError; let Document; /** * Buffer SchemaType constructor * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SchemaBuffer(key, options) { SchemaType.call(this, key, options, 'Buffer'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaBuffer.schemaName = 'Buffer'; SchemaBuffer.defaultOptions = {}; /*! * Inherits from SchemaType. */ SchemaBuffer.prototype = Object.create(SchemaType.prototype); SchemaBuffer.prototype.constructor = SchemaBuffer; SchemaBuffer.prototype.OptionsConstructor = SchemaBufferOptions; /*! * ignore */ SchemaBuffer._checkRequired = v => !!(v && v.length); /** * Sets a default option for all Buffer instances. * * ####Example: * * // Make all buffers have `required` of true by default. * mongoose.Schema.Buffer.set('required', true); * * const User = mongoose.model('User', new Schema({ test: Buffer })); * new User({ }).validateSync().errors.test.message; // Path `test` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaBuffer.set = SchemaType.set; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * ####Example: * * // Allow empty strings to pass `required` check * mongoose.Schema.Types.String.checkRequired(v => v != null); * * const M = mongoose.model({ buf: { type: Buffer, required: true } }); * new M({ buf: Buffer.from('') }).validateSync(); // validation passes! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaBuffer.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. To satisfy a * required validator, a buffer must not be null or undefined and have * non-zero length. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaBuffer.prototype.checkRequired = function(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } return this.constructor._checkRequired(value); }; /** * Casts contents * * @param {Object} value * @param {Document} doc document that triggers the casting * @param {Boolean} init * @api private */ SchemaBuffer.prototype.cast = function(value, doc, init) { let ret; if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (Buffer.isBuffer(value)) { return value; } else if (!utils.isObject(value)) { throw new CastError('Buffer', value, this.path, null, this); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; return ret; } // documents if (value && value._id) { value = value._id; } if (value && value.isMongooseBuffer) { return value; } if (Buffer.isBuffer(value)) { if (!value || !value.isMongooseBuffer) { value = new MongooseBuffer(value, [this.path, doc]); if (this.options.subtype != null) { value._subtype = this.options.subtype; } } return value; } if (value instanceof Binary) { ret = new MongooseBuffer(value.value(true), [this.path, doc]); if (typeof value.sub_type !== 'number') { throw new CastError('Buffer', value, this.path, null, this); } ret._subtype = value.sub_type; return ret; } if (value === null) { return value; } const type = typeof value; if ( type === 'string' || type === 'number' || Array.isArray(value) || (type === 'object' && value.type === 'Buffer' && Array.isArray(value.data)) // gh-6863 ) { if (type === 'number') { value = [value]; } ret = new MongooseBuffer(value, [this.path, doc]); if (this.options.subtype != null) { ret._subtype = this.options.subtype; } return ret; } throw new CastError('Buffer', value, this.path, null, this); }; /** * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/) * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html). * * ####Example: * * const s = new Schema({ uuid: { type: Buffer, subtype: 4 }); * const M = db.model('M', s); * const m = new M({ uuid: 'test string' }); * m.uuid._subtype; // 4 * * @param {Number} subtype the default subtype * @return {SchemaType} this * @api public */ SchemaBuffer.prototype.subtype = function(subtype) { this.options.subtype = subtype; return this; }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } SchemaBuffer.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $bitsAllClear: handleBitwiseOperator, $bitsAnyClear: handleBitwiseOperator, $bitsAllSet: handleBitwiseOperator, $bitsAnySet: handleBitwiseOperator, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaBuffer.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); } return handler.call(this, val); } val = $conditional; const casted = this._castForQuery(val); return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; }; /*! * Module exports. */ module.exports = SchemaBuffer; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../helpers/symbols":326,"../options/SchemaBufferOptions":334,"../schematype":369,"../types/buffer":372,"../utils":381,"./../document":268,"./operators/bitwise":361}],353:[function(require,module,exports){ /*! * Module requirements. */ 'use strict'; const MongooseError = require('../error/index'); const SchemaDateOptions = require('../options/SchemaDateOptions'); const SchemaType = require('../schematype'); const castDate = require('../cast/date'); const utils = require('../utils'); const CastError = SchemaType.CastError; /** * Date SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SchemaDate(key, options) { SchemaType.call(this, key, options, 'Date'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaDate.schemaName = 'Date'; SchemaDate.defaultOptions = {}; /*! * Inherits from SchemaType. */ SchemaDate.prototype = Object.create(SchemaType.prototype); SchemaDate.prototype.constructor = SchemaDate; SchemaDate.prototype.OptionsConstructor = SchemaDateOptions; /*! * ignore */ SchemaDate._cast = castDate; /** * Sets a default option for all Date instances. * * ####Example: * * // Make all dates have `required` of true by default. * mongoose.Schema.Date.set('required', true); * * const User = mongoose.model('User', new Schema({ test: Date })); * new User({ }).validateSync().errors.test.message; // Path `test` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaDate.set = SchemaType.set; /** * Get/set the function used to cast arbitrary values to dates. * * ####Example: * * // Mongoose converts empty string '' into `null` for date types. You * // can create a custom caster to disable it. * const original = mongoose.Schema.Types.Date.cast(); * mongoose.Schema.Types.Date.cast(v => { * assert.ok(v !== ''); * return original(v); * }); * * // Or disable casting entirely * mongoose.Schema.Types.Date.cast(false); * * @param {Function} caster * @return {Function} * @function get * @static * @api public */ SchemaDate.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ SchemaDate._defaultCaster = v => { if (v != null && !(v instanceof Date)) { throw new Error(); } return v; }; /** * Declares a TTL index (rounded to the nearest second) for _Date_ types only. * * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. * This index type is only compatible with Date types. * * ####Example: * * // expire in 24 hours * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); * * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: * * ####Example: * * // expire in 24 hours * new Schema({ createdAt: { type: Date, expires: '24h' }}); * * // expire in 1.5 hours * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); * * // expire in 7 days * const schema = new Schema({ createdAt: Date }); * schema.path('createdAt').expires('7d'); * * @param {Number|String} when * @added 3.0.0 * @return {SchemaType} this * @api public */ SchemaDate.prototype.expires = function(when) { if (!this._index || this._index.constructor.name !== 'Object') { this._index = {}; } this._index.expires = when; utils.expires(this._index); return this; }; /*! * ignore */ SchemaDate._checkRequired = v => v instanceof Date; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * ####Example: * * // Allow empty strings to pass `required` check * mongoose.Schema.Types.String.checkRequired(v => v != null); * * const M = mongoose.model({ str: { type: String, required: true } }); * new M({ str: '' }).validateSync(); // `null`, validation passes! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaDate.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. To satisfy * a required validator, the given value must be an instance of `Date`. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaDate.prototype.checkRequired = function(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaDate.checkRequired(); return _checkRequired(value); }; /** * Sets a minimum date validator. * * ####Example: * * const s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) * const M = db.model('M', s) * const m = new M({ d: Date('1969-12-31') }) * m.save(function (err) { * console.error(err) // validator error * m.d = Date('2014-12-08'); * m.save() // success * }) * * // custom error messages * // We can also use the special {MIN} token which will be replaced with the invalid value * const min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; * const schema = new Schema({ d: { type: Date, min: min }) * const M = mongoose.model('M', schema); * const s= new M({ d: Date('1969-12-31') }); * s.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). * }) * * @param {Date} value minimum date * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaDate.prototype.min = function(value, message) { if (this.minValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minValidator; }, this); } if (value) { let msg = message || MongooseError.messages.Date.min; if (typeof msg === 'string') { msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : value.toString())); } const _this = this; this.validators.push({ validator: this.minValidator = function(val) { let _value = value; if (typeof value === 'function' && value !== Date.now) { _value = _value.call(this); } const min = (_value === Date.now ? _value() : _this.cast(_value)); return val === null || val.valueOf() >= min.valueOf(); }, message: msg, type: 'min', min: value }); } return this; }; /** * Sets a maximum date validator. * * ####Example: * * const s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) * const M = db.model('M', s) * const m = new M({ d: Date('2014-12-08') }) * m.save(function (err) { * console.error(err) // validator error * m.d = Date('2013-12-31'); * m.save() // success * }) * * // custom error messages * // We can also use the special {MAX} token which will be replaced with the invalid value * const max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; * const schema = new Schema({ d: { type: Date, max: max }) * const M = mongoose.model('M', schema); * const s= new M({ d: Date('2014-12-08') }); * s.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). * }) * * @param {Date} maximum date * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaDate.prototype.max = function(value, message) { if (this.maxValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxValidator; }, this); } if (value) { let msg = message || MongooseError.messages.Date.max; if (typeof msg === 'string') { msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : value.toString())); } const _this = this; this.validators.push({ validator: this.maxValidator = function(val) { let _value = value; if (typeof _value === 'function' && _value !== Date.now) { _value = _value.call(this); } const max = (_value === Date.now ? _value() : _this.cast(_value)); return val === null || val.valueOf() <= max.valueOf(); }, message: msg, type: 'max', max: value }); } return this; }; /** * Casts to date * * @param {Object} value to cast * @api private */ SchemaDate.prototype.cast = function(value) { let castDate; if (typeof this._castFunction === 'function') { castDate = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castDate = this.constructor.cast(); } else { castDate = SchemaDate.cast(); } try { return castDate(value); } catch (error) { throw new CastError('date', value, this.path, error, this); } }; /*! * Date Query casting. * * @api private */ function handleSingle(val) { return this.cast(val); } SchemaDate.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaDate.prototype.castForQuery = function($conditional, val) { if (arguments.length !== 2) { return this._castForQuery($conditional); } const handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with Date.'); } return handler.call(this, val); }; /*! * Module exports. */ module.exports = SchemaDate; },{"../cast/date":263,"../error/index":278,"../options/SchemaDateOptions":335,"../schematype":369,"../utils":381}],354:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ 'use strict'; const SchemaType = require('../schematype'); const CastError = SchemaType.CastError; const Decimal128Type = require('../types/decimal128'); const castDecimal128 = require('../cast/decimal128'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; let Document; /** * Decimal128 SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function Decimal128(key, options) { SchemaType.call(this, key, options, 'Decimal128'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ Decimal128.schemaName = 'Decimal128'; Decimal128.defaultOptions = {}; /*! * Inherits from SchemaType. */ Decimal128.prototype = Object.create(SchemaType.prototype); Decimal128.prototype.constructor = Decimal128; /*! * ignore */ Decimal128._cast = castDecimal128; /** * Sets a default option for all Decimal128 instances. * * ####Example: * * // Make all decimal 128s have `required` of true by default. * mongoose.Schema.Decimal128.set('required', true); * * const User = mongoose.model('User', new Schema({ test: mongoose.Decimal128 })); * new User({ }).validateSync().errors.test.message; // Path `test` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ Decimal128.set = SchemaType.set; /** * Get/set the function used to cast arbitrary values to decimals. * * ####Example: * * // Make Mongoose only refuse to cast numbers as decimal128 * const original = mongoose.Schema.Types.Decimal128.cast(); * mongoose.Decimal128.cast(v => { * assert.ok(typeof v !== 'number'); * return original(v); * }); * * // Or disable casting entirely * mongoose.Decimal128.cast(false); * * @param {Function} [caster] * @return {Function} * @function get * @static * @api public */ Decimal128.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ Decimal128._defaultCaster = v => { if (v != null && !(v instanceof Decimal128Type)) { throw new Error(); } return v; }; /*! * ignore */ Decimal128._checkRequired = v => v instanceof Decimal128Type; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ Decimal128.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ Decimal128.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : Decimal128.checkRequired(); return _checkRequired(value); }; /** * Casts to Decimal128 * * @param {Object} value * @param {Object} doc * @param {Boolean} init whether this is an initialization cast * @api private */ Decimal128.prototype.cast = function(value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (value instanceof Decimal128Type) { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('Decimal128', value, this.path, null, this); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); let ret = value; if (!doc.$__.populated || !doc.$__.populated[path] || !doc.$__.populated[path].options || !doc.$__.populated[path].options.options || !doc.$__.populated[path].options.options.lean) { ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; } return ret; } let castDecimal128; if (typeof this._castFunction === 'function') { castDecimal128 = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castDecimal128 = this.constructor.cast(); } else { castDecimal128 = Decimal128.cast(); } try { return castDecimal128(value); } catch (error) { throw new CastError('Decimal128', value, this.path, error, this); } }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } Decimal128.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /*! * Module exports. */ module.exports = Decimal128; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../cast/decimal128":264,"../helpers/symbols":326,"../schematype":369,"../types/decimal128":374,"../utils":381,"./../document":268}],355:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const ArrayType = require('./array'); const CastError = require('../error/cast'); const EventEmitter = require('events').EventEmitter; const SchemaDocumentArrayOptions = require('../options/SchemaDocumentArrayOptions'); const SchemaType = require('../schematype'); const ValidationError = require('../error/validation'); const discriminator = require('../helpers/model/discriminator'); const get = require('../helpers/get'); const handleIdOption = require('../helpers/schema/handleIdOption'); const util = require('util'); const utils = require('../utils'); const getConstructor = require('../helpers/discriminator/getConstructor'); const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const documentArrayParent = require('../helpers/symbols').documentArrayParent; let MongooseDocumentArray; let Subdocument; /** * SubdocsArray SchemaType constructor * * @param {String} key * @param {Schema} schema * @param {Object} options * @inherits SchemaArray * @api public */ function DocumentArrayPath(key, schema, options, schemaOptions) { if (schemaOptions != null && schemaOptions._id != null) { schema = handleIdOption(schema, schemaOptions); } else if (options != null && options._id != null) { schema = handleIdOption(schema, options); } const EmbeddedDocument = _createConstructor(schema, options); EmbeddedDocument.prototype.$basePath = key; ArrayType.call(this, key, EmbeddedDocument, options); this.schema = schema; this.schemaOptions = schemaOptions || {}; this.$isMongooseDocumentArray = true; this.Constructor = EmbeddedDocument; EmbeddedDocument.base = schema.base; const fn = this.defaultValue; if (!('defaultValue' in this) || fn !== void 0) { this.default(function() { let arr = fn.call(this); if (!Array.isArray(arr)) { arr = [arr]; } // Leave it up to `cast()` to convert this to a documentarray return arr; }); } const parentSchemaType = this; this.$embeddedSchemaType = new SchemaType(key + '.$', { required: get(this, 'schemaOptions.required', false) }); this.$embeddedSchemaType.cast = function(value, doc, init) { return parentSchemaType.cast(value, doc, init)[0]; }; this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true; this.$embeddedSchemaType.caster = this.Constructor; this.$embeddedSchemaType.schema = this.schema; } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ DocumentArrayPath.schemaName = 'DocumentArray'; /** * Options for all document arrays. * * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. * * @api public */ DocumentArrayPath.options = { castNonArrays: true }; /*! * Inherits from ArrayType. */ DocumentArrayPath.prototype = Object.create(ArrayType.prototype); DocumentArrayPath.prototype.constructor = DocumentArrayPath; DocumentArrayPath.prototype.OptionsConstructor = SchemaDocumentArrayOptions; /*! * Ignore */ function _createConstructor(schema, options, baseClass) { Subdocument || (Subdocument = require('../types/embedded')); // compile an embedded document for this schema function EmbeddedDocument() { Subdocument.apply(this, arguments); this.$session(this.ownerDocument().$session()); } const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; EmbeddedDocument.prototype = Object.create(proto); EmbeddedDocument.prototype.$__setSchema(schema); EmbeddedDocument.schema = schema; EmbeddedDocument.prototype.constructor = EmbeddedDocument; EmbeddedDocument.$isArraySubdocument = true; EmbeddedDocument.events = new EventEmitter(); // apply methods for (const i in schema.methods) { EmbeddedDocument.prototype[i] = schema.methods[i]; } // apply statics for (const i in schema.statics) { EmbeddedDocument[i] = schema.statics[i]; } for (const i in EventEmitter.prototype) { EmbeddedDocument[i] = EventEmitter.prototype[i]; } EmbeddedDocument.options = options; return EmbeddedDocument; } /** * Adds a discriminator to this document array. * * ####Example: * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); * const schema = Schema({ shapes: [shapeSchema] }); * * const docArrayPath = parentSchema.path('shapes'); * docArrayPath.discriminator('Circle', Schema({ radius: Number })); * * @param {String} name * @param {Schema} schema fields to add to the schema for instances of this sub-class * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. * @see discriminators /docs/discriminators.html * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model * @api public */ DocumentArrayPath.prototype.discriminator = function(name, schema, tiedValue) { if (typeof name === 'function') { name = utils.getFunctionName(name); } schema = discriminator(this.casterConstructor, name, schema, tiedValue); const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor); EmbeddedDocument.baseCasterConstructor = this.casterConstructor; try { Object.defineProperty(EmbeddedDocument, 'name', { value: name }); } catch (error) { // Ignore error, only happens on old versions of node } this.casterConstructor.discriminators[name] = EmbeddedDocument; return this.casterConstructor.discriminators[name]; }; /** * Performs local validations first, then validations on each embedded doc * * @api private */ DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) { // lazy load MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); const _this = this; try { SchemaType.prototype.doValidate.call(this, array, cb, scope); } catch (err) { err.$isArrayValidatorError = true; return fn(err); } function cb(err) { if (err) { err.$isArrayValidatorError = true; return fn(err); } let count = array && array.length; let error; if (!count) { return fn(); } if (options && options.updateValidator) { return fn(); } if (!array.isMongooseDocumentArray) { array = new MongooseDocumentArray(array, _this.path, scope); } // handle sparse arrays, do not use array.forEach which does not // iterate over sparse elements yet reports array.length including // them :( function callback(err) { if (err != null) { error = err; if (!(error instanceof ValidationError)) { error.$isArrayValidatorError = true; } } --count || fn(error); } for (let i = 0, len = count; i < len; ++i) { // sidestep sparse entries let doc = array[i]; if (doc == null) { --count || fn(error); continue; } // If you set the array index directly, the doc might not yet be // a full fledged mongoose subdoc, so make it into one. if (!(doc instanceof Subdocument)) { const Constructor = getConstructor(_this.casterConstructor, array[i]); doc = array[i] = new Constructor(doc, array, undefined, undefined, i); } doc.$__validate(callback); } } }; /** * Performs local validations first, then validations on each embedded doc. * * ####Note: * * This method ignores the asynchronous validators. * * @return {MongooseError|undefined} * @api private */ DocumentArrayPath.prototype.doValidateSync = function(array, scope) { const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); if (schemaTypeError != null) { schemaTypeError.$isArrayValidatorError = true; return schemaTypeError; } const count = array && array.length; let resultError = null; if (!count) { return; } // handle sparse arrays, do not use array.forEach which does not // iterate over sparse elements yet reports array.length including // them :( for (let i = 0, len = count; i < len; ++i) { // sidestep sparse entries let doc = array[i]; if (!doc) { continue; } // If you set the array index directly, the doc might not yet be // a full fledged mongoose subdoc, so make it into one. if (!(doc instanceof Subdocument)) { const Constructor = getConstructor(this.casterConstructor, array[i]); doc = array[i] = new Constructor(doc, array, undefined, undefined, i); } const subdocValidateError = doc.validateSync(); if (subdocValidateError && resultError == null) { resultError = subdocValidateError; } } return resultError; }; /*! * ignore */ DocumentArrayPath.prototype.getDefault = function(scope) { let ret = typeof this.defaultValue === 'function' ? this.defaultValue.call(scope) : this.defaultValue; if (ret == null) { return ret; } // lazy load MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); if (!Array.isArray(ret)) { ret = [ret]; } ret = new MongooseDocumentArray(ret, this.path, scope); for (let i = 0; i < ret.length; ++i) { const Constructor = getConstructor(this.casterConstructor, ret[i]); const _subdoc = new Constructor({}, ret, undefined, undefined, i); _subdoc.init(ret[i]); _subdoc.isNew = true; // Make sure all paths in the subdoc are set to `default` instead // of `init` since we used `init`. Object.assign(_subdoc.$__.activePaths.default, _subdoc.$__.activePaths.init); _subdoc.$__.activePaths.init = {}; ret[i] = _subdoc; } return ret; }; /** * Casts contents * * @param {Object} value * @param {Document} document that triggers the casting * @api private */ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) { // lazy load MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); // Skip casting if `value` is the same as the previous value, no need to cast. See gh-9266 if (value != null && value[arrayPathSymbol] != null && value === prev) { return value; } let selected; let subdoc; const _opts = { transform: false, virtuals: false }; options = options || {}; if (!Array.isArray(value)) { if (!init && !DocumentArrayPath.options.castNonArrays) { throw new CastError('DocumentArray', util.inspect(value), this.path, null, this); } // gh-2442 mark whole array as modified if we're initializing a doc from // the db and the path isn't an array in the document if (!!doc && init) { doc.markModified(this.path); } return this.cast([value], doc, init, prev, options); } if (!(value && value.isMongooseDocumentArray) && !options.skipDocumentArrayCast) { value = new MongooseDocumentArray(value, this.path, doc); } else if (value && value.isMongooseDocumentArray) { // We need to create a new array, otherwise change tracking will // update the old doc (gh-4449) value = new MongooseDocumentArray(value, this.path, doc); } if (options.arrayPath != null) { value[arrayPathSymbol] = options.arrayPath; } const len = value.length; const initDocumentOptions = { skipId: true, willInit: true }; for (let i = 0; i < len; ++i) { if (!value[i]) { continue; } const Constructor = getConstructor(this.casterConstructor, value[i]); // Check if the document has a different schema (re gh-3701) if ((value[i].$__) && (!(value[i] instanceof Constructor) || value[i][documentArrayParent] !== doc)) { value[i] = value[i].toObject({ transform: false, // Special case: if different model, but same schema, apply virtuals // re: gh-7898 virtuals: value[i].schema === Constructor.schema }); } if (value[i] instanceof Subdocument) { // Might not have the correct index yet, so ensure it does. if (value[i].__index == null) { value[i].$setIndex(i); } } else if (value[i] != null) { if (init) { if (doc) { selected || (selected = scopePaths(this, doc.$__.selected, init)); } else { selected = true; } subdoc = new Constructor(null, value, initDocumentOptions, selected, i); value[i] = subdoc.init(value[i]); } else { if (prev && typeof prev.id === 'function') { subdoc = prev.id(value[i]._id); } if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), value[i])) { // handle resetting doc with existing id and same data subdoc.set(value[i]); // if set() is hooked it will have no return value // see gh-746 value[i] = subdoc; } else { try { subdoc = new Constructor(value[i], value, undefined, undefined, i); // if set() is hooked it will have no return value // see gh-746 value[i] = subdoc; } catch (error) { const valueInErrorMessage = util.inspect(value[i]); throw new CastError('embedded', valueInErrorMessage, value[arrayPathSymbol], error, this); } } } } } return value; }; /*! * ignore */ DocumentArrayPath.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) { schematype.requiredValidator = this.requiredValidator; } schematype.Constructor.discriminators = Object.assign({}, this.Constructor.discriminators); return schematype; }; /*! * Scopes paths selected in a query to this array. * Necessary for proper default application of subdocument values. * * @param {DocumentArrayPath} array - the array to scope `fields` paths * @param {Object|undefined} fields - the root fields selected in the query * @param {Boolean|undefined} init - if we are being created part of a query result */ function scopePaths(array, fields, init) { if (!(init && fields)) { return undefined; } const path = array.path + '.'; const keys = Object.keys(fields); let i = keys.length; const selected = {}; let hasKeys; let key; let sub; while (i--) { key = keys[i]; if (key.startsWith(path)) { sub = key.substring(path.length); if (sub === '$') { continue; } if (sub.startsWith('$.')) { sub = sub.substr(2); } hasKeys || (hasKeys = true); selected[sub] = fields[key]; } } return hasKeys && selected || undefined; } /** * Sets a default option for all DocumentArray instances. * * ####Example: * * // Make all numbers have option `min` equal to 0. * mongoose.Schema.DocumentArray.set('_id', false); * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ DocumentArrayPath.defaultOptions = {}; DocumentArrayPath.set = SchemaType.set; /*! * Module exports. */ module.exports = DocumentArrayPath; },{"../error/cast":276,"../error/validation":289,"../helpers/discriminator/getConstructor":296,"../helpers/get":303,"../helpers/model/discriminator":311,"../helpers/schema/handleIdOption":321,"../helpers/symbols":326,"../options/SchemaDocumentArrayOptions":336,"../schematype":369,"../types/documentarray":375,"../types/embedded":376,"../utils":381,"./array":350,"events":253,"util":414}],356:[function(require,module,exports){ /*! * Module exports. */ 'use strict'; exports.String = require('./string'); exports.Number = require('./number'); exports.Boolean = require('./boolean'); exports.DocumentArray = require('./documentarray'); exports.Embedded = require('./SingleNestedPath'); exports.Array = require('./array'); exports.Buffer = require('./buffer'); exports.Date = require('./date'); exports.ObjectId = require('./objectid'); exports.Mixed = require('./mixed'); exports.Decimal128 = exports.Decimal = require('./decimal128'); exports.Map = require('./map'); // alias exports.Oid = exports.ObjectId; exports.Object = exports.Mixed; exports.Bool = exports.Boolean; exports.ObjectID = exports.ObjectId; },{"./SingleNestedPath":349,"./array":350,"./boolean":351,"./buffer":352,"./date":353,"./decimal128":354,"./documentarray":355,"./map":357,"./mixed":358,"./number":359,"./objectid":360,"./string":367}],357:[function(require,module,exports){ (function (global){ 'use strict'; /*! * ignore */ const MongooseMap = require('../types/map'); const SchemaMapOptions = require('../options/SchemaMapOptions'); const SchemaType = require('../schematype'); /*! * ignore */ class Map extends SchemaType { constructor(key, options) { super(key, options, 'Map'); this.$isSchemaMap = true; } set(option, value) { return SchemaType.set(option, value); } cast(val, doc, init) { if (val instanceof MongooseMap) { return val; } if (init) { const map = new MongooseMap({}, this.path, doc, this.$__schemaType); if (val instanceof global.Map) { for (const key of val.keys()) { let _val = val.get(key); if (_val == null) { _val = map.$__schemaType._castNullish(_val); } else { _val = map.$__schemaType.cast(_val, doc, true); } map.$init(key, _val); } } else { for (const key of Object.keys(val)) { let _val = val[key]; if (_val == null) { _val = map.$__schemaType._castNullish(_val); } else { _val = map.$__schemaType.cast(_val, doc, true); } map.$init(key, _val); } } return map; } return new MongooseMap(val, this.path, doc, this.$__schemaType); } clone() { const schematype = super.clone(); if (this.$__schemaType != null) { schematype.$__schemaType = this.$__schemaType.clone(); } return schematype; } } Map.prototype.OptionsConstructor = SchemaMapOptions; Map.defaultOptions = {}; module.exports = Map; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../options/SchemaMapOptions":337,"../schematype":369,"../types/map":378}],358:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const SchemaType = require('../schematype'); const symbols = require('./symbols'); const isObject = require('../helpers/isObject'); /** * Mixed SchemaType constructor. * * @param {String} path * @param {Object} options * @inherits SchemaType * @api public */ function Mixed(path, options) { if (options && options.default) { const def = options.default; if (Array.isArray(def) && def.length === 0) { // make sure empty array defaults are handled options.default = Array; } else if (!options.shared && isObject(def) && Object.keys(def).length === 0) { // prevent odd "shared" objects between documents options.default = function() { return {}; }; } } SchemaType.call(this, path, options, 'Mixed'); this[symbols.schemaMixedSymbol] = true; } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ Mixed.schemaName = 'Mixed'; Mixed.defaultOptions = {}; /*! * Inherits from SchemaType. */ Mixed.prototype = Object.create(SchemaType.prototype); Mixed.prototype.constructor = Mixed; /** * Attaches a getter for all Mixed paths. * * ####Example: * * // Hide the 'hidden' path * mongoose.Schema.Mixed.get(v => Object.assign({}, v, { hidden: null })); * * const Model = mongoose.model('Test', new Schema({ test: {} })); * new Model({ test: { hidden: 'Secret!' } }).test.hidden; // null * * @param {Function} getter * @return {this} * @function get * @static * @api public */ Mixed.get = SchemaType.get; /** * Sets a default option for all Mixed instances. * * ####Example: * * // Make all mixed instances have `required` of true by default. * mongoose.Schema.Mixed.set('required', true); * * const User = mongoose.model('User', new Schema({ test: mongoose.Mixed })); * new User({ }).validateSync().errors.test.message; // Path `test` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ Mixed.set = SchemaType.set; /** * Casts `val` for Mixed. * * _this is a no-op_ * * @param {Object} value to cast * @api private */ Mixed.prototype.cast = function(val) { return val; }; /** * Casts contents for queries. * * @param {String} $cond * @param {any} [val] * @api private */ Mixed.prototype.castForQuery = function($cond, val) { if (arguments.length === 2) { return val; } return $cond; }; /*! * Module exports. */ module.exports = Mixed; },{"../helpers/isObject":308,"../schematype":369,"./symbols":368}],359:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module requirements. */ const MongooseError = require('../error/index'); const SchemaNumberOptions = require('../options/SchemaNumberOptions'); const SchemaType = require('../schematype'); const castNumber = require('../cast/number'); const handleBitwiseOperator = require('./operators/bitwise'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const CastError = SchemaType.CastError; let Document; /** * Number SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SchemaNumber(key, options) { SchemaType.call(this, key, options, 'Number'); } /** * Attaches a getter for all Number instances. * * ####Example: * * // Make all numbers round down * mongoose.Number.get(function(v) { return Math.floor(v); }); * * const Model = mongoose.model('Test', new Schema({ test: Number })); * new Model({ test: 3.14 }).test; // 3 * * @param {Function} getter * @return {this} * @function get * @static * @api public */ SchemaNumber.get = SchemaType.get; /** * Sets a default option for all Number instances. * * ####Example: * * // Make all numbers have option `min` equal to 0. * mongoose.Schema.Number.set('min', 0); * * const Order = mongoose.model('Order', new Schema({ amount: Number })); * new Order({ amount: -10 }).validateSync().errors.amount.message; // Path `amount` must be larger than 0. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaNumber.set = SchemaType.set; /*! * ignore */ SchemaNumber._cast = castNumber; /** * Get/set the function used to cast arbitrary values to numbers. * * ####Example: * * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers * const original = mongoose.Number.cast(); * mongoose.Number.cast(v => { * if (v === '') { return 0; } * return original(v); * }); * * // Or disable casting entirely * mongoose.Number.cast(false); * * @param {Function} caster * @return {Function} * @function get * @static * @api public */ SchemaNumber.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ SchemaNumber._defaultCaster = v => { if (typeof v !== 'number') { throw new Error(); } return v; }; /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaNumber.schemaName = 'Number'; SchemaNumber.defaultOptions = {}; /*! * Inherits from SchemaType. */ SchemaNumber.prototype = Object.create(SchemaType.prototype); SchemaNumber.prototype.constructor = SchemaNumber; SchemaNumber.prototype.OptionsConstructor = SchemaNumberOptions; /*! * ignore */ SchemaNumber._checkRequired = v => typeof v === 'number' || v instanceof Number; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaNumber.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaNumber.checkRequired(); return _checkRequired(value); }; /** * Sets a minimum number validator. * * ####Example: * * const s = new Schema({ n: { type: Number, min: 10 }) * const M = db.model('M', s) * const m = new M({ n: 9 }) * m.save(function (err) { * console.error(err) // validator error * m.n = 10; * m.save() // success * }) * * // custom error messages * // We can also use the special {MIN} token which will be replaced with the invalid value * const min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; * const schema = new Schema({ n: { type: Number, min: min }) * const M = mongoose.model('Measurement', schema); * const s= new M({ n: 4 }); * s.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). * }) * * @param {Number} value minimum number * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaNumber.prototype.min = function(value, message) { if (this.minValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.Number.min; msg = msg.replace(/{MIN}/, value); this.validators.push({ validator: this.minValidator = function(v) { return v == null || v >= value; }, message: msg, type: 'min', min: value }); } return this; }; /** * Sets a maximum number validator. * * ####Example: * * const s = new Schema({ n: { type: Number, max: 10 }) * const M = db.model('M', s) * const m = new M({ n: 11 }) * m.save(function (err) { * console.error(err) // validator error * m.n = 10; * m.save() // success * }) * * // custom error messages * // We can also use the special {MAX} token which will be replaced with the invalid value * const max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; * const schema = new Schema({ n: { type: Number, max: max }) * const M = mongoose.model('Measurement', schema); * const s= new M({ n: 4 }); * s.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). * }) * * @param {Number} maximum number * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaNumber.prototype.max = function(value, message) { if (this.maxValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.Number.max; msg = msg.replace(/{MAX}/, value); this.validators.push({ validator: this.maxValidator = function(v) { return v == null || v <= value; }, message: msg, type: 'max', max: value }); } return this; }; /** * Sets a enum validator * * ####Example: * * const s = new Schema({ n: { type: Number, enum: [1, 2, 3] }); * const M = db.model('M', s); * * const m = new M({ n: 4 }); * await m.save(); // throws validation error * * m.n = 3; * await m.save(); // succeeds * * @param {Array} values allowed values * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaNumber.prototype.enum = function(values, message) { if (this.enumValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.enumValidator; }, this); } if (!Array.isArray(values)) { if (utils.isObject(values)) { values = utils.object.vals(values); } else { values = Array.prototype.slice.call(arguments); } message = MongooseError.messages.Number.enum; } message = message == null ? MongooseError.messages.Number.enum : message; this.enumValidator = v => v == null || values.indexOf(v) !== -1; this.validators.push({ validator: this.enumValidator, message: message, type: 'enum', enumValues: values }); return this; }; /** * Casts to number * * @param {Object} value value to cast * @param {Document} doc document that triggers the casting * @param {Boolean} init * @api private */ SchemaNumber.prototype.cast = function(value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (typeof value === 'number') { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('Number', value, this.path, null, this); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); const ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; return ret; } const val = value && typeof value._id !== 'undefined' ? value._id : // documents value; let castNumber; if (typeof this._castFunction === 'function') { castNumber = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castNumber = this.constructor.cast(); } else { castNumber = SchemaNumber.cast(); } try { return castNumber(val); } catch (err) { throw new CastError('Number', val, this.path, err, this); } }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } function handleArray(val) { const _this = this; if (!Array.isArray(val)) { return [this.cast(val)]; } return val.map(function(m) { return _this.cast(m); }); } SchemaNumber.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $bitsAllClear: handleBitwiseOperator, $bitsAnyClear: handleBitwiseOperator, $bitsAllSet: handleBitwiseOperator, $bitsAnySet: handleBitwiseOperator, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $mod: handleArray }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaNumber.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new CastError('number', val, this.path, null, this); } return handler.call(this, val); } val = this._castForQuery($conditional); return val; }; /*! * Module exports. */ module.exports = SchemaNumber; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../cast/number":265,"../error/index":278,"../helpers/symbols":326,"../options/SchemaNumberOptions":338,"../schematype":369,"../utils":381,"./../document":268,"./operators/bitwise":361}],360:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ 'use strict'; const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions'); const SchemaType = require('../schematype'); const castObjectId = require('../cast/objectid'); const oid = require('../types/objectid'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const CastError = SchemaType.CastError; let Document; /** * ObjectId SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function ObjectId(key, options) { const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); const suppressWarning = options && options.suppressWarning; if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) { console.warn('mongoose: To create a new ObjectId please try ' + '`Mongoose.Types.ObjectId` instead of using ' + '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' + 'you\'re trying to create a hex char path in your schema.'); console.trace(); } SchemaType.call(this, key, options, 'ObjectID'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ ObjectId.schemaName = 'ObjectId'; ObjectId.defaultOptions = {}; /*! * Inherits from SchemaType. */ ObjectId.prototype = Object.create(SchemaType.prototype); ObjectId.prototype.constructor = ObjectId; ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions; /** * Attaches a getter for all ObjectId instances * * ####Example: * * // Always convert to string when getting an ObjectId * mongoose.ObjectId.get(v => v.toString()); * * const Model = mongoose.model('Test', new Schema({})); * typeof (new Model({})._id); // 'string' * * @param {Function} getter * @return {this} * @function get * @static * @api public */ ObjectId.get = SchemaType.get; /** * Sets a default option for all ObjectId instances. * * ####Example: * * // Make all object ids have option `required` equal to true. * mongoose.Schema.ObjectId.set('required', true); * * const Order = mongoose.model('Order', new Schema({ userId: ObjectId })); * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required. * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ ObjectId.set = SchemaType.set; /** * Adds an auto-generated ObjectId default if turnOn is true. * @param {Boolean} turnOn auto generated ObjectId defaults * @api public * @return {SchemaType} this */ ObjectId.prototype.auto = function(turnOn) { if (turnOn) { this.default(defaultId); this.set(resetId); } return this; }; /*! * ignore */ ObjectId._checkRequired = v => v instanceof oid; /*! * ignore */ ObjectId._cast = castObjectId; /** * Get/set the function used to cast arbitrary values to objectids. * * ####Example: * * // Make Mongoose only try to cast length 24 strings. By default, any 12 * // char string is a valid ObjectId. * const original = mongoose.ObjectId.cast(); * mongoose.ObjectId.cast(v => { * assert.ok(typeof v !== 'string' || v.length === 24); * return original(v); * }); * * // Or disable casting entirely * mongoose.ObjectId.cast(false); * * @param {Function} caster * @return {Function} * @function get * @static * @api public */ ObjectId.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ ObjectId._defaultCaster = v => { if (!(v instanceof oid)) { throw new Error(v + ' is not an instance of ObjectId'); } return v; }; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * ####Example: * * // Allow empty strings to pass `required` check * mongoose.Schema.Types.String.checkRequired(v => v != null); * * const M = mongoose.model({ str: { type: String, required: true } }); * new M({ str: '' }).validateSync(); // `null`, validation passes! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ ObjectId.checkRequired = SchemaType.checkRequired; /** * Check if the given value satisfies a required validator. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ ObjectId.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : ObjectId.checkRequired(); return _checkRequired(value); }; /** * Casts to ObjectId * * @param {Object} value * @param {Object} doc * @param {Boolean} init whether this is an initialization cast * @api private */ ObjectId.prototype.cast = function(value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (value instanceof oid) { return value; } else if ((value.constructor.name || '').toLowerCase() === 'objectid') { return new oid(value.toHexString()); } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('ObjectId', value, this.path, null, this); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); let ret = value; if (!doc.$__.populated || !doc.$__.populated[path] || !doc.$__.populated[path].options || !doc.$__.populated[path].options.options || !doc.$__.populated[path].options.options.lean) { ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; } return ret; } let castObjectId; if (typeof this._castFunction === 'function') { castObjectId = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castObjectId = this.constructor.cast(); } else { castObjectId = ObjectId.cast(); } try { return castObjectId(value); } catch (error) { throw new CastError('ObjectId', value, this.path, error, this); } }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } ObjectId.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /*! * ignore */ function defaultId() { return new oid(); } defaultId.$runBeforeSetters = true; function resetId(v) { Document || (Document = require('./../document')); if (this instanceof Document) { if (v === void 0) { const _v = new oid; this.$__._id = _v; return _v; } this.$__._id = v; } return v; } /*! * Module exports. */ module.exports = ObjectId; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../cast/objectid":266,"../helpers/symbols":326,"../options/SchemaObjectIdOptions":339,"../schematype":369,"../types/objectid":379,"../utils":381,"./../document":268}],361:[function(require,module,exports){ (function (Buffer){ /*! * Module requirements. */ 'use strict'; const CastError = require('../../error/cast'); /*! * ignore */ function handleBitwiseOperator(val) { const _this = this; if (Array.isArray(val)) { return val.map(function(v) { return _castNumber(_this.path, v); }); } else if (Buffer.isBuffer(val)) { return val; } // Assume trying to cast to number return _castNumber(_this.path, val); } /*! * ignore */ function _castNumber(path, num) { const v = Number(num); if (isNaN(v)) { throw new CastError('number', num, path); } return v; } module.exports = handleBitwiseOperator; }).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) },{"../../../../is-buffer/index.js":255,"../../error/cast":276}],362:[function(require,module,exports){ 'use strict'; const castBoolean = require('../../cast/boolean'); /*! * ignore */ module.exports = function(val) { const path = this != null ? this.path : null; return castBoolean(val, path); }; },{"../../cast/boolean":262}],363:[function(require,module,exports){ /*! * Module requirements. */ 'use strict'; const castArraysOfNumbers = require('./helpers').castArraysOfNumbers; const castToNumber = require('./helpers').castToNumber; /*! * ignore */ exports.cast$geoIntersects = cast$geoIntersects; exports.cast$near = cast$near; exports.cast$within = cast$within; function cast$near(val) { const SchemaArray = require('../array'); if (Array.isArray(val)) { castArraysOfNumbers(val, this); return val; } _castMinMaxDistance(this, val); if (val && val.$geometry) { return cast$geometry(val, this); } if (!Array.isArray(val)) { throw new TypeError('$near must be either an array or an object ' + 'with a $geometry property'); } return SchemaArray.prototype.castForQuery.call(this, val); } function cast$geometry(val, self) { switch (val.$geometry.type) { case 'Polygon': case 'LineString': case 'Point': castArraysOfNumbers(val.$geometry.coordinates, self); break; default: // ignore unknowns break; } _castMinMaxDistance(self, val); return val; } function cast$within(val) { _castMinMaxDistance(this, val); if (val.$box || val.$polygon) { const type = val.$box ? '$box' : '$polygon'; val[type].forEach(arr => { if (!Array.isArray(arr)) { const msg = 'Invalid $within $box argument. ' + 'Expected an array, received ' + arr; throw new TypeError(msg); } arr.forEach((v, i) => { arr[i] = castToNumber.call(this, v); }); }); } else if (val.$center || val.$centerSphere) { const type = val.$center ? '$center' : '$centerSphere'; val[type].forEach((item, i) => { if (Array.isArray(item)) { item.forEach((v, j) => { item[j] = castToNumber.call(this, v); }); } else { val[type][i] = castToNumber.call(this, item); } }); } else if (val.$geometry) { cast$geometry(val, this); } return val; } function cast$geoIntersects(val) { const geo = val.$geometry; if (!geo) { return; } cast$geometry(val, this); return val; } function _castMinMaxDistance(self, val) { if (val.$maxDistance) { val.$maxDistance = castToNumber.call(self, val.$maxDistance); } if (val.$minDistance) { val.$minDistance = castToNumber.call(self, val.$minDistance); } } },{"../array":350,"./helpers":364}],364:[function(require,module,exports){ 'use strict'; /*! * Module requirements. */ const SchemaNumber = require('../number'); /*! * @ignore */ exports.castToNumber = castToNumber; exports.castArraysOfNumbers = castArraysOfNumbers; /*! * @ignore */ function castToNumber(val) { return SchemaNumber.cast()(val); } function castArraysOfNumbers(arr, self) { arr.forEach(function(v, i) { if (Array.isArray(v)) { castArraysOfNumbers(v, self); } else { arr[i] = castToNumber.call(self, v); } }); } },{"../number":359}],365:[function(require,module,exports){ 'use strict'; const CastError = require('../../error/cast'); const castBoolean = require('../../cast/boolean'); const castString = require('../../cast/string'); /*! * Casts val to an object suitable for `$text`. Throws an error if the object * can't be casted. * * @param {Any} val value to cast * @param {String} [path] path to associate with any errors that occured * @return {Object} casted object * @see https://docs.mongodb.com/manual/reference/operator/query/text/ * @api private */ module.exports = function(val, path) { if (val == null || typeof val !== 'object') { throw new CastError('$text', val, path); } if (val.$search != null) { val.$search = castString(val.$search, path + '.$search'); } if (val.$language != null) { val.$language = castString(val.$language, path + '.$language'); } if (val.$caseSensitive != null) { val.$caseSensitive = castBoolean(val.$caseSensitive, path + '.$castSensitive'); } if (val.$diacriticSensitive != null) { val.$diacriticSensitive = castBoolean(val.$diacriticSensitive, path + '.$diacriticSensitive'); } return val; }; },{"../../cast/boolean":262,"../../cast/string":267,"../../error/cast":276}],366:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function(val) { if (Array.isArray(val)) { if (!val.every(v => typeof v === 'number' || typeof v === 'string')) { throw new Error('$type array values must be strings or numbers'); } return val; } if (typeof val !== 'number' && typeof val !== 'string') { throw new Error('$type parameter must be number, string, or array of numbers and strings'); } return val; }; },{}],367:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ const SchemaType = require('../schematype'); const MongooseError = require('../error/index'); const SchemaStringOptions = require('../options/SchemaStringOptions'); const castString = require('../cast/string'); const utils = require('../utils'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const CastError = SchemaType.CastError; let Document; /** * String SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SchemaString(key, options) { this.enumValues = []; this.regExp = null; SchemaType.call(this, key, options, 'String'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaString.schemaName = 'String'; SchemaString.defaultOptions = {}; /*! * Inherits from SchemaType. */ SchemaString.prototype = Object.create(SchemaType.prototype); SchemaString.prototype.constructor = SchemaString; Object.defineProperty(SchemaString.prototype, 'OptionsConstructor', { configurable: false, enumerable: false, writable: false, value: SchemaStringOptions }); /*! * ignore */ SchemaString._cast = castString; /** * Get/set the function used to cast arbitrary values to strings. * * ####Example: * * // Throw an error if you pass in an object. Normally, Mongoose allows * // objects with custom `toString()` functions. * const original = mongoose.Schema.Types.String.cast(); * mongoose.Schema.Types.String.cast(v => { * assert.ok(v == null || typeof v !== 'object'); * return original(v); * }); * * // Or disable casting entirely * mongoose.Schema.Types.String.cast(false); * * @param {Function} caster * @return {Function} * @function get * @static * @api public */ SchemaString.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = this._defaultCaster; } this._cast = caster; return this._cast; }; /*! * ignore */ SchemaString._defaultCaster = v => { if (v != null && typeof v !== 'string') { throw new Error(); } return v; }; /** * Attaches a getter for all String instances. * * ####Example: * * // Make all numbers round down * mongoose.Schema.String.get(v => v.toLowerCase()); * * const Model = mongoose.model('Test', new Schema({ test: String })); * new Model({ test: 'FOO' }).test; // 'foo' * * @param {Function} getter * @return {this} * @function get * @static * @api public */ SchemaString.get = SchemaType.get; /** * Sets a default option for all String instances. * * ####Example: * * // Make all strings have option `trim` equal to true. * mongoose.Schema.String.set('trim', true); * * const User = mongoose.model('User', new Schema({ name: String })); * new User({ name: ' John Doe ' }).name; // 'John Doe' * * @param {String} option - The option you'd like to set the value for * @param {*} value - value for option * @return {undefined} * @function set * @static * @api public */ SchemaString.set = SchemaType.set; /*! * ignore */ SchemaString._checkRequired = v => (v instanceof String || typeof v === 'string') && v.length; /** * Override the function the required validator uses to check whether a string * passes the `required` check. * * ####Example: * * // Allow empty strings to pass `required` check * mongoose.Schema.Types.String.checkRequired(v => v != null); * * const M = mongoose.model({ str: { type: String, required: true } }); * new M({ str: '' }).validateSync(); // `null`, validation passes! * * @param {Function} fn * @return {Function} * @function checkRequired * @static * @api public */ SchemaString.checkRequired = SchemaType.checkRequired; /** * Adds an enum validator * * ####Example: * * const states = ['opening', 'open', 'closing', 'closed'] * const s = new Schema({ state: { type: String, enum: states }}) * const M = db.model('M', s) * const m = new M({ state: 'invalid' }) * m.save(function (err) { * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. * m.state = 'open' * m.save(callback) // success * }) * * // or with custom error messages * const enum = { * values: ['opening', 'open', 'closing', 'closed'], * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' * } * const s = new Schema({ state: { type: String, enum: enum }) * const M = db.model('M', s) * const m = new M({ state: 'invalid' }) * m.save(function (err) { * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` * m.state = 'open' * m.save(callback) // success * }) * * @param {String|Object} [args...] enumeration values * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaString.prototype.enum = function() { if (this.enumValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.enumValidator; }, this); this.enumValidator = false; } if (arguments[0] === void 0 || arguments[0] === false) { return this; } let values; let errorMessage; if (utils.isObject(arguments[0])) { if (Array.isArray(arguments[0].values)) { values = arguments[0].values; errorMessage = arguments[0].message; } else { values = utils.object.vals(arguments[0]); errorMessage = MongooseError.messages.String.enum; } } else { values = arguments; errorMessage = MongooseError.messages.String.enum; } for (const value of values) { if (value !== undefined) { this.enumValues.push(this.cast(value)); } } const vals = this.enumValues; this.enumValidator = function(v) { return undefined === v || ~vals.indexOf(v); }; this.validators.push({ validator: this.enumValidator, message: errorMessage, type: 'enum', enumValues: vals }); return this; }; /** * Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). * * ####Example: * * const s = new Schema({ email: { type: String, lowercase: true }}) * const M = db.model('M', s); * const m = new M({ email: 'SomeEmail@example.COM' }); * console.log(m.email) // someemail@example.com * M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com' * * Note that `lowercase` does **not** affect regular expression queries: * * ####Example: * // Still queries for documents whose `email` matches the regular * // expression /SomeEmail/. Mongoose does **not** convert the RegExp * // to lowercase. * M.find({ email: /SomeEmail/ }); * * @api public * @return {SchemaType} this */ SchemaString.prototype.lowercase = function(shouldApply) { if (arguments.length > 0 && !shouldApply) { return this; } return this.set(function(v, self) { if (typeof v !== 'string') { v = self.cast(v); } if (v) { return v.toLowerCase(); } return v; }); }; /** * Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). * * ####Example: * * const s = new Schema({ caps: { type: String, uppercase: true }}) * const M = db.model('M', s); * const m = new M({ caps: 'an example' }); * console.log(m.caps) // AN EXAMPLE * M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE' * * Note that `uppercase` does **not** affect regular expression queries: * * ####Example: * // Mongoose does **not** convert the RegExp to uppercase. * M.find({ email: /an example/ }); * * @api public * @return {SchemaType} this */ SchemaString.prototype.uppercase = function(shouldApply) { if (arguments.length > 0 && !shouldApply) { return this; } return this.set(function(v, self) { if (typeof v !== 'string') { v = self.cast(v); } if (v) { return v.toUpperCase(); } return v; }); }; /** * Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). * * The string value will be trimmed when set. * * ####Example: * * const s = new Schema({ name: { type: String, trim: true }}); * const M = db.model('M', s); * const string = ' some name '; * console.log(string.length); // 11 * const m = new M({ name: string }); * console.log(m.name.length); // 9 * * // Equivalent to `findOne({ name: string.trim() })` * M.findOne({ name: string }); * * Note that `trim` does **not** affect regular expression queries: * * ####Example: * // Mongoose does **not** trim whitespace from the RegExp. * M.find({ name: / some name / }); * * @api public * @return {SchemaType} this */ SchemaString.prototype.trim = function(shouldTrim) { if (arguments.length > 0 && !shouldTrim) { return this; } return this.set(function(v, self) { if (typeof v !== 'string') { v = self.cast(v); } if (v) { return v.trim(); } return v; }); }; /** * Sets a minimum length validator. * * ####Example: * * const schema = new Schema({ postalCode: { type: String, minlength: 5 }) * const Address = db.model('Address', schema) * const address = new Address({ postalCode: '9512' }) * address.save(function (err) { * console.error(err) // validator error * address.postalCode = '95125'; * address.save() // success * }) * * // custom error messages * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length * const minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; * const schema = new Schema({ postalCode: { type: String, minlength: minlength }) * const Address = mongoose.model('Address', schema); * const address = new Address({ postalCode: '9512' }); * address.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). * }) * * @param {Number} value minimum string length * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaString.prototype.minlength = function(value, message) { if (this.minlengthValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.minlengthValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.String.minlength; msg = msg.replace(/{MINLENGTH}/, value); this.validators.push({ validator: this.minlengthValidator = function(v) { return v === null || v.length >= value; }, message: msg, type: 'minlength', minlength: value }); } return this; }; SchemaString.prototype.minLength = SchemaString.prototype.minlength; /** * Sets a maximum length validator. * * ####Example: * * const schema = new Schema({ postalCode: { type: String, maxlength: 9 }) * const Address = db.model('Address', schema) * const address = new Address({ postalCode: '9512512345' }) * address.save(function (err) { * console.error(err) // validator error * address.postalCode = '95125'; * address.save() // success * }) * * // custom error messages * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length * const maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; * const schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) * const Address = mongoose.model('Address', schema); * const address = new Address({ postalCode: '9512512345' }); * address.validate(function (err) { * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). * }) * * @param {Number} value maximum string length * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaString.prototype.maxlength = function(value, message) { if (this.maxlengthValidator) { this.validators = this.validators.filter(function(v) { return v.validator !== this.maxlengthValidator; }, this); } if (value !== null && value !== undefined) { let msg = message || MongooseError.messages.String.maxlength; msg = msg.replace(/{MAXLENGTH}/, value); this.validators.push({ validator: this.maxlengthValidator = function(v) { return v === null || v.length <= value; }, message: msg, type: 'maxlength', maxlength: value }); } return this; }; SchemaString.prototype.maxLength = SchemaString.prototype.maxlength; /** * Sets a regexp validator. * * Any value that does not pass `regExp`.test(val) will fail validation. * * ####Example: * * const s = new Schema({ name: { type: String, match: /^a/ }}) * const M = db.model('M', s) * const m = new M({ name: 'I am invalid' }) * m.validate(function (err) { * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." * m.name = 'apples' * m.validate(function (err) { * assert.ok(err) // success * }) * }) * * // using a custom error message * const match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; * const s = new Schema({ file: { type: String, match: match }}) * const M = db.model('M', s); * const m = new M({ file: 'invalid' }); * m.validate(function (err) { * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" * }) * * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. * * const s = new Schema({ name: { type: String, match: /^a/, required: true }}) * * @param {RegExp} regExp regular expression to test against * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @api public */ SchemaString.prototype.match = function match(regExp, message) { // yes, we allow multiple match validators const msg = message || MongooseError.messages.String.match; const matchValidator = function(v) { if (!regExp) { return false; } // In case RegExp happens to have `/g` flag set, we need to reset the // `lastIndex`, otherwise `match` will intermittently fail. regExp.lastIndex = 0; const ret = ((v != null && v !== '') ? regExp.test(v) : true); return ret; }; this.validators.push({ validator: matchValidator, message: msg, type: 'regexp', regexp: regExp }); return this; }; /** * Check if the given value satisfies the `required` validator. The value is * considered valid if it is a string (that is, not `null` or `undefined`) and * has positive length. The `required` validator **will** fail for empty * strings. * * @param {Any} value * @param {Document} doc * @return {Boolean} * @api public */ SchemaString.prototype.checkRequired = function checkRequired(value, doc) { if (SchemaType._isRef(this, value, doc, true)) { return !!value; } // `require('util').inherits()` does **not** copy static properties, and // plugins like mongoose-float use `inherits()` for pre-ES6. const _checkRequired = typeof this.constructor.checkRequired == 'function' ? this.constructor.checkRequired() : SchemaString.checkRequired(); return _checkRequired(value); }; /** * Casts to String * * @api private */ SchemaString.prototype.cast = function(value, doc, init) { if (SchemaType._isRef(this, value, doc, init)) { // wait! we may need to cast this to a document if (value === null || value === undefined) { return value; } // lazy load Document || (Document = require('./../document')); if (value instanceof Document) { value.$__.wasPopulated = true; return value; } // setting a populated path if (typeof value === 'string') { return value; } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { throw new CastError('string', value, this.path, null, this); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. const path = doc.$__fullPath(this.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; const pop = owner.populated(path, true); const ret = new pop.options[populateModelSymbol](value); ret.$__.wasPopulated = true; return ret; } let castString; if (typeof this._castFunction === 'function') { castString = this._castFunction; } else if (typeof this.constructor.cast === 'function') { castString = this.constructor.cast(); } else { castString = SchemaString.cast(); } try { return castString(value); } catch (error) { throw new CastError('string', value, this.path, null, this); } }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } function handleArray(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { return _this.castForQuery(m); }); } const $conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $all: handleArray, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $options: String, $regex: handleSingle, $not: handleSingle }); Object.defineProperty(SchemaString.prototype, '$conditionalHandlers', { configurable: false, enumerable: false, writable: false, value: Object.freeze($conditionalHandlers) }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [val] * @api private */ SchemaString.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with String.'); } return handler.call(this, val); } val = $conditional; if (Object.prototype.toString.call(val) === '[object RegExp]') { return val; } return this._castForQuery(val); }; /*! * Module exports. */ module.exports = SchemaString; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../cast/string":267,"../error/index":278,"../helpers/symbols":326,"../options/SchemaStringOptions":341,"../schematype":369,"../utils":381,"./../document":268}],368:[function(require,module,exports){ 'use strict'; exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed'); exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware'); },{}],369:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ const MongooseError = require('./error/index'); const SchemaTypeOptions = require('./options/SchemaTypeOptions'); const $exists = require('./schema/operators/exists'); const $type = require('./schema/operators/type'); const get = require('./helpers/get'); const handleImmutable = require('./helpers/schematype/handleImmutable'); const immediate = require('./helpers/immediate'); const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol; const util = require('util'); const utils = require('./utils'); const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol; const documentIsSelected = require('./helpers/symbols').documentIsSelected; const documentIsModified = require('./helpers/symbols').documentIsModified; const CastError = MongooseError.CastError; const ValidatorError = MongooseError.ValidatorError; /** * SchemaType constructor. Do **not** instantiate `SchemaType` directly. * Mongoose converts your schema paths into SchemaTypes automatically. * * ####Example: * * const schema = new Schema({ name: String }); * schema.path('name') instanceof SchemaType; // true * * @param {String} path * @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html) * @param {String} [instance] * @api public */ function SchemaType(path, options, instance) { this[schemaTypeSymbol] = true; this.path = path; this.instance = instance; this.validators = []; this.getters = this.constructor.hasOwnProperty('getters') ? this.constructor.getters.slice() : []; this.setters = []; options = options || {}; const defaultOptions = this.constructor.defaultOptions || {}; const defaultOptionsKeys = Object.keys(defaultOptions); for (const option of defaultOptionsKeys) { if (defaultOptions.hasOwnProperty(option) && !options.hasOwnProperty(option)) { options[option] = defaultOptions[option]; } } if (options.select == null) { delete options.select; } const Options = this.OptionsConstructor || SchemaTypeOptions; this.options = new Options(options); this._index = null; if (utils.hasUserDefinedProperty(this.options, 'immutable')) { this.$immutable = this.options.immutable; handleImmutable(this); } const keys = Object.keys(this.options); for (const prop of keys) { if (prop === 'cast') { this.castFunction(this.options[prop]); continue; } if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') { // { unique: true, index: true } if (prop === 'index' && this._index) { if (options.index === false) { const index = this._index; if (typeof index === 'object' && index != null) { if (index.unique) { throw new Error('Path "' + this.path + '" may not have `index` ' + 'set to false and `unique` set to true'); } if (index.sparse) { throw new Error('Path "' + this.path + '" may not have `index` ' + 'set to false and `sparse` set to true'); } } this._index = false; } continue; } const val = options[prop]; // Special case so we don't screw up array defaults, see gh-5780 if (prop === 'default') { this.default(val); continue; } const opts = Array.isArray(val) ? val : [val]; this[prop].apply(this, opts); } } Object.defineProperty(this, '$$context', { enumerable: false, configurable: false, writable: true, value: null }); } /*! * ignore */ SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; /** * Get/set the function used to cast arbitrary values to this type. * * ####Example: * * // Disallow `null` for numbers, and don't try to cast any values to * // numbers, so even strings like '123' will cause a CastError. * mongoose.Number.cast(function(v) { * assert.ok(v === undefined || typeof v === 'number'); * return v; * }); * * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed * @return {Function} * @static * @receiver SchemaType * @function cast * @api public */ SchemaType.cast = function cast(caster) { if (arguments.length === 0) { return this._cast; } if (caster === false) { caster = v => v; } this._cast = caster; return this._cast; }; /** * Get/set the function used to cast arbitrary values to this particular schematype instance. * Overrides `SchemaType.cast()`. * * ####Example: * * // Disallow `null` for numbers, and don't try to cast any values to * // numbers, so even strings like '123' will cause a CastError. * const number = new mongoose.Number('mypath', {}); * number.cast(function(v) { * assert.ok(v === undefined || typeof v === 'number'); * return v; * }); * * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed * @return {Function} * @static * @receiver SchemaType * @function cast * @api public */ SchemaType.prototype.castFunction = function castFunction(caster) { if (arguments.length === 0) { return this._castFunction; } if (caster === false) { caster = this.constructor._defaultCaster || (v => v); } this._castFunction = caster; return this._castFunction; }; /** * Sets a default option for this schema type. * * ####Example: * * // Make all strings be trimmed by default * mongoose.SchemaTypes.String.set('trim', true); * * @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...) * @param {*} value The value of the option you'd like to set. * @return {void} * @static * @receiver SchemaType * @function set * @api public */ SchemaType.set = function set(option, value) { if (!this.hasOwnProperty('defaultOptions')) { this.defaultOptions = Object.assign({}, this.defaultOptions); } this.defaultOptions[option] = value; }; /** * Attaches a getter for all instances of this schema type. * * ####Example: * * // Make all numbers round down * mongoose.Number.get(function(v) { return Math.floor(v); }); * * @param {Function} getter * @return {this} * @static * @receiver SchemaType * @function get * @api public */ SchemaType.get = function(getter) { this.getters = this.hasOwnProperty('getters') ? this.getters : []; this.getters.push(getter); }; /** * Sets a default value for this SchemaType. * * ####Example: * * const schema = new Schema({ n: { type: Number, default: 10 }) * const M = db.model('M', schema) * const m = new M; * console.log(m.n) // 10 * * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. * * ####Example: * * // values are cast: * const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) * const M = db.model('M', schema) * const m = new M; * console.log(m.aNumber) // 4.815162342 * * // default unique objects for Mixed types: * const schema = new Schema({ mixed: Schema.Types.Mixed }); * schema.path('mixed').default(function () { * return {}; * }); * * // if we don't use a function to return object literals for Mixed defaults, * // each document will receive a reference to the same object literal creating * // a "shared" object instance: * const schema = new Schema({ mixed: Schema.Types.Mixed }); * schema.path('mixed').default({}); * const M = db.model('M', schema); * const m1 = new M; * m1.mixed.added = 1; * console.log(m1.mixed); // { added: 1 } * const m2 = new M; * console.log(m2.mixed); // { added: 1 } * * @param {Function|any} val the default value * @return {defaultValue} * @api public */ SchemaType.prototype.default = function(val) { if (arguments.length === 1) { if (val === void 0) { this.defaultValue = void 0; return void 0; } if (val != null && val.instanceOfSchema) { throw new MongooseError('Cannot set default value of path `' + this.path + '` to a mongoose Schema instance.'); } this.defaultValue = val; return this.defaultValue; } else if (arguments.length > 1) { this.defaultValue = utils.args(arguments); } return this.defaultValue; }; /** * Declares the index options for this schematype. * * ####Example: * * const s = new Schema({ name: { type: String, index: true }) * const s = new Schema({ loc: { type: [Number], index: 'hashed' }) * const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) * const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) * const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) * s.path('my.path').index(true); * s.path('my.date').index({ expires: 60 }); * s.path('my.path').index({ unique: true, sparse: true }); * * ####NOTE: * * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) * by default. If `background` is set to `false`, MongoDB will not execute any * read/write operations you send until the index build. * Specify `background: false` to override Mongoose's default._ * * @param {Object|Boolean|String} options * @return {SchemaType} this * @api public */ SchemaType.prototype.index = function(options) { this._index = options; utils.expires(this._index); return this; }; /** * Declares an unique index. * * ####Example: * * const s = new Schema({ name: { type: String, unique: true }}); * s.path('name').index({ unique: true }); * * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ * * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.unique = function(bool) { if (this._index === false) { if (!bool) { return; } throw new Error('Path "' + this.path + '" may not have `index` set to ' + 'false and `unique` set to true'); } if (this._index == null || this._index === true) { this._index = {}; } else if (typeof this._index === 'string') { this._index = { type: this._index }; } this._index.unique = bool; return this; }; /** * Declares a full text index. * * ###Example: * * const s = new Schema({name : {type: String, text : true }) * s.path('name').index({text : true}); * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.text = function(bool) { if (this._index === false) { if (!bool) { return; } throw new Error('Path "' + this.path + '" may not have `index` set to ' + 'false and `text` set to true'); } if (this._index === null || this._index === undefined || typeof this._index === 'boolean') { this._index = {}; } else if (typeof this._index === 'string') { this._index = { type: this._index }; } this._index.text = bool; return this; }; /** * Declares a sparse index. * * ####Example: * * const s = new Schema({ name: { type: String, sparse: true } }); * s.path('name').index({ sparse: true }); * * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.sparse = function(bool) { if (this._index === false) { if (!bool) { return; } throw new Error('Path "' + this.path + '" may not have `index` set to ' + 'false and `sparse` set to true'); } if (this._index == null || typeof this._index === 'boolean') { this._index = {}; } else if (typeof this._index === 'string') { this._index = { type: this._index }; } this._index.sparse = bool; return this; }; /** * Defines this path as immutable. Mongoose prevents you from changing * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew). * * ####Example: * * const schema = new Schema({ * name: { type: String, immutable: true }, * age: Number * }); * const Model = mongoose.model('Test', schema); * * await Model.create({ name: 'test' }); * const doc = await Model.findOne(); * * doc.isNew; // false * doc.name = 'new name'; * doc.name; // 'test', because `name` is immutable * * Mongoose also prevents changing immutable properties using `updateOne()` * and `updateMany()` based on [strict mode](/docs/guide.html#strict). * * ####Example: * * // Mongoose will strip out the `name` update, because `name` is immutable * Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } }); * * // If `strict` is set to 'throw', Mongoose will throw an error if you * // update `name` * const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }). * then(() => null, err => err); * err.name; // StrictModeError * * // If `strict` is `false`, Mongoose allows updating `name` even though * // the property is immutable. * Model.updateOne({}, { name: 'test2' }, { strict: false }); * * @param {Boolean} bool * @return {SchemaType} this * @see isNew /docs/api.html#document_Document-isNew * @api public */ SchemaType.prototype.immutable = function(bool) { this.$immutable = bool; handleImmutable(this); return this; }; /** * Defines a custom function for transforming this path when converting a document to JSON. * * Mongoose calls this function with one parameter: the current `value` of the path. Mongoose * then uses the return value in the JSON output. * * ####Example: * * const schema = new Schema({ * date: { type: Date, transform: v => v.getFullYear() } * }); * const Model = mongoose.model('Test', schema); * * await Model.create({ date: new Date('2016-06-01') }); * const doc = await Model.findOne(); * * doc.date instanceof Date; // true * * doc.toJSON().date; // 2016 as a number * JSON.stringify(doc); // '{"_id":...,"date":2016}' * * @param {Function} fn * @return {SchemaType} this * @api public */ SchemaType.prototype.transform = function(fn) { this.options.transform = fn; return this; }; /** * Adds a setter to this schematype. * * ####Example: * * function capitalize (val) { * if (typeof val !== 'string') val = ''; * return val.charAt(0).toUpperCase() + val.substring(1); * } * * // defining within the schema * const s = new Schema({ name: { type: String, set: capitalize }}); * * // or with the SchemaType * const s = new Schema({ name: String }) * s.path('name').set(capitalize); * * Setters allow you to transform the data before it gets to the raw mongodb * document or query. * * Suppose you are implementing user registration for a website. Users provide * an email and password, which gets saved to mongodb. The email is a string * that you will want to normalize to lower case, in order to avoid one email * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. * * You can set up email lower case normalization easily via a Mongoose setter. * * function toLower(v) { * return v.toLowerCase(); * } * * const UserSchema = new Schema({ * email: { type: String, set: toLower } * }); * * const User = db.model('User', UserSchema); * * const user = new User({email: 'AVENUE@Q.COM'}); * console.log(user.email); // 'avenue@q.com' * * // or * const user = new User(); * user.email = 'Avenue@Q.com'; * console.log(user.email); // 'avenue@q.com' * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com' * * As you can see above, setters allow you to transform the data before it * stored in MongoDB, or before executing a query. * * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ * * new Schema({ email: { type: String, lowercase: true }}) * * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. * * function inspector (val, schematype) { * if (schematype.options.required) { * return schematype.path + ' is required'; * } else { * return val; * } * } * * const VirusSchema = new Schema({ * name: { type: String, required: true, set: inspector }, * taxonomy: { type: String, set: inspector } * }) * * const Virus = db.model('Virus', VirusSchema); * const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); * * console.log(v.name); // name is required * console.log(v.taxonomy); // Parvovirinae * * You can also use setters to modify other properties on the document. If * you're setting a property `name` on a document, the setter will run with * `this` as the document. Be careful, in mongoose 5 setters will also run * when querying by `name` with `this` as the query. * * ```javascript * const nameSchema = new Schema({ name: String, keywords: [String] }); * nameSchema.path('name').set(function(v) { * // Need to check if `this` is a document, because in mongoose 5 * // setters will also run on queries, in which case `this` will be a * // mongoose query object. * if (this instanceof Document && v != null) { * this.keywords = v.split(' '); * } * return v; * }); * ``` * * @param {Function} fn * @return {SchemaType} this * @api public */ SchemaType.prototype.set = function(fn) { if (typeof fn !== 'function') { throw new TypeError('A setter must be a function.'); } this.setters.push(fn); return this; }; /** * Adds a getter to this schematype. * * ####Example: * * function dob (val) { * if (!val) return val; * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); * } * * // defining within the schema * const s = new Schema({ born: { type: Date, get: dob }) * * // or by retreiving its SchemaType * const s = new Schema({ born: Date }) * s.path('born').get(dob) * * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. * * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: * * function obfuscate (cc) { * return '****-****-****-' + cc.slice(cc.length-4, cc.length); * } * * const AccountSchema = new Schema({ * creditCardNumber: { type: String, get: obfuscate } * }); * * const Account = db.model('Account', AccountSchema); * * Account.findById(id, function (err, found) { * console.log(found.creditCardNumber); // '****-****-****-1234' * }); * * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. * * function inspector (val, schematype) { * if (schematype.options.required) { * return schematype.path + ' is required'; * } else { * return schematype.path + ' is not'; * } * } * * const VirusSchema = new Schema({ * name: { type: String, required: true, get: inspector }, * taxonomy: { type: String, get: inspector } * }) * * const Virus = db.model('Virus', VirusSchema); * * Virus.findById(id, function (err, virus) { * console.log(virus.name); // name is required * console.log(virus.taxonomy); // taxonomy is not * }) * * @param {Function} fn * @return {SchemaType} this * @api public */ SchemaType.prototype.get = function(fn) { if (typeof fn !== 'function') { throw new TypeError('A getter must be a function.'); } this.getters.push(fn); return this; }; /** * Adds validator(s) for this document path. * * Validators always receive the value to validate as their first argument and * must return `Boolean`. Returning `false` or throwing an error means * validation failed. * * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. * * ####Examples: * * // make sure every value is equal to "something" * function validator (val) { * return val == 'something'; * } * new Schema({ name: { type: String, validate: validator }}); * * // with a custom error message * * const custom = [validator, 'Uh oh, {PATH} does not equal "something".'] * new Schema({ name: { type: String, validate: custom }}); * * // adding many validators at a time * * const many = [ * { validator: validator, msg: 'uh oh' } * , { validator: anotherValidator, msg: 'failed' } * ] * new Schema({ name: { type: String, validate: many }}); * * // or utilizing SchemaType methods directly: * * const schema = new Schema({ name: 'string' }); * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); * * ####Error message templates: * * From the examples above, you may have noticed that error messages support * basic templating. There are a few other template keywords besides `{PATH}` * and `{VALUE}` too. To find out more, details are available * [here](#error_messages_MongooseError.messages). * * If Mongoose's built-in error message templating isn't enough, Mongoose * supports setting the `message` property to a function. * * schema.path('name').validate({ * validator: function() { return v.length > 5; }, * // `errors['name']` will be "name must have length 5, got 'foo'" * message: function(props) { * return `${props.path} must have length 5, got '${props.value}'`; * } * }); * * To bypass Mongoose's error messages and just copy the error message that * the validator throws, do this: * * schema.path('name').validate({ * validator: function() { throw new Error('Oops!'); }, * // `errors['name']` will be "Oops!" * message: function(props) { return props.reason.message; } * }); * * ####Asynchronous validation: * * Mongoose supports validators that return a promise. A validator that returns * a promise is called an _async validator_. Async validators run in * parallel, and `validate()` will wait until all async validators have settled. * * schema.path('name').validate({ * validator: function (value) { * return new Promise(function (resolve, reject) { * resolve(false); // validation failed * }); * } * }); * * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. * * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). * * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. * * const conn = mongoose.createConnection(..); * conn.on('error', handleError); * * const Product = conn.model('Product', yourSchema); * const dvd = new Product(..); * dvd.save(); // emits error on the `conn` above * * If you want to handle these errors at the Model level, add an `error` * listener to your Model as shown below. * * // registering an error listener on the Model lets us handle errors more locally * Product.on('error', handleError); * * @param {RegExp|Function|Object} obj validator function, or hash describing options * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails. * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string * @param {String} [type] optional validator type * @return {SchemaType} this * @api public */ SchemaType.prototype.validate = function(obj, message, type) { if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { let properties; if (typeof message === 'function') { properties = { validator: obj, message: message }; properties.type = type || 'user defined'; } else if (message instanceof Object && !type) { properties = utils.clone(message); if (!properties.message) { properties.message = properties.msg; } properties.validator = obj; properties.type = properties.type || 'user defined'; } else { if (message == null) { message = MongooseError.messages.general.default; } if (!type) { type = 'user defined'; } properties = { message: message, type: type, validator: obj }; } if (properties.isAsync) { handleIsAsync(); } this.validators.push(properties); return this; } let i; let length; let arg; for (i = 0, length = arguments.length; i < length; i++) { arg = arguments[i]; if (!utils.isPOJO(arg)) { const msg = 'Invalid validator. Received (' + typeof arg + ') ' + arg + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; throw new Error(msg); } this.validate(arg.validator, arg); } return this; }; /*! * ignore */ const handleIsAsync = util.deprecate(function handleIsAsync() {}, 'Mongoose: the `isAsync` option for custom validators is deprecated. Make ' + 'your async validators return a promise instead: ' + 'https://mongoosejs.com/docs/validation.html#async-custom-validators'); /** * Adds a required validator to this SchemaType. The validator gets added * to the front of this SchemaType's validators array using `unshift()`. * * ####Example: * * const s = new Schema({ born: { type: Date, required: true }) * * // or with custom error message * * const s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) * * // or with a function * * const s = new Schema({ * userId: ObjectId, * username: { * type: String, * required: function() { return this.userId != null; } * } * }) * * // or with a function and a custom message * const s = new Schema({ * userId: ObjectId, * username: { * type: String, * required: [ * function() { return this.userId != null; }, * 'username is required if id is specified' * ] * } * }) * * // or through the path API * * s.path('name').required(true); * * // with custom error messaging * * s.path('name').required(true, 'grrr :( '); * * // or make a path conditionally required based on a function * const isOver18 = function() { return this.age >= 18; }; * s.path('voterRegistrationId').required(isOver18); * * The required validator uses the SchemaType's `checkRequired` function to * determine whether a given value satisfies the required validator. By default, * a value satisfies the required validator if `val != null` (that is, if * the value is not null nor undefined). However, most built-in mongoose schema * types override the default `checkRequired` function: * * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. * @param {String} [message] optional custom error message * @return {SchemaType} this * @see Customized Error Messages #error_messages_MongooseError-messages * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired * @api public */ SchemaType.prototype.required = function(required, message) { let customOptions = {}; if (arguments.length > 0 && required == null) { this.validators = this.validators.filter(function(v) { return v.validator !== this.requiredValidator; }, this); this.isRequired = false; delete this.originalRequiredValue; return this; } if (typeof required === 'object') { customOptions = required; message = customOptions.message || message; required = required.isRequired; } if (required === false) { this.validators = this.validators.filter(function(v) { return v.validator !== this.requiredValidator; }, this); this.isRequired = false; delete this.originalRequiredValue; return this; } const _this = this; this.isRequired = true; this.requiredValidator = function(v) { const cachedRequired = get(this, '$__.cachedRequired'); // no validation when this path wasn't selected in the query. if (cachedRequired != null && !this[documentIsSelected](_this.path) && !this[documentIsModified](_this.path)) { return true; } // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we // don't call required functions multiple times in one validate call // See gh-6801 if (cachedRequired != null && _this.path in cachedRequired) { const res = cachedRequired[_this.path] ? _this.checkRequired(v, this) : true; delete cachedRequired[_this.path]; return res; } else if (typeof required === 'function') { return required.apply(this) ? _this.checkRequired(v, this) : true; } return _this.checkRequired(v, this); }; this.originalRequiredValue = required; if (typeof required === 'string') { message = required; required = undefined; } const msg = message || MongooseError.messages.general.required; this.validators.unshift(Object.assign({}, customOptions, { validator: this.requiredValidator, message: msg, type: 'required' })); return this; }; /** * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) * looks at to determine the foreign collection it should query. * * ####Example: * const userSchema = new Schema({ name: String }); * const User = mongoose.model('User', userSchema); * * const postSchema = new Schema({ user: mongoose.ObjectId }); * postSchema.path('user').ref('User'); // Can set ref to a model name * postSchema.path('user').ref(User); // Or a model class * postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name * postSchema.path('user').ref(() => User); // Or a function that returns the model class * * // Or you can just declare the `ref` inline in your schema * const postSchema2 = new Schema({ * user: { type: mongoose.ObjectId, ref: User } * }); * * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model. * @return {SchemaType} this * @api public */ SchemaType.prototype.ref = function(ref) { this.options.ref = ref; return this; }; /** * Gets the default value * * @param {Object} scope the scope which callback are executed * @param {Boolean} init * @api private */ SchemaType.prototype.getDefault = function(scope, init) { let ret = typeof this.defaultValue === 'function' ? this.defaultValue.call(scope) : this.defaultValue; if (ret !== null && ret !== undefined) { if (typeof ret === 'object' && (!this.options || !this.options.shared)) { ret = utils.clone(ret); } const casted = this.applySetters(ret, scope, init); if (casted && casted.$isSingleNested) { casted.$__parent = scope; } return casted; } return ret; }; /*! * Applies setters without casting * * @api private */ SchemaType.prototype._applySetters = function(value, scope, init, priorVal) { let v = value; const setters = this.setters; const caster = this.caster; for (const setter of utils.clone(setters).reverse()) { v = setter.call(scope, v, this); } if (caster && !caster.$isMongooseArray && Array.isArray(v) && caster.setters) { const newVal = []; for (let i = 0; i < v.length; ++i) { const value = v[i]; try { newVal.push(caster.applySetters(value, scope, init, priorVal)); } catch (err) { if (err instanceof MongooseError.CastError) { err.$originalErrorPath = err.path; err.path = err.path + '.' + i; } throw err; } } v = newVal; } return v; }; /*! * ignore */ SchemaType.prototype._castNullish = function _castNullish(v) { return v; }; /** * Applies setters * * @param {Object} value * @param {Object} scope * @param {Boolean} init * @api private */ SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { let v = this._applySetters(value, scope, init, priorVal, options); if (v == null) { return this._castNullish(v); } // do not cast until all setters are applied #665 v = this.cast(v, scope, init, priorVal, options); return v; }; /** * Applies getters to a value * * @param {Object} value * @param {Object} scope * @api private */ SchemaType.prototype.applyGetters = function(value, scope) { let v = value; const getters = this.getters; const len = getters.length; if (len === 0) { return v; } for (let i = 0; i < len; ++i) { v = getters[i].call(scope, v, this); } return v; }; /** * Sets default `select()` behavior for this path. * * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. * * ####Example: * * T = db.model('T', new Schema({ x: { type: String, select: true }})); * T.find(..); // field x will always be selected .. * // .. unless overridden; * T.find().select('-x').exec(callback); * * @param {Boolean} val * @return {SchemaType} this * @api public */ SchemaType.prototype.select = function select(val) { this.selected = !!val; return this; }; /** * Performs a validation of `value` using the validators declared for this SchemaType. * * @param {any} value * @param {Function} callback * @param {Object} scope * @api private */ SchemaType.prototype.doValidate = function(value, fn, scope, options) { let err = false; const path = this.path; // Avoid non-object `validators` const validators = this.validators. filter(v => v != null && typeof v === 'object'); let count = validators.length; if (!count) { return fn(null); } const _this = this; validators.forEach(function(v) { if (err) { return; } const validator = v.validator; let ok; const validatorProperties = utils.clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.value = value; if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); return; } if (typeof validator !== 'function') { return; } if (value === undefined && validator !== _this.requiredValidator) { validate(true, validatorProperties); return; } if (validatorProperties.isAsync) { asyncValidate(validator, scope, value, validatorProperties, validate); return; } try { if (validatorProperties.propsParameter) { ok = validator.call(scope, value, validatorProperties); } else { ok = validator.call(scope, value); } } catch (error) { ok = false; validatorProperties.reason = error; if (error.message) { validatorProperties.message = error.message; } } if (ok != null && typeof ok.then === 'function') { ok.then( function(ok) { validate(ok, validatorProperties); }, function(error) { validatorProperties.reason = error; validatorProperties.message = error.message; ok = false; validate(ok, validatorProperties); }); } else { validate(ok, validatorProperties); } }); function validate(ok, validatorProperties) { if (err) { return; } if (ok === undefined || ok) { if (--count <= 0) { immediate(function() { fn(null); }); } } else { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; immediate(function() { fn(err); }); } } }; /*! * Handle async validators */ function asyncValidate(validator, scope, value, props, cb) { let called = false; const returnVal = validator.call(scope, value, function(ok, customMsg) { if (called) { return; } called = true; if (customMsg) { props.message = customMsg; } cb(ok, props); }); if (typeof returnVal === 'boolean') { called = true; cb(returnVal, props); } else if (returnVal && typeof returnVal.then === 'function') { // Promise returnVal.then( function(ok) { if (called) { return; } called = true; cb(ok, props); }, function(error) { if (called) { return; } called = true; props.reason = error; props.message = error.message; cb(false, props); }); } } /** * Performs a validation of `value` using the validators declared for this SchemaType. * * ####Note: * * This method ignores the asynchronous validators. * * @param {any} value * @param {Object} scope * @return {MongooseError|undefined} * @api private */ SchemaType.prototype.doValidateSync = function(value, scope, options) { const path = this.path; const count = this.validators.length; if (!count) { return null; } let validators = this.validators; if (value === void 0) { if (this.validators.length > 0 && this.validators[0].type === 'required') { validators = [this.validators[0]]; } else { return null; } } let err = null; validators.forEach(function(v) { if (err) { return; } if (v == null || typeof v !== 'object') { return; } const validator = v.validator; const validatorProperties = utils.clone(v); validatorProperties.path = options && options.path ? options.path : path; validatorProperties.value = value; let ok; // Skip any explicit async validators. Validators that return a promise // will still run, but won't trigger any errors. if (validator.isAsync) { return; } if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); return; } if (typeof validator !== 'function') { return; } try { if (validatorProperties.propsParameter) { ok = validator.call(scope, value, validatorProperties); } else { ok = validator.call(scope, value); } } catch (error) { ok = false; validatorProperties.reason = error; } // Skip any validators that return a promise, we can't handle those // synchronously if (ok != null && typeof ok.then === 'function') { return; } validate(ok, validatorProperties); }); return err; function validate(ok, validatorProperties) { if (err) { return; } if (ok !== undefined && !ok) { const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err[validatorErrorSymbol] = true; } } }; /** * Determines if value is a valid Reference. * * @param {SchemaType} self * @param {Object} value * @param {Document} doc * @param {Boolean} init * @return {Boolean} * @api private */ SchemaType._isRef = function(self, value, doc, init) { // fast path let ref = init && self.options && (self.options.ref || self.options.refPath); if (!ref && doc && doc.$__ != null) { // checks for // - this populated with adhoc model and no ref was set in schema OR // - setting / pushing values after population const path = doc.$__fullPath(self.path); const owner = doc.ownerDocument ? doc.ownerDocument() : doc; ref = owner.populated(path) || doc.populated(self.path); } if (ref) { if (value == null) { return true; } if (!Buffer.isBuffer(value) && // buffers are objects too value._bsontype !== 'Binary' // raw binary value from the db && utils.isObject(value) // might have deselected _id in population query ) { return true; } } return false; }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } /*! * ignore */ function handleArray(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { return _this.castForQuery(m); }); } /*! * Just like handleArray, except also allows `[]` because surprisingly * `$in: [1, []]` works fine */ function handle$in(val) { const _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { if (Array.isArray(m) && m.length === 0) { return m; } return _this.castForQuery(m); }); } /*! * ignore */ SchemaType.prototype.$conditionalHandlers = { $all: handleArray, $eq: handleSingle, $in: handle$in, $ne: handleSingle, $nin: handle$in, $exists: $exists, $type: $type }; /*! * Wraps `castForQuery` to handle context */ SchemaType.prototype.castForQueryWrapper = function(params) { this.$$context = params.context; if ('$conditional' in params) { const ret = this.castForQuery(params.$conditional, params.val); this.$$context = null; return ret; } if (params.$skipQueryCastForUpdate || params.$applySetters) { const ret = this._castForQuery(params.val); this.$$context = null; return ret; } const ret = this.castForQuery(params.val); this.$$context = null; return ret; }; /** * Cast the given value with the given optional query operator. * * @param {String} [$conditional] query operator, like `$eq` or `$in` * @param {any} val * @api private */ SchemaType.prototype.castForQuery = function($conditional, val) { let handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional); } return handler.call(this, val); } val = $conditional; return this._castForQuery(val); }; /*! * Internal switch for runSetters * * @api private */ SchemaType.prototype._castForQuery = function(val) { return this.applySetters(val, this.$$context); }; /** * Override the function the required validator uses to check whether a value * passes the `required` check. Override this on the individual SchemaType. * * ####Example: * * // Use this to allow empty strings to pass the `required` validator * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); * * @param {Function} fn * @return {Function} * @static * @receiver SchemaType * @function checkRequired * @api public */ SchemaType.checkRequired = function(fn) { if (arguments.length > 0) { this._checkRequired = fn; } return this._checkRequired; }; /** * Default check for if this path satisfies the `required` validator. * * @param {any} val * @api private */ SchemaType.prototype.checkRequired = function(val) { return val != null; }; /*! * ignore */ SchemaType.prototype.clone = function() { const options = Object.assign({}, this.options); const schematype = new this.constructor(this.path, options, this.instance); schematype.validators = this.validators.slice(); if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator; if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue; if (this.$immutable !== undefined && this.options.immutable === undefined) { schematype.$immutable = this.$immutable; handleImmutable(schematype); } if (this._index !== undefined) schematype._index = this._index; if (this.selected !== undefined) schematype.selected = this.selected; if (this.isRequired !== undefined) schematype.isRequired = this.isRequired; if (this.originalRequiredValue !== undefined) schematype.originalRequiredValue = this.originalRequiredValue; schematype.getters = this.getters.slice(); schematype.setters = this.setters.slice(); return schematype; }; /*! * Module exports. */ module.exports = exports = SchemaType; exports.CastError = CastError; exports.ValidatorError = ValidatorError; }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":255,"./error/index":278,"./helpers/get":303,"./helpers/immediate":305,"./helpers/schematype/handleImmutable":324,"./helpers/symbols":326,"./options/SchemaTypeOptions":342,"./schema/operators/exists":362,"./schema/operators/type":366,"./utils":381,"util":414}],370:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const utils = require('./utils'); /*! * StateMachine represents a minimal `interface` for the * constructors it builds via StateMachine.ctor(...). * * @api private */ const StateMachine = module.exports = exports = function StateMachine() { }; /*! * StateMachine.ctor('state1', 'state2', ...) * A factory method for subclassing StateMachine. * The arguments are a list of states. For each state, * the constructor's prototype gets state transition * methods named after each state. These transition methods * place their path argument into the given state. * * @param {String} state * @param {String} [state] * @return {Function} subclass constructor * @private */ StateMachine.ctor = function() { const states = utils.args(arguments); const ctor = function() { StateMachine.apply(this, arguments); this.paths = {}; this.states = {}; this.stateNames = states; let i = states.length, state; while (i--) { state = states[i]; this.states[state] = {}; } }; ctor.prototype = new StateMachine(); states.forEach(function(state) { // Changes the `path`'s state to `state`. ctor.prototype[state] = function(path) { this._changeState(path, state); }; }); return ctor; }; /*! * This function is wrapped by the state change functions: * * - `require(path)` * - `modify(path)` * - `init(path)` * * @api private */ StateMachine.prototype._changeState = function _changeState(path, nextState) { const prevBucket = this.states[this.paths[path]]; if (prevBucket) delete prevBucket[path]; this.paths[path] = nextState; this.states[nextState][path] = true; }; /*! * ignore */ StateMachine.prototype.clear = function clear(state) { const keys = Object.keys(this.states[state]); let i = keys.length; let path; while (i--) { path = keys[i]; delete this.states[state][path]; delete this.paths[path]; } }; /*! * Checks to see if at least one path is in the states passed in via `arguments` * e.g., this.some('required', 'inited') * * @param {String} state that we want to check for. * @private */ StateMachine.prototype.some = function some() { const _this = this; const what = arguments.length ? arguments : this.stateNames; return Array.prototype.some.call(what, function(state) { return Object.keys(_this.states[state]).length; }); }; /*! * This function builds the functions that get assigned to `forEach` and `map`, * since both of those methods share a lot of the same logic. * * @param {String} iterMethod is either 'forEach' or 'map' * @return {Function} * @api private */ StateMachine.prototype._iter = function _iter(iterMethod) { return function() { const numArgs = arguments.length; let states = utils.args(arguments, 0, numArgs - 1); const callback = arguments[numArgs - 1]; if (!states.length) states = this.stateNames; const _this = this; const paths = states.reduce(function(paths, state) { return paths.concat(Object.keys(_this.states[state])); }, []); return paths[iterMethod](function(path, i, paths) { return callback(path, i, paths); }); }; }; /*! * Iterates over the paths that belong to one of the parameter states. * * The function profile can look like: * this.forEach(state1, fn); // iterates over all paths in state1 * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 * this.forEach(fn); // iterates over all paths in all states * * @param {String} [state] * @param {String} [state] * @param {Function} callback * @private */ StateMachine.prototype.forEach = function forEach() { this.forEach = this._iter('forEach'); return this.forEach.apply(this, arguments); }; /*! * Maps over the paths that belong to one of the parameter states. * * The function profile can look like: * this.forEach(state1, fn); // iterates over all paths in state1 * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 * this.forEach(fn); // iterates over all paths in all states * * @param {String} [state] * @param {String} [state] * @param {Function} callback * @return {Array} * @private */ StateMachine.prototype.map = function map() { this.map = this._iter('map'); return this.map.apply(this, arguments); }; },{"./utils":381}],371:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const CoreMongooseArray = require('./core_array'); const Document = require('../document'); const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; const _basePush = Array.prototype.push; /** * Mongoose Array constructor. * * ####NOTE: * * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ * * @param {Array} values * @param {String} path * @param {Document} doc parent document * @api private * @inherits Array * @see http://bit.ly/f6CnZU */ function MongooseArray(values, path, doc, schematype) { const arr = new CoreMongooseArray(); arr[arrayAtomicsSymbol] = {}; if (Array.isArray(values)) { const len = values.length; for (let i = 0; i < len; ++i) { _basePush.call(arr, values[i]); } if (values[arrayAtomicsSymbol] != null) { arr[arrayAtomicsSymbol] = values[arrayAtomicsSymbol]; } } arr[arrayPathSymbol] = path; arr[arraySchemaSymbol] = void 0; // Because doc comes from the context of another function, doc === global // can happen if there was a null somewhere up the chain (see #3020) // RB Jun 17, 2015 updated to check for presence of expected paths instead // to make more proof against unusual node environments if (doc && doc instanceof Document) { arr[arrayParentSymbol] = doc; arr[arraySchemaSymbol] = schematype || doc.schema.path(path); } return arr; } /*! * Module exports. */ module.exports = exports = MongooseArray; },{"../document":268,"../helpers/symbols":326,"./core_array":373}],372:[function(require,module,exports){ /*! * Module dependencies. */ 'use strict'; const Binary = require('../driver').get().Binary; const utils = require('../utils'); const Buffer = require('safe-buffer').Buffer; /** * Mongoose Buffer constructor. * * Values always have to be passed to the constructor to initialize. * * @param {Buffer} value * @param {String} encode * @param {Number} offset * @api private * @inherits Buffer * @see http://bit.ly/f6CnZU */ function MongooseBuffer(value, encode, offset) { const length = arguments.length; let val; if (length === 0 || arguments[0] === null || arguments[0] === undefined) { val = 0; } else { val = value; } let encoding; let path; let doc; if (Array.isArray(encode)) { // internal casting path = encode[0]; doc = encode[1]; } else { encoding = encode; } let buf; if (typeof val === 'number' || val instanceof Number) { buf = Buffer.alloc(val); } else { // string, array or object { type: 'Buffer', data: [...] } buf = Buffer.from(val, encoding, offset); } utils.decorate(buf, MongooseBuffer.mixin); buf.isMongooseBuffer = true; // make sure these internal props don't show up in Object.keys() buf[MongooseBuffer.pathSymbol] = path; buf[parentSymbol] = doc; buf._subtype = 0; return buf; } const pathSymbol = Symbol.for('mongoose#Buffer#_path'); const parentSymbol = Symbol.for('mongoose#Buffer#_parent'); MongooseBuffer.pathSymbol = pathSymbol; /*! * Inherit from Buffer. */ MongooseBuffer.mixin = { /** * Default subtype for the Binary representing this Buffer * * @api private * @property _subtype * @receiver MongooseBuffer */ _subtype: undefined, /** * Marks this buffer as modified. * * @api private * @method _markModified * @receiver MongooseBuffer */ _markModified: function() { const parent = this[parentSymbol]; if (parent) { parent.markModified(this[MongooseBuffer.pathSymbol]); } return this; }, /** * Writes the buffer. * * @api public * @method write * @receiver MongooseBuffer */ write: function() { const written = Buffer.prototype.write.apply(this, arguments); if (written > 0) { this._markModified(); } return written; }, /** * Copies the buffer. * * ####Note: * * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. * * @return {Number} The number of bytes copied. * @param {Buffer} target * @method copy * @receiver MongooseBuffer */ copy: function(target) { const ret = Buffer.prototype.copy.apply(this, arguments); if (target && target.isMongooseBuffer) { target._markModified(); } return ret; } }; /*! * Compile other Buffer methods marking this buffer as modified. */ ( // node < 0.5 ('writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + 'writeFloat writeDouble fill ' + 'utf8Write binaryWrite asciiWrite set ' + // node >= 0.5 'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + 'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + 'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE') ).split(' ').forEach(function(method) { if (!Buffer.prototype[method]) { return; } MongooseBuffer.mixin[method] = function() { const ret = Buffer.prototype[method].apply(this, arguments); this._markModified(); return ret; }; }); /** * Converts this buffer to its Binary type representation. * * ####SubTypes: * * const bson = require('bson') * bson.BSON_BINARY_SUBTYPE_DEFAULT * bson.BSON_BINARY_SUBTYPE_FUNCTION * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY * bson.BSON_BINARY_SUBTYPE_UUID * bson.BSON_BINARY_SUBTYPE_MD5 * bson.BSON_BINARY_SUBTYPE_USER_DEFINED * * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); * * @see http://bsonspec.org/#/specification * @param {Hex} [subtype] * @return {Binary} * @api public * @method toObject * @receiver MongooseBuffer */ MongooseBuffer.mixin.toObject = function(options) { const subtype = typeof options === 'number' ? options : (this._subtype || 0); return new Binary(Buffer.from(this), subtype); }; /** * Converts this buffer for storage in MongoDB, including subtype * * @return {Binary} * @api public * @method toBSON * @receiver MongooseBuffer */ MongooseBuffer.mixin.toBSON = function() { return new Binary(this, this._subtype || 0); }; /** * Determines if this buffer is equals to `other` buffer * * @param {Buffer} other * @return {Boolean} * @method equals * @receiver MongooseBuffer */ MongooseBuffer.mixin.equals = function(other) { if (!Buffer.isBuffer(other)) { return false; } if (this.length !== other.length) { return false; } for (let i = 0; i < this.length; ++i) { if (this[i] !== other[i]) { return false; } } return true; }; /** * Sets the subtype option and marks the buffer modified. * * ####SubTypes: * * const bson = require('bson') * bson.BSON_BINARY_SUBTYPE_DEFAULT * bson.BSON_BINARY_SUBTYPE_FUNCTION * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY * bson.BSON_BINARY_SUBTYPE_UUID * bson.BSON_BINARY_SUBTYPE_MD5 * bson.BSON_BINARY_SUBTYPE_USER_DEFINED * * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); * * @see http://bsonspec.org/#/specification * @param {Hex} subtype * @api public * @method subtype * @receiver MongooseBuffer */ MongooseBuffer.mixin.subtype = function(subtype) { if (typeof subtype !== 'number') { throw new TypeError('Invalid subtype. Expected a number'); } if (this._subtype !== subtype) { this._markModified(); } this._subtype = subtype; }; /*! * Module exports. */ MongooseBuffer.Binary = Binary; module.exports = MongooseBuffer; },{"../driver":270,"../utils":381,"safe-buffer":401}],373:[function(require,module,exports){ (function (Buffer){ 'use strict'; const Document = require('../document'); const EmbeddedDocument = require('./embedded'); const MongooseError = require('../error/mongooseError'); const ObjectId = require('./objectid'); const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths'); const get = require('../helpers/get'); const internalToObjectOptions = require('../options').internalToObjectOptions; const utils = require('../utils'); const util = require('util'); const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; const slicedSymbol = Symbol('mongoose#Array#sliced'); const _basePush = Array.prototype.push; const validatorsSymbol = Symbol('mongoose#MongooseCoreArray#validators'); /*! * ignore */ class CoreMongooseArray extends Array { get isMongooseArray() { return true; } get validators() { return this[validatorsSymbol]; } set validators(v) { this[validatorsSymbol] = v; } /** * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. * * If no atomics exist, we return all array values after conversion. * * @return {Array} * @method $__getAtomics * @memberOf MongooseArray * @instance * @api private */ $__getAtomics() { const ret = []; const keys = Object.keys(this[arrayAtomicsSymbol] || {}); let i = keys.length; const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); if (i === 0) { ret[0] = ['$set', this.toObject(opts)]; return ret; } while (i--) { const op = keys[i]; let val = this[arrayAtomicsSymbol][op]; // the atomic values which are arrays are not MongooseArrays. we // need to convert their elements as if they were MongooseArrays // to handle populated arrays versus DocumentArrays properly. if (utils.isMongooseObject(val)) { val = val.toObject(opts); } else if (Array.isArray(val)) { val = this.toObject.call(val, opts); } else if (val != null && Array.isArray(val.$each)) { val.$each = this.toObject.call(val.$each, opts); } else if (val != null && typeof val.valueOf === 'function') { val = val.valueOf(); } if (op === '$addToSet') { val = { $each: val }; } ret.push([op, val]); } return ret; } /*! * ignore */ $atomics() { return this[arrayAtomicsSymbol]; } /*! * ignore */ $parent() { return this[arrayParentSymbol]; } /*! * ignore */ $path() { return this[arrayPathSymbol]; } /** * Atomically shifts the array at most one time per document `save()`. * * ####NOTE: * * _Calling this multiple times on an array before saving sends the same command as calling it once._ * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ * * doc.array = [1,2,3]; * * const shifted = doc.array.$shift(); * console.log(shifted); // 1 * console.log(doc.array); // [2,3] * * // no affect * shifted = doc.array.$shift(); * console.log(doc.array); // [2,3] * * doc.save(function (err) { * if (err) return handleError(err); * * // we saved, now $shift works again * shifted = doc.array.$shift(); * console.log(shifted ); // 2 * console.log(doc.array); // [3] * }) * * @api public * @memberOf MongooseArray * @instance * @method $shift * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop */ $shift() { this._registerAtomic('$pop', -1); this._markModified(); // only allow shifting once if (this._shifted) { return; } this._shifted = true; return [].shift.call(this); } /** * Pops the array atomically at most one time per document `save()`. * * #### NOTE: * * _Calling this mulitple times on an array before saving sends the same command as calling it once._ * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ * * doc.array = [1,2,3]; * * const popped = doc.array.$pop(); * console.log(popped); // 3 * console.log(doc.array); // [1,2] * * // no affect * popped = doc.array.$pop(); * console.log(doc.array); // [1,2] * * doc.save(function (err) { * if (err) return handleError(err); * * // we saved, now $pop works again * popped = doc.array.$pop(); * console.log(popped); // 2 * console.log(doc.array); // [1] * }) * * @api public * @method $pop * @memberOf MongooseArray * @instance * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop * @method $pop * @memberOf MongooseArray */ $pop() { this._registerAtomic('$pop', 1); this._markModified(); // only allow popping once if (this._popped) { return; } this._popped = true; return [].pop.call(this); } /*! * ignore */ $schema() { return this[arraySchemaSymbol]; } /** * Casts a member based on this arrays schema. * * @param {any} value * @return value the casted value * @method _cast * @api private * @memberOf MongooseArray */ _cast(value) { let populated = false; let Model; if (this[arrayParentSymbol]) { populated = this[arrayParentSymbol].populated(this[arrayPathSymbol], true); } if (populated && value !== null && value !== undefined) { // cast to the populated Models schema Model = populated.options[populateModelSymbol]; // only objects are permitted so we can safely assume that // non-objects are to be interpreted as _id if (Buffer.isBuffer(value) || value instanceof ObjectId || !utils.isObject(value)) { value = { _id: value }; } // gh-2399 // we should cast model only when it's not a discriminator const isDisc = value.schema && value.schema.discriminatorMapping && value.schema.discriminatorMapping.key !== undefined; if (!isDisc) { value = new Model(value); } return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], true); } return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], false); } /** * Internal helper for .map() * * @api private * @return {Number} * @method _mapCast * @memberOf MongooseArray */ _mapCast(val, index) { return this._cast(val, this.length + index); } /** * Marks this array as modified. * * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) * * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array * @param {String} embeddedPath the path which changed in the embeddedDoc * @method _markModified * @api private * @memberOf MongooseArray */ _markModified(elem, embeddedPath) { const parent = this[arrayParentSymbol]; let dirtyPath; if (parent) { dirtyPath = this[arrayPathSymbol]; if (arguments.length) { if (embeddedPath != null) { // an embedded doc bubbled up the change dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath; } else { // directly set an index dirtyPath = dirtyPath + '.' + elem; } } if (dirtyPath != null && dirtyPath.endsWith('.$')) { return this; } parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); } return this; } /** * Register an atomic operation with the parent. * * @param {Array} op operation * @param {any} val * @method _registerAtomic * @api private * @memberOf MongooseArray */ _registerAtomic(op, val) { if (this[slicedSymbol]) { return; } if (op === '$set') { // $set takes precedence over all other ops. // mark entire array modified. this[arrayAtomicsSymbol] = { $set: val }; cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]); this._markModified(); return this; } const atomics = this[arrayAtomicsSymbol]; // reset pop/shift after save if (op === '$pop' && !('$pop' in atomics)) { const _this = this; this[arrayParentSymbol].once('save', function() { _this._popped = _this._shifted = null; }); } // check for impossible $atomic combos (Mongo denies more than one // $atomic op on a single path if (this[arrayAtomicsSymbol].$set || Object.keys(atomics).length && !(op in atomics)) { // a different op was previously registered. // save the entire thing. this[arrayAtomicsSymbol] = { $set: this }; return this; } let selector; if (op === '$pullAll' || op === '$addToSet') { atomics[op] || (atomics[op] = []); atomics[op] = atomics[op].concat(val); } else if (op === '$pullDocs') { const pullOp = atomics['$pull'] || (atomics['$pull'] = {}); if (val[0] instanceof EmbeddedDocument) { selector = pullOp['$or'] || (pullOp['$or'] = []); Array.prototype.push.apply(selector, val.map(function(v) { return v.toObject({ transform: false, virtuals: false }); })); } else { selector = pullOp['_id'] || (pullOp['_id'] = { $in: [] }); selector['$in'] = selector['$in'].concat(val); } } else if (op === '$push') { atomics.$push = atomics.$push || { $each: [] }; if (val != null && utils.hasUserDefinedProperty(val, '$each')) { atomics.$push = val; } else { atomics.$push.$each = atomics.$push.$each.concat(val); } } else { atomics[op] = val; } return this; } /** * Adds values to the array if not already present. * * ####Example: * * console.log(doc.array) // [2,3,4] * const added = doc.array.addToSet(4,5); * console.log(doc.array) // [2,3,4,5] * console.log(added) // [5] * * @param {any} [args...] * @return {Array} the values that were added * @memberOf MongooseArray * @api public * @method addToSet */ addToSet() { _checkManualPopulation(this, arguments); let values = [].map.call(arguments, this._mapCast, this); values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); const added = []; let type = ''; if (values[0] instanceof EmbeddedDocument) { type = 'doc'; } else if (values[0] instanceof Date) { type = 'date'; } values.forEach(function(v) { let found; const val = +v; switch (type) { case 'doc': found = this.some(function(doc) { return doc.equals(v); }); break; case 'date': found = this.some(function(d) { return +d === val; }); break; default: found = ~this.indexOf(v); } if (!found) { [].push.call(this, v); this._registerAtomic('$addToSet', v); this._markModified(); [].push.call(added, v); } }, this); return added; } /** * Returns the number of pending atomic operations to send to the db for this array. * * @api private * @return {Number} * @method hasAtomics * @memberOf MongooseArray */ hasAtomics() { if (!utils.isPOJO(this[arrayAtomicsSymbol])) { return 0; } return Object.keys(this[arrayAtomicsSymbol]).length; } /** * Return whether or not the `obj` is included in the array. * * @param {Object} obj the item to check * @return {Boolean} * @api public * @method includes * @memberOf MongooseArray */ includes(obj, fromIndex) { const ret = this.indexOf(obj, fromIndex); return ret !== -1; } /** * Return the index of `obj` or `-1` if not found. * * @param {Object} obj the item to look for * @return {Number} * @api public * @method indexOf * @memberOf MongooseArray */ indexOf(obj, fromIndex) { if (obj instanceof ObjectId) { obj = obj.toString(); } fromIndex = fromIndex == null ? 0 : fromIndex; const len = this.length; for (let i = fromIndex; i < len; ++i) { if (obj == this[i]) { return i; } } return -1; } /** * Helper for console.log * * @api public * @method inspect * @memberOf MongooseArray */ inspect() { return JSON.stringify(this); } /** * Pushes items to the array non-atomically. * * ####NOTE: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @param {any} [args...] * @api public * @method nonAtomicPush * @memberOf MongooseArray */ nonAtomicPush() { const values = [].map.call(arguments, this._mapCast, this); const ret = [].push.apply(this, values); this._registerAtomic('$set', this); this._markModified(); return ret; } /** * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. * * ####Note: * * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @see MongooseArray#$pop #types_array_MongooseArray-%24pop * @api public * @method pop * @memberOf MongooseArray */ pop() { const ret = [].pop.call(this); this._registerAtomic('$set', this); this._markModified(); return ret; } /** * Pulls items from the array atomically. Equality is determined by casting * the provided value to an embedded document and comparing using * [the `Document.equals()` function.](./api.html#document_Document-equals) * * ####Examples: * * doc.array.pull(ObjectId) * doc.array.pull({ _id: 'someId' }) * doc.array.pull(36) * doc.array.pull('tag 1', 'tag 2') * * To remove a document from a subdocument array we may pass an object with a matching `_id`. * * doc.subdocs.push({ _id: 4815162342 }) * doc.subdocs.pull({ _id: 4815162342 }) // removed * * Or we may passing the _id directly and let mongoose take care of it. * * doc.subdocs.push({ _id: 4815162342 }) * doc.subdocs.pull(4815162342); // works * * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. * * @param {any} [args...] * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull * @api public * @method pull * @memberOf MongooseArray */ pull() { const values = [].map.call(arguments, this._cast, this); const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); let i = cur.length; let mem; while (i--) { mem = cur[i]; if (mem instanceof Document) { const some = values.some(function(v) { return mem.equals(v); }); if (some) { [].splice.call(cur, i, 1); } } else if (~cur.indexOf.call(values, mem)) { [].splice.call(cur, i, 1); } } if (values[0] instanceof EmbeddedDocument) { this._registerAtomic('$pullDocs', values.map(function(v) { return v.$__getValue('_id') || v; })); } else { this._registerAtomic('$pullAll', values); } this._markModified(); // Might have modified child paths and then pulled, like // `doc.children[1].name = 'test';` followed by // `doc.children.remove(doc.children[0]);`. In this case we fall back // to a `$set` on the whole array. See #3511 if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) { this._registerAtomic('$set', this); } return this; } /** * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. * * ####Example: * * const schema = Schema({ nums: [Number] }); * const Model = mongoose.model('Test', schema); * * const doc = await Model.create({ nums: [3, 4] }); * doc.nums.push(5); // Add 5 to the end of the array * await doc.save(); * * // You can also pass an object with `$each` as the * // first parameter to use MongoDB's `$position` * doc.nums.push({ * $each: [1, 2], * $position: 0 * }); * doc.nums; // [1, 2, 3, 4, 5] * * @param {Object} [args...] * @api public * @method push * @memberOf MongooseArray */ push() { let values = arguments; let atomic = values; const isOverwrite = values[0] != null && utils.hasUserDefinedProperty(values[0], '$each'); if (isOverwrite) { atomic = values[0]; values = values[0].$each; } if (this[arraySchemaSymbol] == null) { return _basePush.apply(this, values); } _checkManualPopulation(this, values); const parent = this[arrayParentSymbol]; values = [].map.call(values, this._mapCast, this); values = this[arraySchemaSymbol].applySetters(values, parent, undefined, undefined, { skipDocumentArrayCast: true }); let ret; const atomics = this[arrayAtomicsSymbol]; if (isOverwrite) { atomic.$each = values; if (get(atomics, '$push.$each.length', 0) > 0 && atomics.$push.$position != atomics.$position) { throw new MongooseError('Cannot call `Array#push()` multiple times ' + 'with different `$position`'); } if (atomic.$position != null) { [].splice.apply(this, [atomic.$position, 0].concat(values)); ret = this.length; } else { ret = [].push.apply(this, values); } } else { if (get(atomics, '$push.$each.length', 0) > 0 && atomics.$push.$position != null) { throw new MongooseError('Cannot call `Array#push()` multiple times ' + 'with different `$position`'); } atomic = values; ret = [].push.apply(this, values); } this._registerAtomic('$push', atomic); this._markModified(); return ret; } /** * Alias of [pull](#mongoosearray_MongooseArray-pull) * * @see MongooseArray#pull #types_array_MongooseArray-pull * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull * @api public * @memberOf MongooseArray * @instance * @method remove */ remove() { return this.pull.apply(this, arguments); } /** * Sets the casted `val` at index `i` and marks the array modified. * * ####Example: * * // given documents based on the following * const Doc = mongoose.model('Doc', new Schema({ array: [Number] })); * * const doc = new Doc({ array: [2,3,4] }) * * console.log(doc.array) // [2,3,4] * * doc.array.set(1,"5"); * console.log(doc.array); // [2,5,4] // properly cast to number * doc.save() // the change is saved * * // VS not using array#set * doc.array[1] = "5"; * console.log(doc.array); // [2,"5",4] // no casting * doc.save() // change is not saved * * @return {Array} this * @api public * @method set * @memberOf MongooseArray */ set(i, val) { const value = this._cast(val, i); this[i] = value; this._markModified(i); return this; } /** * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * * ####Example: * * doc.array = [2,3]; * const res = doc.array.shift(); * console.log(res) // 2 * console.log(doc.array) // [3] * * ####Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method shift * @memberOf MongooseArray */ shift() { const ret = [].shift.call(this); this._registerAtomic('$set', this); this._markModified(); return ret; } /** * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. * * ####NOTE: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method sort * @memberOf MongooseArray * @see https://masteringjs.io/tutorials/fundamentals/array-sort */ sort() { const ret = [].sort.apply(this, arguments); this._registerAtomic('$set', this); return ret; } /** * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. * * ####Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method splice * @memberOf MongooseArray * @see https://masteringjs.io/tutorials/fundamentals/array-splice */ splice() { let ret; _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); if (arguments.length) { let vals; if (this[arraySchemaSymbol] == null) { vals = arguments; } else { vals = []; for (let i = 0; i < arguments.length; ++i) { vals[i] = i < 2 ? arguments[i] : this._cast(arguments[i], arguments[0] + (i - 2)); } } ret = [].splice.apply(this, vals); this._registerAtomic('$set', this); } return ret; } /*! * ignore */ slice() { const ret = super.slice.apply(this, arguments); ret[arrayParentSymbol] = this[arrayParentSymbol]; ret[arraySchemaSymbol] = this[arraySchemaSymbol]; ret[arrayAtomicsSymbol] = this[arrayAtomicsSymbol]; ret[arrayPathSymbol] = this[arrayPathSymbol]; ret[slicedSymbol] = true; return ret; } /*! * ignore */ filter() { const ret = super.filter.apply(this, arguments); ret[arrayParentSymbol] = this[arrayParentSymbol]; ret[arraySchemaSymbol] = this[arraySchemaSymbol]; ret[arrayAtomicsSymbol] = this[arrayAtomicsSymbol]; ret[arrayPathSymbol] = this[arrayPathSymbol]; return ret; } /*! * ignore */ toBSON() { return this.toObject(internalToObjectOptions); } /** * Returns a native js Array. * * @param {Object} options * @return {Array} * @api public * @method toObject * @memberOf MongooseArray */ toObject(options) { if (options && options.depopulate) { options = utils.clone(options); options._isNested = true; // Ensure return value is a vanilla array, because in Node.js 6+ `map()` // is smart enough to use the inherited array's constructor. return [].concat(this).map(function(doc) { return doc instanceof Document ? doc.toObject(options) : doc; }); } return [].concat(this); } /** * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * * ####Note: * * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method unshift * @memberOf MongooseArray */ unshift() { _checkManualPopulation(this, arguments); let values; if (this[arraySchemaSymbol] == null) { values = arguments; } else { values = [].map.call(arguments, this._cast, this); values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); } [].unshift.apply(this, values); this._registerAtomic('$set', this); this._markModified(); return this.length; } } if (util.inspect.custom) { CoreMongooseArray.prototype[util.inspect.custom] = CoreMongooseArray.prototype.inspect; } /*! * ignore */ function _isAllSubdocs(docs, ref) { if (!ref) { return false; } for (const arg of docs) { if (arg == null) { return false; } const model = arg.constructor; if (!(arg instanceof Document) || (model.modelName !== ref && model.baseModelName !== ref)) { return false; } } return true; } /*! * ignore */ function _checkManualPopulation(arr, docs) { const ref = arr == null ? null : get(arr[arraySchemaSymbol], 'caster.options.ref', null); if (arr.length === 0 && docs.length > 0) { if (_isAllSubdocs(docs, ref)) { arr[arrayParentSymbol].populated(arr[arrayPathSymbol], [], { [populateModelSymbol]: docs[0].constructor }); } } } module.exports = CoreMongooseArray; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../document":268,"../error/mongooseError":281,"../helpers/document/cleanModifiedSubpaths":299,"../helpers/get":303,"../helpers/symbols":326,"../options":331,"../utils":381,"./embedded":376,"./objectid":379,"util":414}],374:[function(require,module,exports){ /** * ObjectId type constructor * * ####Example * * const id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ 'use strict'; module.exports = require('../driver').get().Decimal128; },{"../driver":270}],375:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ const CoreMongooseArray = require('./core_array'); const Document = require('../document'); const ObjectId = require('./objectid'); const castObjectId = require('../cast/objectid'); const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue'); const internalToObjectOptions = require('../options').internalToObjectOptions; const util = require('util'); const utils = require('../utils'); const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; const documentArrayParent = require('../helpers/symbols').documentArrayParent; const _basePush = Array.prototype.push; class CoreDocumentArray extends CoreMongooseArray { get isMongooseDocumentArray() { return true; } /*! * ignore */ toBSON() { return this.toObject(internalToObjectOptions); } /*! * ignore */ map() { const ret = super.map.apply(this, arguments); ret[arraySchemaSymbol] = null; ret[arrayPathSymbol] = null; ret[arrayParentSymbol] = null; return ret; } /** * Overrides MongooseArray#cast * * @method _cast * @api private * @receiver MongooseDocumentArray */ _cast(value, index) { if (this[arraySchemaSymbol] == null) { return value; } let Constructor = this[arraySchemaSymbol].casterConstructor; const isInstance = Constructor.$isMongooseDocumentArray ? value && value.isMongooseDocumentArray : value instanceof Constructor; if (isInstance || // Hack re: #5001, see #5005 (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) { if (!(value[documentArrayParent] && value.__parentArray)) { // value may have been created using array.create() value[documentArrayParent] = this[arrayParentSymbol]; value.__parentArray = this; } value.$setIndex(index); return value; } if (value === undefined || value === null) { return null; } // handle cast('string') or cast(ObjectId) etc. // only objects are permitted so we can safely assume that // non-objects are to be interpreted as _id if (Buffer.isBuffer(value) || value instanceof ObjectId || !utils.isObject(value)) { value = { _id: value }; } if (value && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor, value[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } if (Constructor.$isMongooseDocumentArray) { return Constructor.cast(value, this, undefined, undefined, index); } return new Constructor(value, this, undefined, undefined, index); } /** * Searches array items for the first document with a matching _id. * * ####Example: * * const embeddedDoc = m.array.id(some_id); * * @return {EmbeddedDocument|null} the subdocument or null if not found. * @param {ObjectId|String|Number|Buffer} id * @TODO cast to the _id based on schema for proper comparison * @method id * @api public * @receiver MongooseDocumentArray */ id(id) { let casted; let sid; let _id; try { casted = castObjectId(id).toString(); } catch (e) { casted = null; } for (const val of this) { if (!val) { continue; } _id = val.get('_id'); if (_id === null || typeof _id === 'undefined') { continue; } else if (_id instanceof Document) { sid || (sid = String(id)); if (sid == _id._id) { return val; } } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) { if (id == _id || utils.deepEqual(id, _id)) { return val; } } else if (casted == _id) { return val; } } return null; } /** * Returns a native js Array of plain js objects * * ####NOTE: * * _Each sub-document is converted to a plain object by calling its `#toObject` method._ * * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion * @return {Array} * @method toObject * @api public * @receiver MongooseDocumentArray */ toObject(options) { // `[].concat` coerces the return value into a vanilla JS array, rather // than a Mongoose array. return [].concat(this.map(function(doc) { if (doc == null) { return null; } if (typeof doc.toObject !== 'function') { return doc; } return doc.toObject(options); })); } slice() { const arr = super.slice.apply(this, arguments); arr[arrayParentSymbol] = this[arrayParentSymbol]; arr[arrayPathSymbol] = this[arrayPathSymbol]; return arr; } /** * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. * * @param {Object} [args...] * @api public * @method push * @memberOf MongooseDocumentArray */ push() { const ret = super.push.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Pulls items from the array atomically. * * @param {Object} [args...] * @api public * @method pull * @memberOf MongooseDocumentArray */ pull() { const ret = super.pull.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. */ shift() { const ret = super.shift.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. */ splice() { const ret = super.splice.apply(this, arguments); _updateParentPopulated(this); return ret; } /** * Helper for console.log * * @method inspect * @api public * @receiver MongooseDocumentArray */ inspect() { return this.toObject(); } /** * Creates a subdocument casted to this schema. * * This is the same subdocument constructor used for casting. * * @param {Object} obj the value to cast to this arrays SubDocument schema * @method create * @api public * @receiver MongooseDocumentArray */ create(obj) { let Constructor = this[arraySchemaSymbol].casterConstructor; if (obj && Constructor.discriminators && Constructor.schema && Constructor.schema.options && Constructor.schema.options.discriminatorKey) { if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; } else { const constructorByValue = getDiscriminatorByValue(Constructor, obj[Constructor.schema.options.discriminatorKey]); if (constructorByValue) { Constructor = constructorByValue; } } } return new Constructor(obj, this); } /*! * ignore */ notify(event) { const _this = this; return function notify(val, _arr) { _arr = _arr || _this; let i = _arr.length; while (i--) { if (_arr[i] == null) { continue; } switch (event) { // only swap for save event for now, we may change this to all event types later case 'save': val = _this[i]; break; default: // NO-OP break; } if (_arr[i].isMongooseArray) { notify(val, _arr[i]); } else if (_arr[i]) { _arr[i].emit(event, val); } } }; } } if (util.inspect.custom) { CoreDocumentArray.prototype[util.inspect.custom] = CoreDocumentArray.prototype.inspect; } /*! * If this is a document array, each element may contain single * populated paths, so we need to modify the top-level document's * populated cache. See gh-8247, gh-8265. */ function _updateParentPopulated(arr) { const parent = arr[arrayParentSymbol]; if (!parent || parent.$__.populated == null) return; const populatedPaths = Object.keys(parent.$__.populated). filter(p => p.startsWith(arr[arrayPathSymbol] + '.')); for (const path of populatedPaths) { const remnant = path.slice((arr[arrayPathSymbol] + '.').length); if (!Array.isArray(parent.$__.populated[path].value)) { continue; } parent.$__.populated[path].value = arr.map(val => val.populated(remnant)); } } /** * DocumentArray constructor * * @param {Array} values * @param {String} path the path to this array * @param {Document} doc parent document * @api private * @return {MongooseDocumentArray} * @inherits MongooseArray * @see http://bit.ly/f6CnZU */ function MongooseDocumentArray(values, path, doc) { // TODO: replace this with `new CoreDocumentArray().concat()` when we remove // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png const arr = new CoreDocumentArray(); arr[arrayAtomicsSymbol] = {}; arr[arraySchemaSymbol] = void 0; if (Array.isArray(values)) { if (values[arrayPathSymbol] === path && values[arrayParentSymbol] === doc) { arr[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]); } values.forEach(v => { _basePush.call(arr, v); }); } arr[arrayPathSymbol] = path; // Because doc comes from the context of another function, doc === global // can happen if there was a null somewhere up the chain (see #3020 && #3034) // RB Jun 17, 2015 updated to check for presence of expected paths instead // to make more proof against unusual node environments if (doc && doc instanceof Document) { arr[arrayParentSymbol] = doc; arr[arraySchemaSymbol] = doc.schema.path(path); // `schema.path()` doesn't drill into nested arrays properly yet, see // gh-6398, gh-6602. This is a workaround because nested arrays are // always plain non-document arrays, so once you get to a document array // nesting is done. Matryoshka code. while (arr != null && arr[arraySchemaSymbol] != null && arr[arraySchemaSymbol].$isMongooseArray && !arr[arraySchemaSymbol].$isMongooseDocumentArray) { arr[arraySchemaSymbol] = arr[arraySchemaSymbol].casterConstructor; } } return arr; } /*! * Module exports. */ module.exports = MongooseDocumentArray; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":255,"../cast/objectid":266,"../document":268,"../helpers/discriminator/getDiscriminatorByValue":297,"../helpers/symbols":326,"../options":331,"../utils":381,"./core_array":373,"./objectid":379,"util":414}],376:[function(require,module,exports){ /* eslint no-func-assign: 1 */ /*! * Module dependencies. */ 'use strict'; const Document = require('../document_provider')(); const EventEmitter = require('events').EventEmitter; const ValidationError = require('../error/validation'); const immediate = require('../helpers/immediate'); const internalToObjectOptions = require('../options').internalToObjectOptions; const get = require('../helpers/get'); const promiseOrCallback = require('../helpers/promiseOrCallback'); const util = require('util'); const documentArrayParent = require('../helpers/symbols').documentArrayParent; const validatorErrorSymbol = require('../helpers/symbols').validatorErrorSymbol; /** * EmbeddedDocument constructor. * * @param {Object} obj js object returned from the db * @param {MongooseDocumentArray} parentArr the parent array of this document * @param {Boolean} skipId * @inherits Document * @api private */ function EmbeddedDocument(obj, parentArr, skipId, fields, index) { const options = {}; if (parentArr != null && parentArr.isMongooseDocumentArray) { this.__parentArray = parentArr; this[documentArrayParent] = parentArr.$parent(); } else { this.__parentArray = undefined; this[documentArrayParent] = undefined; } this.$setIndex(index); this.$isDocumentArrayElement = true; if (this[documentArrayParent] != null) { options.defaults = this[documentArrayParent].$__.$options.defaults; } Document.call(this, obj, fields, skipId, options); const _this = this; this.on('isNew', function(val) { _this.isNew = val; }); _this.on('save', function() { _this.constructor.emit('save', _this); }); } /*! * Inherit from Document */ EmbeddedDocument.prototype = Object.create(Document.prototype); EmbeddedDocument.prototype.constructor = EmbeddedDocument; for (const i in EventEmitter.prototype) { EmbeddedDocument[i] = EventEmitter.prototype[i]; } EmbeddedDocument.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; /*! * ignore */ EmbeddedDocument.prototype.$setIndex = function(index) { this.__index = index; if (get(this, '$__.validationError', null) != null) { const keys = Object.keys(this.$__.validationError.errors); for (const key of keys) { this.invalidate(key, this.$__.validationError.errors[key]); } } }; /** * Marks the embedded doc modified. * * ####Example: * * const doc = blogpost.comments.id(hexstring); * doc.mixed.type = 'changed'; * doc.markModified('mixed.type'); * * @param {String} path the path which changed * @api public * @receiver EmbeddedDocument */ EmbeddedDocument.prototype.markModified = function(path) { this.$__.activePaths.modify(path); if (!this.__parentArray) { return; } const pathToCheck = this.__parentArray.$path() + '.0.' + path; if (this.isNew && this.ownerDocument().isSelected(pathToCheck)) { // Mark the WHOLE parent array as modified // if this is a new document (i.e., we are initializing // a document), this.__parentArray._markModified(); } else { this.__parentArray._markModified(this, path); } }; /*! * ignore */ EmbeddedDocument.prototype.populate = function() { throw new Error('Mongoose does not support calling populate() on nested ' + 'docs. Instead of `doc.arr[0].populate("path")`, use ' + '`doc.populate("arr.0.path")`'); }; /** * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @return {Promise} resolved Promise * @api private */ EmbeddedDocument.prototype.save = function(options, fn) { if (typeof options === 'function') { fn = options; options = {}; } options = options || {}; if (!options.suppressWarning) { console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + 'the document to MongoDB, it only runs save middleware. ' + 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + 'if you\'re sure this behavior is right for your app.'); } return promiseOrCallback(fn, cb => { this.$__save(cb); }); }; /** * Used as a stub for middleware * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @method $__save * @api private */ EmbeddedDocument.prototype.$__save = function(fn) { return immediate(() => fn(null, this)); }; /*! * Registers remove event listeners for triggering * on subdocuments. * * @param {EmbeddedDocument} sub * @api private */ function registerRemoveListener(sub) { let owner = sub.ownerDocument(); function emitRemove() { owner.removeListener('save', emitRemove); owner.removeListener('remove', emitRemove); sub.emit('remove', sub); sub.constructor.emit('remove', sub); owner = sub = null; } owner.on('save', emitRemove); owner.on('remove', emitRemove); } /*! * no-op for hooks */ EmbeddedDocument.prototype.$__remove = function(cb) { return cb(null, this); }; /** * Removes the subdocument from its parent array. * * @param {Object} [options] * @param {Function} [fn] * @api public */ EmbeddedDocument.prototype.remove = function(options, fn) { if (typeof options === 'function' && !fn) { fn = options; options = undefined; } if (!this.__parentArray || (options && options.noop)) { fn && fn(null); return this; } let _id; if (!this.willRemove) { _id = this._doc._id; if (!_id) { throw new Error('For your own good, Mongoose does not know ' + 'how to remove an EmbeddedDocument that has no _id'); } this.__parentArray.pull({ _id: _id }); this.willRemove = true; registerRemoveListener(this); } if (fn) { fn(null); } return this; }; /** * Override #update method of parent documents. * @api private */ EmbeddedDocument.prototype.update = function() { throw new Error('The #update method is not available on EmbeddedDocuments'); }; /** * Helper for console.log * * @api public */ EmbeddedDocument.prototype.inspect = function() { return this.toObject({ transform: false, virtuals: false, flattenDecimals: false }); }; if (util.inspect.custom) { /*! * Avoid Node deprecation warning DEP0079 */ EmbeddedDocument.prototype[util.inspect.custom] = EmbeddedDocument.prototype.inspect; } /** * Marks a path as invalid, causing validation to fail. * * @param {String} path the field to invalidate * @param {String|Error} err error which states the reason `path` was invalid * @return {Boolean} * @api public */ EmbeddedDocument.prototype.invalidate = function(path, err, val) { Document.prototype.invalidate.call(this, path, err, val); if (!this[documentArrayParent] || this.__index == null) { if (err[validatorErrorSymbol] || err instanceof ValidationError) { return this.ownerDocument().$__.validationError; } throw err; } const index = this.__index; const parentPath = this.__parentArray.$path(); const fullPath = [parentPath, index, path].join('.'); this[documentArrayParent].invalidate(fullPath, err, val); return this.ownerDocument().$__.validationError; }; /** * Marks a path as valid, removing existing validation errors. * * @param {String} path the field to mark as valid * @api private * @method $markValid * @receiver EmbeddedDocument */ EmbeddedDocument.prototype.$markValid = function(path) { if (!this[documentArrayParent]) { return; } const index = this.__index; if (typeof index !== 'undefined') { const parentPath = this.__parentArray.$path(); const fullPath = [parentPath, index, path].join('.'); this[documentArrayParent].$markValid(fullPath); } }; /*! * ignore */ EmbeddedDocument.prototype.$ignore = function(path) { Document.prototype.$ignore.call(this, path); if (!this[documentArrayParent]) { return; } const index = this.__index; if (typeof index !== 'undefined') { const parentPath = this.__parentArray.$path(); const fullPath = [parentPath, index, path].join('.'); this[documentArrayParent].$ignore(fullPath); } }; /** * Checks if a path is invalid * * @param {String} path the field to check * @api private * @method $isValid * @receiver EmbeddedDocument */ EmbeddedDocument.prototype.$isValid = function(path) { const index = this.__index; if (typeof index !== 'undefined' && this[documentArrayParent]) { return !this[documentArrayParent].$__.validationError || !this[documentArrayParent].$__.validationError.errors[this.$__fullPath(path)]; } return true; }; /** * Returns the top level document of this sub-document. * * @return {Document} */ EmbeddedDocument.prototype.ownerDocument = function() { if (this.$__.ownerDocument) { return this.$__.ownerDocument; } let parent = this[documentArrayParent]; if (!parent) { return this; } while (parent[documentArrayParent] || parent.$__parent) { parent = parent[documentArrayParent] || parent.$__parent; } this.$__.ownerDocument = parent; return this.$__.ownerDocument; }; /** * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. * * @param {String} [path] * @return {String} * @api private * @method $__fullPath * @memberOf EmbeddedDocument * @instance */ EmbeddedDocument.prototype.$__fullPath = function(path) { if (!this.$__.fullPath) { let parent = this; // eslint-disable-line consistent-this if (!parent[documentArrayParent]) { return path; } const paths = []; while (parent[documentArrayParent] || parent.$__parent) { if (parent[documentArrayParent]) { paths.unshift(parent.__parentArray.$path()); } else { paths.unshift(parent.$basePath); } parent = parent[documentArrayParent] || parent.$__parent; } this.$__.fullPath = paths.join('.'); if (!this.$__.ownerDocument) { // optimization this.$__.ownerDocument = parent; } } return path ? this.$__.fullPath + '.' + path : this.$__.fullPath; }; /** * Returns this sub-documents parent document. * * @api public */ EmbeddedDocument.prototype.parent = function() { return this[documentArrayParent]; }; /** * Returns this sub-documents parent document. * * @api public */ EmbeddedDocument.prototype.$parent = EmbeddedDocument.prototype.parent; /** * Returns this sub-documents parent array. * * @api public */ EmbeddedDocument.prototype.parentArray = function() { return this.__parentArray; }; /*! * Module exports. */ module.exports = EmbeddedDocument; },{"../document_provider":269,"../error/validation":289,"../helpers/get":303,"../helpers/immediate":305,"../helpers/promiseOrCallback":315,"../helpers/symbols":326,"../options":331,"events":253,"util":414}],377:[function(require,module,exports){ /*! * Module exports. */ 'use strict'; exports.Array = require('./array'); exports.Buffer = require('./buffer'); exports.Document = // @deprecate exports.Embedded = require('./embedded'); exports.DocumentArray = require('./documentarray'); exports.Decimal128 = require('./decimal128'); exports.ObjectId = require('./objectid'); exports.Map = require('./map'); exports.Subdocument = require('./subdocument'); },{"./array":371,"./buffer":372,"./decimal128":374,"./documentarray":375,"./embedded":376,"./map":378,"./objectid":379,"./subdocument":380}],378:[function(require,module,exports){ 'use strict'; const Mixed = require('../schema/mixed'); const deepEqual = require('../utils').deepEqual; const get = require('../helpers/get'); const handleSpreadDoc = require('../helpers/document/handleSpreadDoc'); const util = require('util'); const specialProperties = require('../helpers/specialProperties'); const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; /*! * ignore */ class MongooseMap extends Map { constructor(v, path, doc, schemaType) { if (v != null && v.constructor.name === 'Object') { v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []); } super(v); this.$__parent = doc != null && doc.$__ != null ? doc : null; this.$__path = path; this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; this.$__runDeferred(); } $init(key, value) { checkValidKey(key); super.set(key, value); if (value != null && value.$isSingleNested) { value.$basePath = this.$__path + '.' + key; } } $__set(key, value) { super.set(key, value); } get(key, options) { options = options || {}; if (options.getters === false) { return super.get(key); } return this.$__schemaType.applyGetters(super.get(key), this.$__parent); } set(key, value) { checkValidKey(key); value = handleSpreadDoc(value); // Weird, but because you can't assign to `this` before calling `super()` // you can't get access to `$__schemaType` to cast in the initial call to // `set()` from the `super()` constructor. if (this.$__schemaType == null) { this.$__deferred = this.$__deferred || []; this.$__deferred.push({ key: key, value: value }); return; } const fullPath = this.$__path + '.' + key; const populated = this.$__parent != null && this.$__parent.$__ ? this.$__parent.populated(fullPath) || this.$__parent.populated(this.$__path) : null; const priorVal = this.get(key); if (populated != null) { if (value.$__ == null) { value = new populated.options[populateModelSymbol](value); } value.$__.wasPopulated = true; } else { try { value = this.$__schemaType. applySetters(value, this.$__parent, false, this.get(key)); } catch (error) { if (this.$__parent != null && this.$__parent.$__ != null) { this.$__parent.invalidate(fullPath, error); return; } throw error; } } super.set(key, value); if (value != null && value.$isSingleNested) { value.$basePath = this.$__path + '.' + key; } const parent = this.$__parent; if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) { parent.markModified(this.$__path + '.' + key); } } clear() { super.clear(); const parent = this.$__parent; if (parent != null) { parent.markModified(this.$__path); } } delete(key) { this.set(key, undefined); super.delete(key); } toBSON() { return new Map(this); } toObject(options) { if (get(options, 'flattenMaps')) { const ret = {}; const keys = this.keys(); for (const key of keys) { ret[key] = this.get(key); } return ret; } return new Map(this); } toJSON() { const ret = {}; const keys = this.keys(); for (const key of keys) { ret[key] = this.get(key); } return ret; } inspect() { return new Map(this); } $__runDeferred() { if (!this.$__deferred) { return; } for (const keyValueObject of this.$__deferred) { this.set(keyValueObject.key, keyValueObject.value); } this.$__deferred = null; } } if (util.inspect.custom) { Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { enumerable: false, writable: false, configurable: false, value: MongooseMap.prototype.inspect }); } Object.defineProperty(MongooseMap.prototype, '$__set', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$__parent', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$__path', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$__schemaType', { enumerable: false, writable: true, configurable: false }); Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', { enumerable: false, writable: false, configurable: false, value: true }); Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', { enumerable: false, writable: false, configurable: false, value: true }); /*! * Since maps are stored as objects under the hood, keys must be strings * and can't contain any invalid characters */ function checkValidKey(key) { const keyType = typeof key; if (keyType !== 'string') { throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`); } if (key.startsWith('$')) { throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`); } if (key.includes('.')) { throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`); } if (specialProperties.has(key)) { throw new Error(`Mongoose maps do not support reserved key name "${key}"`); } } module.exports = MongooseMap; },{"../helpers/document/handleSpreadDoc":302,"../helpers/get":303,"../helpers/specialProperties":325,"../helpers/symbols":326,"../schema/mixed":358,"../utils":381,"util":414}],379:[function(require,module,exports){ /** * ObjectId type constructor * * ####Example * * const id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ 'use strict'; const ObjectId = require('../driver').get().ObjectId; const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; /*! * Getter for convenience with populate, see gh-6115 */ Object.defineProperty(ObjectId.prototype, '_id', { enumerable: false, configurable: true, get: function() { return this; } }); ObjectId.prototype[objectIdSymbol] = true; module.exports = ObjectId; },{"../driver":270,"../helpers/symbols":326}],380:[function(require,module,exports){ 'use strict'; const Document = require('../document'); const immediate = require('../helpers/immediate'); const internalToObjectOptions = require('../options').internalToObjectOptions; const promiseOrCallback = require('../helpers/promiseOrCallback'); const documentArrayParent = require('../helpers/symbols').documentArrayParent; module.exports = Subdocument; /** * Subdocument constructor. * * @inherits Document * @api private */ function Subdocument(value, fields, parent, skipId, options) { this.$isSingleNested = true; const hasPriorDoc = options != null && options.priorDoc; let initedPaths = null; if (hasPriorDoc) { this._doc = Object.assign({}, options.priorDoc._doc); delete this._doc[this.schema.options.discriminatorKey]; initedPaths = Object.keys(options.priorDoc._doc || {}). filter(key => key !== this.schema.options.discriminatorKey); } if (parent != null) { // If setting a nested path, should copy isNew from parent re: gh-7048 options = Object.assign({}, options, { isNew: parent.isNew, defaults: parent.$__.$options.defaults }); } Document.call(this, value, fields, skipId, options); if (hasPriorDoc) { for (const key of initedPaths) { if (!this.$__.activePaths.states.modify[key] && !this.$__.activePaths.states.default[key] && !this.$__.$setCalled.has(key)) { const schematype = this.schema.path(key); const def = schematype == null ? void 0 : schematype.getDefault(this); if (def === void 0) { delete this._doc[key]; } else { this._doc[key] = def; this.$__.activePaths.default(key); } } } delete options.priorDoc; delete this.$__.$options.priorDoc; } } Subdocument.prototype = Object.create(Document.prototype); Subdocument.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; /** * Used as a stub for middleware * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @return {Promise} resolved Promise * @api private */ Subdocument.prototype.save = function(options, fn) { if (typeof options === 'function') { fn = options; options = {}; } options = options || {}; if (!options.suppressWarning) { console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + 'the document to MongoDB, it only runs save middleware. ' + 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + 'if you\'re sure this behavior is right for your app.'); } return promiseOrCallback(fn, cb => { this.$__save(cb); }); }; /** * Used as a stub for middleware * * ####NOTE: * * _This is a no-op. Does not actually save the doc to the db._ * * @param {Function} [fn] * @method $__save * @api private */ Subdocument.prototype.$__save = function(fn) { return immediate(() => fn(null, this)); }; Subdocument.prototype.$isValid = function(path) { if (this.$__parent && this.$basePath) { return this.$__parent.$isValid([this.$basePath, path].join('.')); } return Document.prototype.$isValid.call(this, path); }; Subdocument.prototype.markModified = function(path) { Document.prototype.markModified.call(this, path); if (this.$__parent && this.$basePath) { if (this.$__parent.isDirectModified(this.$basePath)) { return; } this.$__parent.markModified([this.$basePath, path].join('.'), this); } }; Subdocument.prototype.isModified = function(paths, modifiedPaths) { if (this.$__parent && this.$basePath) { if (Array.isArray(paths) || typeof paths === 'string') { paths = (Array.isArray(paths) ? paths : paths.split(' ')); paths = paths.map(p => [this.$basePath, p].join('.')); return this.$__parent.isModified(paths, modifiedPaths); } return this.$__parent.isModified(this.$basePath); } return Document.prototype.isModified.call(this, paths, modifiedPaths); }; /** * Marks a path as valid, removing existing validation errors. * * @param {String} path the field to mark as valid * @api private * @method $markValid * @receiver Subdocument */ Subdocument.prototype.$markValid = function(path) { Document.prototype.$markValid.call(this, path); if (this.$__parent && this.$basePath) { this.$__parent.$markValid([this.$basePath, path].join('.')); } }; /*! * ignore */ Subdocument.prototype.invalidate = function(path, err, val) { // Hack: array subdocuments' validationError is equal to the owner doc's, // so validating an array subdoc gives the top-level doc back. Temporary // workaround for #5208 so we don't have circular errors. if (err !== this.ownerDocument().$__.validationError) { Document.prototype.invalidate.call(this, path, err, val); } if (this.$__parent && this.$basePath) { this.$__parent.invalidate([this.$basePath, path].join('.'), err, val); } else if (err.kind === 'cast' || err.name === 'CastError') { throw err; } return this.ownerDocument().$__.validationError; }; /*! * ignore */ Subdocument.prototype.$ignore = function(path) { Document.prototype.$ignore.call(this, path); if (this.$__parent && this.$basePath) { this.$__parent.$ignore([this.$basePath, path].join('.')); } }; /** * Returns the top level document of this sub-document. * * @return {Document} */ Subdocument.prototype.ownerDocument = function() { if (this.$__.ownerDocument) { return this.$__.ownerDocument; } let parent = this.$__parent; if (!parent) { return this; } while (parent.$__parent || parent[documentArrayParent]) { parent = parent.$__parent || parent[documentArrayParent]; } this.$__.ownerDocument = parent; return this.$__.ownerDocument; }; /** * Returns this sub-documents parent document. * * @api public */ Subdocument.prototype.parent = function() { return this.$__parent; }; /** * Returns this sub-documents parent document. * * @api public */ Subdocument.prototype.$parent = Subdocument.prototype.parent; /*! * no-op for hooks */ Subdocument.prototype.$__remove = function(cb) { return cb(null, this); }; /** * Null-out this subdoc * * @param {Object} [options] * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove */ Subdocument.prototype.remove = function(options, callback) { if (typeof options === 'function') { callback = options; options = null; } registerRemoveListener(this); // If removing entire doc, no need to remove subdoc if (!options || !options.noop) { this.$__parent.set(this.$basePath, null); } if (typeof callback === 'function') { callback(null); } }; /*! * ignore */ Subdocument.prototype.populate = function() { throw new Error('Mongoose does not support calling populate() on nested ' + 'docs. Instead of `doc.nested.populate("path")`, use ' + '`doc.populate("nested.path")`'); }; /*! * Registers remove event listeners for triggering * on subdocuments. * * @param {Subdocument} sub * @api private */ function registerRemoveListener(sub) { let owner = sub.ownerDocument(); function emitRemove() { owner.removeListener('save', emitRemove); owner.removeListener('remove', emitRemove); sub.emit('remove', sub); sub.constructor.emit('remove', sub); owner = sub = null; } owner.on('save', emitRemove); owner.on('remove', emitRemove); } },{"../document":268,"../helpers/immediate":305,"../helpers/promiseOrCallback":315,"../helpers/symbols":326,"../options":331}],381:[function(require,module,exports){ (function (process){ 'use strict'; /*! * Module dependencies. */ const ms = require('ms'); const mpath = require('mpath'); const sliced = require('sliced'); const Buffer = require('safe-buffer').Buffer; const Decimal = require('./types/decimal128'); const ObjectId = require('./types/objectid'); const PopulateOptions = require('./options/PopulateOptions'); const clone = require('./helpers/clone'); const isObject = require('./helpers/isObject'); const isBsonType = require('./helpers/isBsonType'); const getFunctionName = require('./helpers/getFunctionName'); const isMongooseObject = require('./helpers/isMongooseObject'); const promiseOrCallback = require('./helpers/promiseOrCallback'); const specialProperties = require('./helpers/specialProperties'); let Document; exports.specialProperties = specialProperties; /*! * Produces a collection name from model `name`. By default, just returns * the model name * * @param {String} name a model name * @param {Function} pluralize function that pluralizes the collection name * @return {String} a collection name * @api private */ exports.toCollectionName = function(name, pluralize) { if (name === 'system.profile') { return name; } if (name === 'system.indexes') { return name; } if (typeof pluralize === 'function') { return pluralize(name); } return name; }; /*! * Determines if `a` and `b` are deep equal. * * Modified from node/lib/assert.js * * @param {any} a a value to compare to `b` * @param {any} b a value to compare to `a` * @return {Boolean} * @api private */ exports.deepEqual = function deepEqual(a, b) { if (a === b) { return true; } if (typeof a !== 'object' && typeof b !== 'object') { return a === b; } if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) || (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) { return a.toString() === b.toString(); } if (a instanceof RegExp && b instanceof RegExp) { return a.source === b.source && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.global === b.global; } if (a == null || b == null) { return false; } if (a.prototype !== b.prototype) { return false; } if (a instanceof Map && b instanceof Map) { return deepEqual(Array.from(a.keys()), Array.from(b.keys())) && deepEqual(Array.from(a.values()), Array.from(b.values())); } // Handle MongooseNumbers if (a instanceof Number && b instanceof Number) { return a.valueOf() === b.valueOf(); } if (Buffer.isBuffer(a)) { return exports.buffer.areEqual(a, b); } if (Array.isArray(a) && Array.isArray(b)) { const len = a.length; if (len !== b.length) { return false; } for (let i = 0; i < len; ++i) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (a.$__ != null) { a = a._doc; } else if (isMongooseObject(a)) { a = a.toObject(); } if (b.$__ != null) { b = b._doc; } else if (isMongooseObject(b)) { b = b.toObject(); } const ka = Object.keys(a); const kb = Object.keys(b); const kaLength = ka.length; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (kaLength !== kb.length) { return false; } // the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); // ~~~cheap key test for (let i = kaLength - 1; i >= 0; i--) { if (ka[i] !== kb[i]) { return false; } } // equivalent values for every corresponding key, and // ~~~possibly expensive deep test for (const key of ka) { if (!deepEqual(a[key], b[key])) { return false; } } return true; }; /*! * Get the last element of an array */ exports.last = function(arr) { if (arr.length > 0) { return arr[arr.length - 1]; } return void 0; }; exports.clone = clone; /*! * ignore */ exports.promiseOrCallback = promiseOrCallback; /*! * ignore */ exports.omit = function omit(obj, keys) { if (keys == null) { return Object.assign({}, obj); } if (!Array.isArray(keys)) { keys = [keys]; } const ret = Object.assign({}, obj); for (const key of keys) { delete ret[key]; } return ret; }; /*! * Shallow copies defaults into options. * * @param {Object} defaults * @param {Object} options * @return {Object} the merged object * @api private */ exports.options = function(defaults, options) { const keys = Object.keys(defaults); let i = keys.length; let k; options = options || {}; while (i--) { k = keys[i]; if (!(k in options)) { options[k] = defaults[k]; } } return options; }; /*! * Generates a random string * * @api private */ exports.random = function() { return Math.random().toString().substr(3); }; /*! * Merges `from` into `to` without overwriting existing properties. * * @param {Object} to * @param {Object} from * @api private */ exports.merge = function merge(to, from, options, path) { options = options || {}; const keys = Object.keys(from); let i = 0; const len = keys.length; let key; path = path || ''; const omitNested = options.omitNested || {}; while (i < len) { key = keys[i++]; if (options.omit && options.omit[key]) { continue; } if (omitNested[path]) { continue; } if (specialProperties.has(key)) { continue; } if (to[key] == null) { to[key] = from[key]; } else if (exports.isObject(from[key])) { if (!exports.isObject(to[key])) { to[key] = {}; } if (from[key] != null) { // Skip merging schemas if we're creating a discriminator schema and // base schema has a given path as a single nested but discriminator schema // has the path as a document array, or vice versa (gh-9534) if (options.isDiscriminatorSchemaMerge && (from[key].$isSingleNested && to[key].$isMongooseDocumentArray) || (from[key].$isMongooseDocumentArray && to[key].$isSingleNested)) { continue; } else if (from[key].instanceOfSchema) { if (to[key].instanceOfSchema) { to[key].add(from[key].clone()); } else { to[key] = from[key].clone(); } continue; } else if (from[key] instanceof ObjectId) { to[key] = new ObjectId(from[key]); continue; } } merge(to[key], from[key], options, path ? path + '.' + key : key); } else if (options.overwrite) { to[key] = from[key]; } } }; /*! * Applies toObject recursively. * * @param {Document|Array|Object} obj * @return {Object} * @api private */ exports.toObject = function toObject(obj) { Document || (Document = require('./document')); let ret; if (obj == null) { return obj; } if (obj instanceof Document) { return obj.toObject(); } if (Array.isArray(obj)) { ret = []; for (const doc of obj) { ret.push(toObject(doc)); } return ret; } if (exports.isPOJO(obj)) { ret = {}; for (const k in obj) { if (specialProperties.has(k)) { continue; } ret[k] = toObject(obj[k]); } return ret; } return obj; }; exports.isObject = isObject; /*! * Determines if `arg` is a plain old JavaScript object (POJO). Specifically, * `arg` must be an object but not an instance of any special class, like String, * ObjectId, etc. * * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf * * @param {Object|Array|String|Function|RegExp|any} arg * @api private * @return {Boolean} */ exports.isPOJO = function isPOJO(arg) { if (arg == null || typeof arg !== 'object') { return false; } const proto = Object.getPrototypeOf(arg); // Prototype may be null if you used `Object.create(null)` // Checking `proto`'s constructor is safe because `getPrototypeOf()` // explicitly crosses the boundary from object data to object metadata return !proto || proto.constructor.name === 'Object'; }; /*! * Determines if `obj` is a built-in object like an array, date, boolean, * etc. */ exports.isNativeObject = function(arg) { return Array.isArray(arg) || arg instanceof Date || arg instanceof Boolean || arg instanceof Number || arg instanceof String; }; /*! * Determines if `val` is an object that has no own keys */ exports.isEmptyObject = function(val) { return val != null && typeof val === 'object' && Object.keys(val).length === 0; }; /*! * Search if `obj` or any POJOs nested underneath `obj` has a property named * `key` */ exports.hasKey = function hasKey(obj, key) { const props = Object.keys(obj); for (const prop of props) { if (prop === key) { return true; } if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) { return true; } } return false; }; /*! * A faster Array.prototype.slice.call(arguments) alternative * @api private */ exports.args = sliced; /*! * process.nextTick helper. * * Wraps `callback` in a try/catch + nextTick. * * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. * * @param {Function} callback * @api private */ exports.tick = function tick(callback) { if (typeof callback !== 'function') { return; } return function() { try { callback.apply(this, arguments); } catch (err) { // only nextTick on err to get out of // the event loop and avoid state corruption. process.nextTick(function() { throw err; }); } }; }; /*! * Returns true if `v` is an object that can be serialized as a primitive in * MongoDB */ exports.isMongooseType = function(v) { return v instanceof ObjectId || v instanceof Decimal || v instanceof Buffer; }; exports.isMongooseObject = isMongooseObject; /*! * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. * * @param {Object} object * @api private */ exports.expires = function expires(object) { if (!(object && object.constructor.name === 'Object')) { return; } if (!('expires' in object)) { return; } let when; if (typeof object.expires !== 'string') { when = object.expires; } else { when = Math.round(ms(object.expires) / 1000); } object.expireAfterSeconds = when; delete object.expires; }; /*! * populate helper */ exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) { // might have passed an object specifying all arguments let obj = null; if (arguments.length === 1) { if (path instanceof PopulateOptions) { return [path]; } if (Array.isArray(path)) { const singles = makeSingles(path); return singles.map(o => exports.populate(o)[0]); } if (exports.isObject(path)) { obj = Object.assign({}, path); } else { obj = { path: path }; } } else if (typeof model === 'object') { obj = { path: path, select: select, match: model, options: match }; } else { obj = { path: path, select: select, model: model, match: match, options: options, populate: subPopulate, justOne: justOne, count: count }; } if (typeof obj.path !== 'string') { throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); } return _populateObj(obj); // The order of select/conditions args is opposite Model.find but // necessary to keep backward compatibility (select could be // an array, string, or object literal). function makeSingles(arr) { const ret = []; arr.forEach(function(obj) { if (/[\s]/.test(obj.path)) { const paths = obj.path.split(' '); paths.forEach(function(p) { const copy = Object.assign({}, obj); copy.path = p; ret.push(copy); }); } else { ret.push(obj); } }); return ret; } }; function _populateObj(obj) { if (Array.isArray(obj.populate)) { const ret = []; obj.populate.forEach(function(obj) { if (/[\s]/.test(obj.path)) { const copy = Object.assign({}, obj); const paths = copy.path.split(' '); paths.forEach(function(p) { copy.path = p; ret.push(exports.populate(copy)[0]); }); } else { ret.push(exports.populate(obj)[0]); } }); obj.populate = exports.populate(ret); } else if (obj.populate != null && typeof obj.populate === 'object') { obj.populate = exports.populate(obj.populate); } const ret = []; const paths = obj.path.split(' '); if (obj.options != null) { obj.options = exports.clone(obj.options); } for (const path of paths) { ret.push(new PopulateOptions(Object.assign({}, obj, { path: path }))); } return ret; } /*! * Return the value of `obj` at the given `path`. * * @param {String} path * @param {Object} obj */ exports.getValue = function(path, obj, map) { return mpath.get(path, obj, '_doc', map); }; /*! * Sets the value of `obj` at the given `path`. * * @param {String} path * @param {Anything} val * @param {Object} obj */ exports.setValue = function(path, val, obj, map, _copying) { mpath.set(path, val, obj, '_doc', map, _copying); }; /*! * Returns an array of values from object `o`. * * @param {Object} o * @return {Array} * @private */ exports.object = {}; exports.object.vals = function vals(o) { const keys = Object.keys(o); let i = keys.length; const ret = []; while (i--) { ret.push(o[keys[i]]); } return ret; }; /*! * @see exports.options */ exports.object.shallowCopy = exports.options; /*! * Safer helper for hasOwnProperty checks * * @param {Object} obj * @param {String} prop */ const hop = Object.prototype.hasOwnProperty; exports.object.hasOwnProperty = function(obj, prop) { return hop.call(obj, prop); }; /*! * Determine if `val` is null or undefined * * @return {Boolean} */ exports.isNullOrUndefined = function(val) { return val === null || val === undefined; }; /*! * ignore */ exports.array = {}; /*! * Flattens an array. * * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] * * @param {Array} arr * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results. * @return {Array} * @private */ exports.array.flatten = function flatten(arr, filter, ret) { ret || (ret = []); arr.forEach(function(item) { if (Array.isArray(item)) { flatten(item, filter, ret); } else { if (!filter || filter(item)) { ret.push(item); } } }); return ret; }; /*! * ignore */ const _hasOwnProperty = Object.prototype.hasOwnProperty; exports.hasUserDefinedProperty = function(obj, key) { if (obj == null) { return false; } if (Array.isArray(key)) { for (const k of key) { if (exports.hasUserDefinedProperty(obj, k)) { return true; } } return false; } if (_hasOwnProperty.call(obj, key)) { return true; } if (typeof obj === 'object' && key in obj) { const v = obj[key]; return v !== Object.prototype[key] && v !== Array.prototype[key]; } return false; }; /*! * ignore */ const MAX_ARRAY_INDEX = Math.pow(2, 32) - 1; exports.isArrayIndex = function(val) { if (typeof val === 'number') { return val >= 0 && val <= MAX_ARRAY_INDEX; } if (typeof val === 'string') { if (!/^\d+$/.test(val)) { return false; } val = +val; return val >= 0 && val <= MAX_ARRAY_INDEX; } return false; }; /*! * Removes duplicate values from an array * * [1, 2, 3, 3, 5] => [1, 2, 3, 5] * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] * => [ObjectId("550988ba0c19d57f697dc45e")] * * @param {Array} arr * @return {Array} * @private */ exports.array.unique = function(arr) { const primitives = {}; const ids = {}; const ret = []; for (const item of arr) { if (typeof item === 'number' || typeof item === 'string' || item == null) { if (primitives[item]) { continue; } ret.push(item); primitives[item] = true; } else if (item instanceof ObjectId) { if (ids[item.toString()]) { continue; } ret.push(item); ids[item.toString()] = true; } else { ret.push(item); } } return ret; }; /*! * Determines if two buffers are equal. * * @param {Buffer} a * @param {Object} b */ exports.buffer = {}; exports.buffer.areEqual = function(a, b) { if (!Buffer.isBuffer(a)) { return false; } if (!Buffer.isBuffer(b)) { return false; } if (a.length !== b.length) { return false; } for (let i = 0, len = a.length; i < len; ++i) { if (a[i] !== b[i]) { return false; } } return true; }; exports.getFunctionName = getFunctionName; /*! * Decorate buffers */ exports.decorate = function(destination, source) { for (const key in source) { if (specialProperties.has(key)) { continue; } destination[key] = source[key]; } }; /** * merges to with a copy of from * * @param {Object} to * @param {Object} fromObj * @api private */ exports.mergeClone = function(to, fromObj) { if (isMongooseObject(fromObj)) { fromObj = fromObj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } const keys = Object.keys(fromObj); const len = keys.length; let i = 0; let key; while (i < len) { key = keys[i++]; if (specialProperties.has(key)) { continue; } if (typeof to[key] === 'undefined') { to[key] = exports.clone(fromObj[key], { transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } else { let val = fromObj[key]; if (val != null && val.valueOf && !(val instanceof Date)) { val = val.valueOf(); } if (exports.isObject(val)) { let obj = val; if (isMongooseObject(val) && !val.isMongooseBuffer) { obj = obj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } if (val.isMongooseBuffer) { obj = Buffer.from(obj); } exports.mergeClone(to[key], obj); } else { to[key] = exports.clone(val, { flattenDecimals: false }); } } } }; /** * Executes a function on each element of an array (like _.each) * * @param {Array} arr * @param {Function} fn * @api private */ exports.each = function(arr, fn) { for (const item of arr) { fn(item); } }; /*! * ignore */ exports.getOption = function(name) { const sources = Array.prototype.slice.call(arguments, 1); for (const source of sources) { if (source[name] != null) { return source[name]; } } return null; }; /*! * ignore */ exports.noop = function() {}; }).call(this,require('_process')) },{"./document":268,"./helpers/clone":293,"./helpers/getFunctionName":304,"./helpers/isBsonType":306,"./helpers/isMongooseObject":307,"./helpers/isObject":308,"./helpers/promiseOrCallback":315,"./helpers/specialProperties":325,"./options/PopulateOptions":332,"./types/decimal128":374,"./types/objectid":379,"_process":399,"mpath":384,"ms":383,"safe-buffer":401,"sliced":402}],382:[function(require,module,exports){ 'use strict'; const utils = require('./utils'); /** * VirtualType constructor * * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. * * ####Example: * * const fullname = schema.virtual('fullname'); * fullname instanceof mongoose.VirtualType // true * * @param {Object} options * @param {string|function} [options.ref] if `ref` is not nullish, this becomes a [populated virtual](/docs/populate.html#populate-virtuals) * @param {string|function} [options.localField] the local field to populate on if this is a populated virtual. * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) * @param {Object|Function} [options.match=null] add an extra match condition to `populate()` * @param {Number} [options.limit=null] add a default `limit` to the `populate()` query * @param {Number} [options.skip=null] add a default `skip` to the `populate()` query * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. * @param {Object} [options.options=null] Additional options like `limit` and `lean`. * @api public */ function VirtualType(options, name) { this.path = name; this.getters = []; this.setters = []; this.options = Object.assign({}, options); } /** * If no getters/getters, add a default * * @param {Function} fn * @return {VirtualType} this * @api private */ VirtualType.prototype._applyDefaultGetters = function() { if (this.getters.length > 0 || this.setters.length > 0) { return; } const path = this.path; const internalProperty = '$' + path; this.getters.push(function() { return this[internalProperty]; }); this.setters.push(function(v) { this[internalProperty] = v; }); }; /*! * ignore */ VirtualType.prototype.clone = function() { const clone = new VirtualType(this.options, this.path); clone.getters = [].concat(this.getters); clone.setters = [].concat(this.setters); return clone; }; /** * Adds a custom getter to this virtual. * * Mongoose calls the getter function with the below 3 parameters. * * - `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`. * - `virtual`: the virtual object you called `.get()` on * - `doc`: the document this virtual is attached to. Equivalent to `this`. * * ####Example: * * const virtual = schema.virtual('fullname'); * virtual.get(function(value, virtual, doc) { * return this.name.first + ' ' + this.name.last; * }); * * @param {Function(Any, VirtualType, Document)} fn * @return {VirtualType} this * @api public */ VirtualType.prototype.get = function(fn) { this.getters.push(fn); return this; }; /** * Adds a custom setter to this virtual. * * Mongoose calls the setter function with the below 3 parameters. * * - `value`: the value being set * - `virtual`: the virtual object you're calling `.set()` on * - `doc`: the document this virtual is attached to. Equivalent to `this`. * * ####Example: * * const virtual = schema.virtual('fullname'); * virtual.set(function(value, virtual, doc) { * const parts = value.split(' '); * this.name.first = parts[0]; * this.name.last = parts[1]; * }); * * const Model = mongoose.model('Test', schema); * const doc = new Model(); * // Calls the setter with `value = 'Jean-Luc Picard'` * doc.fullname = 'Jean-Luc Picard'; * doc.name.first; // 'Jean-Luc' * doc.name.last; // 'Picard' * * @param {Function(Any, VirtualType, Document)} fn * @return {VirtualType} this * @api public */ VirtualType.prototype.set = function(fn) { this.setters.push(fn); return this; }; /** * Applies getters to `value`. * * @param {Object} value * @param {Document} doc The document this virtual is attached to * @return {any} the value after applying all getters * @api public */ VirtualType.prototype.applyGetters = function(value, doc) { if (utils.hasUserDefinedProperty(this.options, ['ref', 'refPath']) && doc.$$populatedVirtuals && doc.$$populatedVirtuals.hasOwnProperty(this.path)) { value = doc.$$populatedVirtuals[this.path]; } let v = value; for (let l = this.getters.length - 1; l >= 0; l--) { v = this.getters[l].call(doc, v, this, doc); } return v; }; /** * Applies setters to `value`. * * @param {Object} value * @param {Document} doc * @return {any} the value after applying all setters * @api public */ VirtualType.prototype.applySetters = function(value, doc) { let v = value; for (let l = this.setters.length - 1; l >= 0; l--) { v = this.setters[l].call(doc, v, this, doc); } return v; }; /*! * exports */ module.exports = VirtualType; },{"./utils":381}],383:[function(require,module,exports){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } },{}],384:[function(require,module,exports){ 'use strict'; module.exports = exports = require('./lib'); },{"./lib":385}],385:[function(require,module,exports){ /* eslint strict:off */ /* eslint no-var: off */ /* eslint no-redeclare: off */ var stringToParts = require('./stringToParts'); // These properties are special and can open client libraries to security // issues var ignoreProperties = ['__proto__', 'constructor', 'prototype']; /** * Returns the value of object `o` at the given `path`. * * ####Example: * * var obj = { * comments: [ * { title: 'exciting!', _doc: { title: 'great!' }} * , { title: 'number dos' } * ] * } * * mpath.get('comments.0.title', o) // 'exciting!' * mpath.get('comments.0.title', o, '_doc') // 'great!' * mpath.get('comments.title', o) // ['exciting!', 'number dos'] * * // summary * mpath.get(path, o) * mpath.get(path, o, special) * mpath.get(path, o, map) * mpath.get(path, o, special, map) * * @param {String} path * @param {Object} o * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. */ exports.get = function(path, o, special, map) { var lookup; if ('function' == typeof special) { if (special.length < 2) { map = special; special = undefined; } else { lookup = special; special = undefined; } } map || (map = K); var parts = 'string' == typeof path ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } var obj = o, part; for (var i = 0; i < parts.length; ++i) { part = parts[i]; if (Array.isArray(obj) && !/^\d+$/.test(part)) { // reading a property from the array items var paths = parts.slice(i); // Need to `concat()` to avoid `map()` calling a constructor of an array // subclass return [].concat(obj).map(function(item) { return item ? exports.get(paths, item, special || lookup, map) : map(undefined); }); } if (lookup) { obj = lookup(obj, part); } else { var _from = special && obj[special] ? obj[special] : obj; obj = _from instanceof Map ? _from.get(part) : _from[part]; } if (!obj) return map(obj); } return map(obj); }; /** * Returns true if `in` returns true for every piece of the path * * @param {String} path * @param {Object} o */ exports.has = function(path, o) { var parts = typeof path === 'string' ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } var len = parts.length; var cur = o; for (var i = 0; i < len; ++i) { if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { return false; } cur = cur[parts[i]]; } return true; }; /** * Deletes the last piece of `path` * * @param {String} path * @param {Object} o */ exports.unset = function(path, o) { var parts = typeof path === 'string' ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } var len = parts.length; var cur = o; for (var i = 0; i < len; ++i) { if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { return false; } // Disallow any updates to __proto__ or special properties. if (ignoreProperties.indexOf(parts[i]) !== -1) { return false; } if (i === len - 1) { delete cur[parts[i]]; return true; } cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; } return true; }; /** * Sets the `val` at the given `path` of object `o`. * * @param {String} path * @param {Anything} val * @param {Object} o * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. */ exports.set = function(path, val, o, special, map, _copying) { var lookup; if ('function' == typeof special) { if (special.length < 2) { map = special; special = undefined; } else { lookup = special; special = undefined; } } map || (map = K); var parts = 'string' == typeof path ? stringToParts(path) : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } if (null == o) return; for (var i = 0; i < parts.length; ++i) { // Silently ignore any updates to `__proto__`, these are potentially // dangerous if using mpath with unsanitized data. if (ignoreProperties.indexOf(parts[i]) !== -1) { return; } } // the existance of $ in a path tells us if the user desires // the copying of an array instead of setting each value of // the array to the one by one to matching positions of the // current array. Unless the user explicitly opted out by passing // false, see Automattic/mongoose#6273 var copy = _copying || (/\$/.test(path) && _copying !== false), obj = o, part; for (var i = 0, len = parts.length - 1; i < len; ++i) { part = parts[i]; if ('$' == part) { if (i == len - 1) { break; } else { continue; } } if (Array.isArray(obj) && !/^\d+$/.test(part)) { var paths = parts.slice(i); if (!copy && Array.isArray(val)) { for (var j = 0; j < obj.length && j < val.length; ++j) { // assignment of single values of array exports.set(paths, val[j], obj[j], special || lookup, map, copy); } } else { for (var j = 0; j < obj.length; ++j) { // assignment of entire value exports.set(paths, val, obj[j], special || lookup, map, copy); } } return; } if (lookup) { obj = lookup(obj, part); } else { var _to = special && obj[special] ? obj[special] : obj; obj = _to instanceof Map ? _to.get(part) : _to[part]; } if (!obj) return; } // process the last property of the path part = parts[len]; // use the special property if exists if (special && obj[special]) { obj = obj[special]; } // set the value on the last branch if (Array.isArray(obj) && !/^\d+$/.test(part)) { if (!copy && Array.isArray(val)) { _setArray(obj, val, part, lookup, special, map); } else { for (var j = 0; j < obj.length; ++j) { var item = obj[j]; if (item) { if (lookup) { lookup(item, part, map(val)); } else { if (item[special]) item = item[special]; item[part] = map(val); } } } } } else { if (lookup) { lookup(obj, part, map(val)); } else if (obj instanceof Map) { obj.set(part, map(val)); } else { obj[part] = map(val); } } }; /*! * Recursively set nested arrays */ function _setArray(obj, val, part, lookup, special, map) { for (var item, j = 0; j < obj.length && j < val.length; ++j) { item = obj[j]; if (Array.isArray(item) && Array.isArray(val[j])) { _setArray(item, val[j], part, lookup, special, map); } else if (item) { if (lookup) { lookup(item, part, map(val[j])); } else { if (item[special]) item = item[special]; item[part] = map(val[j]); } } } } /*! * Returns the value passed to it. */ function K(v) { return v; } },{"./stringToParts":386}],386:[function(require,module,exports){ 'use strict'; module.exports = function stringToParts(str) { const result = []; let curPropertyName = ''; let state = 'DEFAULT'; for (let i = 0; i < str.length; ++i) { // Fall back to treating as property name rather than bracket notation if // square brackets contains something other than a number. if (state === 'IN_SQUARE_BRACKETS' && !/\d/.test(str[i]) && str[i] !== ']') { state = 'DEFAULT'; curPropertyName = result[result.length - 1] + '[' + curPropertyName; result.splice(result.length - 1, 1); } if (str[i] === '[') { if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { result.push(curPropertyName); curPropertyName = ''; } state = 'IN_SQUARE_BRACKETS'; } else if (str[i] === ']') { if (state === 'IN_SQUARE_BRACKETS') { state = 'IMMEDIATELY_AFTER_SQUARE_BRACKETS'; result.push(curPropertyName); curPropertyName = ''; } else { state = 'DEFAULT'; curPropertyName += str[i]; } } else if (str[i] === '.') { if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { result.push(curPropertyName); curPropertyName = ''; } state = 'DEFAULT'; } else { curPropertyName += str[i]; } } if (state !== 'IMMEDIATELY_AFTER_SQUARE_BRACKETS') { result.push(curPropertyName); } return result; }; },{}],387:[function(require,module,exports){ 'use strict'; /** * methods a collection must implement */ var methods = [ 'find', 'findOne', 'update', 'updateMany', 'updateOne', 'replaceOne', 'remove', 'count', 'distinct', 'findAndModify', 'aggregate', 'findStream', 'deleteOne', 'deleteMany' ]; /** * Collection base class from which implementations inherit */ function Collection() {} for (var i = 0, len = methods.length; i < len; ++i) { var method = methods[i]; Collection.prototype[method] = notImplemented(method); } module.exports = exports = Collection; Collection.methods = methods; /** * creates a function which throws an implementation error */ function notImplemented(method) { return function() { throw new Error('collection.' + method + ' not implemented'); }; } },{}],388:[function(require,module,exports){ 'use strict'; var env = require('../env'); if ('unknown' == env.type) { throw new Error('Unknown environment'); } module.exports = env.isNode ? require('./node') : env.isMongo ? require('./collection') : require('./collection'); },{"../env":390,"./collection":387,"./node":389}],389:[function(require,module,exports){ 'use strict'; /** * Module dependencies */ var Collection = require('./collection'); var utils = require('../utils'); function NodeCollection(col) { this.collection = col; this.collectionName = col.collectionName; } /** * inherit from collection base class */ utils.inherits(NodeCollection, Collection); /** * find(match, options, function(err, docs)) */ NodeCollection.prototype.find = function(match, options, cb) { this.collection.find(match, options, function(err, cursor) { if (err) return cb(err); try { cursor.toArray(cb); } catch (error) { cb(error); } }); }; /** * findOne(match, options, function(err, doc)) */ NodeCollection.prototype.findOne = function(match, options, cb) { this.collection.findOne(match, options, cb); }; /** * count(match, options, function(err, count)) */ NodeCollection.prototype.count = function(match, options, cb) { this.collection.count(match, options, cb); }; /** * distinct(prop, match, options, function(err, count)) */ NodeCollection.prototype.distinct = function(prop, match, options, cb) { this.collection.distinct(prop, match, options, cb); }; /** * update(match, update, options, function(err[, result])) */ NodeCollection.prototype.update = function(match, update, options, cb) { this.collection.update(match, update, options, cb); }; /** * update(match, update, options, function(err[, result])) */ NodeCollection.prototype.updateMany = function(match, update, options, cb) { this.collection.updateMany(match, update, options, cb); }; /** * update(match, update, options, function(err[, result])) */ NodeCollection.prototype.updateOne = function(match, update, options, cb) { this.collection.updateOne(match, update, options, cb); }; /** * replaceOne(match, update, options, function(err[, result])) */ NodeCollection.prototype.replaceOne = function(match, update, options, cb) { this.collection.replaceOne(match, update, options, cb); }; /** * deleteOne(match, options, function(err[, result]) */ NodeCollection.prototype.deleteOne = function(match, options, cb) { this.collection.deleteOne(match, options, cb); }; /** * deleteMany(match, options, function(err[, result]) */ NodeCollection.prototype.deleteMany = function(match, options, cb) { this.collection.deleteMany(match, options, cb); }; /** * remove(match, options, function(err[, result]) */ NodeCollection.prototype.remove = function(match, options, cb) { this.collection.remove(match, options, cb); }; /** * findAndModify(match, update, options, function(err, doc)) */ NodeCollection.prototype.findAndModify = function(match, update, options, cb) { var sort = Array.isArray(options.sort) ? options.sort : []; this.collection.findAndModify(match, sort, update, options, cb); }; /** * var stream = findStream(match, findOptions, streamOptions) */ NodeCollection.prototype.findStream = function(match, findOptions, streamOptions) { return this.collection.find(match, findOptions).stream(streamOptions); }; /** * var cursor = findCursor(match, findOptions) */ NodeCollection.prototype.findCursor = function(match, findOptions) { return this.collection.find(match, findOptions); }; /** * aggregation(operators..., function(err, doc)) * TODO */ /** * Expose */ module.exports = exports = NodeCollection; },{"../utils":393,"./collection":387}],390:[function(require,module,exports){ (function (process,global,Buffer){ 'use strict'; exports.isNode = 'undefined' != typeof process && 'object' == typeof module && 'object' == typeof global && 'function' == typeof Buffer && process.argv; exports.isMongo = !exports.isNode && 'function' == typeof printjson && 'function' == typeof ObjectId && 'function' == typeof rs && 'function' == typeof sh; exports.isBrowser = !exports.isNode && !exports.isMongo && 'undefined' != typeof window; exports.type = exports.isNode ? 'node' : exports.isMongo ? 'mongo' : exports.isBrowser ? 'browser' : 'unknown'; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"_process":399,"buffer":115}],391:[function(require,module,exports){ 'use strict'; /** * Dependencies */ var slice = require('sliced'); var assert = require('assert'); var util = require('util'); var utils = require('./utils'); var debug = require('debug')('mquery'); /* global Map */ /** * Query constructor used for building queries. * * ####Example: * * var query = new Query({ name: 'mquery' }); * query.setOptions({ collection: moduleCollection }) * query.where('age').gte(21).exec(callback); * * @param {Object} [criteria] * @param {Object} [options] * @api public */ function Query(criteria, options) { if (!(this instanceof Query)) return new Query(criteria, options); var proto = this.constructor.prototype; this.op = proto.op || undefined; this.options = Object.assign({}, proto.options); this._conditions = proto._conditions ? utils.clone(proto._conditions) : {}; this._fields = proto._fields ? utils.clone(proto._fields) : undefined; this._update = proto._update ? utils.clone(proto._update) : undefined; this._path = proto._path || undefined; this._distinct = proto._distinct || undefined; this._collection = proto._collection || undefined; this._traceFunction = proto._traceFunction || undefined; if (options) { this.setOptions(options); } if (criteria) { if (criteria.find && criteria.remove && criteria.update) { // quack quack! this.collection(criteria); } else { this.find(criteria); } } } /** * This is a parameter that the user can set which determines if mquery * uses $within or $geoWithin for queries. It defaults to true which * means $geoWithin will be used. If using MongoDB < 2.4 you should * set this to false. * * @api public * @property use$geoWithin */ var $withinCmd = '$geoWithin'; Object.defineProperty(Query, 'use$geoWithin', { get: function( ) { return $withinCmd == '$geoWithin'; }, set: function(v) { if (true === v) { // mongodb >= 2.4 $withinCmd = '$geoWithin'; } else { $withinCmd = '$within'; } } }); /** * Converts this query to a constructor function with all arguments and options retained. * * ####Example * * // Create a query that will read documents with a "video" category from * // `aCollection` on the primary node in the replica-set unless it is down, * // in which case we'll read from a secondary node. * var query = mquery({ category: 'video' }) * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); * * // create a constructor based off these settings * var Video = query.toConstructor(); * * // Video is now a subclass of mquery() and works the same way but with the * // default query parameters and options set. * * // run a query with the previous settings but filter for movies with names * // that start with "Life". * Video().where({ name: /^Life/ }).exec(cb); * * @return {Query} new Query * @api public */ Query.prototype.toConstructor = function toConstructor() { function CustomQuery(criteria, options) { if (!(this instanceof CustomQuery)) return new CustomQuery(criteria, options); Query.call(this, criteria, options); } utils.inherits(CustomQuery, Query); // set inherited defaults var p = CustomQuery.prototype; p.options = {}; p.setOptions(this.options); p.op = this.op; p._conditions = utils.clone(this._conditions); p._fields = utils.clone(this._fields); p._update = utils.clone(this._update); p._path = this._path; p._distinct = this._distinct; p._collection = this._collection; p._traceFunction = this._traceFunction; return CustomQuery; }; /** * Sets query options. * * ####Options: * * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) * - collection the collection to query against * * _* denotes a query helper method is also available_ * * @param {Object} options * @api public */ Query.prototype.setOptions = function(options) { if (!(options && utils.isObject(options))) return this; // set arbitrary options var methods = utils.keys(options), method; for (var i = 0; i < methods.length; ++i) { method = methods[i]; // use methods if exist (safer option manipulation) if ('function' == typeof this[method]) { var args = utils.isArray(options[method]) ? options[method] : [options[method]]; this[method].apply(this, args); } else { this.options[method] = options[method]; } } return this; }; /** * Sets this Querys collection. * * @param {Collection} coll * @return {Query} this */ Query.prototype.collection = function collection(coll) { this._collection = new Query.Collection(coll); return this; }; /** * Adds a collation to this op (MongoDB 3.4 and up) * * ####Example * * query.find().collation({ locale: "en_US", strength: 1 }) * * @param {Object} value * @return {Query} this * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation * @api public */ Query.prototype.collation = function(value) { this.options.collation = value; return this; }; /** * Specifies a `$where` condition * * Use `$where` when you need to select documents using a JavaScript expression. * * ####Example * * query.$where('this.comments.length > 10 || this.name.length > 5') * * query.$where(function () { * return this.comments.length > 10 || this.name.length > 5; * }) * * @param {String|Function} js javascript string or function * @return {Query} this * @memberOf Query * @method $where * @api public */ Query.prototype.$where = function(js) { this._conditions.$where = js; return this; }; /** * Specifies a `path` for use with chaining. * * ####Example * * // instead of writing: * User.find({age: {$gte: 21, $lte: 65}}, callback); * * // we can instead write: * User.where('age').gte(21).lte(65); * * // passing query conditions is permitted * User.find().where({ name: 'vonderful' }) * * // chaining * User * .where('age').gte(21).lte(65) * .where('name', /^vonderful/i) * .where('friends').slice(10) * .exec(callback) * * @param {String} [path] * @param {Object} [val] * @return {Query} this * @api public */ Query.prototype.where = function() { if (!arguments.length) return this; if (!this.op) this.op = 'find'; var type = typeof arguments[0]; if ('string' == type) { this._path = arguments[0]; if (2 === arguments.length) { this._conditions[this._path] = arguments[1]; } return this; } if ('object' == type && !Array.isArray(arguments[0])) { return this.merge(arguments[0]); } throw new TypeError('path must be a string or object'); }; /** * Specifies the complementary comparison value for paths specified with `where()` * * ####Example * * User.where('age').equals(49); * * // is the same as * * User.where('age', 49); * * @param {Object} val * @return {Query} this * @api public */ Query.prototype.equals = function equals(val) { this._ensurePath('equals'); var path = this._path; this._conditions[path] = val; return this; }; /** * Specifies the complementary comparison value for paths specified with `where()` * This is alias of `equals` * * ####Example * * User.where('age').eq(49); * * // is the same as * * User.shere('age').equals(49); * * // is the same as * * User.where('age', 49); * * @param {Object} val * @return {Query} this * @api public */ Query.prototype.eq = function eq(val) { this._ensurePath('eq'); var path = this._path; this._conditions[path] = val; return this; }; /** * Specifies arguments for an `$or` condition. * * ####Example * * query.or([{ color: 'red' }, { status: 'emergency' }]) * * @param {Array} array array of conditions * @return {Query} this * @api public */ Query.prototype.or = function or(array) { var or = this._conditions.$or || (this._conditions.$or = []); if (!utils.isArray(array)) array = [array]; or.push.apply(or, array); return this; }; /** * Specifies arguments for a `$nor` condition. * * ####Example * * query.nor([{ color: 'green' }, { status: 'ok' }]) * * @param {Array} array array of conditions * @return {Query} this * @api public */ Query.prototype.nor = function nor(array) { var nor = this._conditions.$nor || (this._conditions.$nor = []); if (!utils.isArray(array)) array = [array]; nor.push.apply(nor, array); return this; }; /** * Specifies arguments for a `$and` condition. * * ####Example * * query.and([{ color: 'green' }, { status: 'ok' }]) * * @see $and http://docs.mongodb.org/manual/reference/operator/and/ * @param {Array} array array of conditions * @return {Query} this * @api public */ Query.prototype.and = function and(array) { var and = this._conditions.$and || (this._conditions.$and = []); if (!Array.isArray(array)) array = [array]; and.push.apply(and, array); return this; }; /** * Specifies a $gt query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * ####Example * * Thing.find().where('age').gt(21) * * // or * Thing.find().gt('age', 21) * * @method gt * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $gte query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method gte * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $lt query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method lt * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $lte query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method lte * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $ne query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method ne * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies an $in query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method in * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies an $nin query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method nin * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies an $all query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method all * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $size query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method size * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /** * Specifies a $regex query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method regex * @memberOf Query * @param {String} [path] * @param {String|RegExp} val * @api public */ /** * Specifies a $maxDistance query condition. * * When called with one argument, the most recent path passed to `where()` is used. * * @method maxDistance * @memberOf Query * @param {String} [path] * @param {Number} val * @api public */ /*! * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance * * Thing.where('type').nin(array) */ 'gt gte lt lte ne in nin all regex size maxDistance minDistance'.split(' ').forEach(function($conditional) { Query.prototype[$conditional] = function() { var path, val; if (1 === arguments.length) { this._ensurePath($conditional); val = arguments[0]; path = this._path; } else { val = arguments[1]; path = arguments[0]; } var conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ? this._conditions[path] : (this._conditions[path] = {}); conds['$' + $conditional] = val; return this; }; }); /** * Specifies a `$mod` condition * * @param {String} [path] * @param {Number} val * @return {Query} this * @api public */ Query.prototype.mod = function() { var val, path; if (1 === arguments.length) { this._ensurePath('mod'); val = arguments[0]; path = this._path; } else if (2 === arguments.length && !utils.isArray(arguments[1])) { this._ensurePath('mod'); val = slice(arguments); path = this._path; } else if (3 === arguments.length) { val = slice(arguments, 1); path = arguments[0]; } else { val = arguments[1]; path = arguments[0]; } var conds = this._conditions[path] || (this._conditions[path] = {}); conds.$mod = val; return this; }; /** * Specifies an `$exists` condition * * ####Example * * // { name: { $exists: true }} * Thing.where('name').exists() * Thing.where('name').exists(true) * Thing.find().exists('name') * * // { name: { $exists: false }} * Thing.where('name').exists(false); * Thing.find().exists('name', false); * * @param {String} [path] * @param {Number} val * @return {Query} this * @api public */ Query.prototype.exists = function() { var path, val; if (0 === arguments.length) { this._ensurePath('exists'); path = this._path; val = true; } else if (1 === arguments.length) { if ('boolean' === typeof arguments[0]) { this._ensurePath('exists'); path = this._path; val = arguments[0]; } else { path = arguments[0]; val = true; } } else if (2 === arguments.length) { path = arguments[0]; val = arguments[1]; } var conds = this._conditions[path] || (this._conditions[path] = {}); conds.$exists = val; return this; }; /** * Specifies an `$elemMatch` condition * * ####Example * * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) * * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) * * query.elemMatch('comment', function (elem) { * elem.where('author').equals('autobot'); * elem.where('votes').gte(5); * }) * * query.where('comment').elemMatch(function (elem) { * elem.where({ author: 'autobot' }); * elem.where('votes').gte(5); * }) * * @param {String|Object|Function} path * @param {Object|Function} criteria * @return {Query} this * @api public */ Query.prototype.elemMatch = function() { if (null == arguments[0]) throw new TypeError('Invalid argument'); var fn, path, criteria; if ('function' === typeof arguments[0]) { this._ensurePath('elemMatch'); path = this._path; fn = arguments[0]; } else if (utils.isObject(arguments[0])) { this._ensurePath('elemMatch'); path = this._path; criteria = arguments[0]; } else if ('function' === typeof arguments[1]) { path = arguments[0]; fn = arguments[1]; } else if (arguments[1] && utils.isObject(arguments[1])) { path = arguments[0]; criteria = arguments[1]; } else { throw new TypeError('Invalid argument'); } if (fn) { criteria = new Query; fn(criteria); criteria = criteria._conditions; } var conds = this._conditions[path] || (this._conditions[path] = {}); conds.$elemMatch = criteria; return this; }; // Spatial queries /** * Sugar for geo-spatial queries. * * ####Example * * query.within().box() * query.within().circle() * query.within().geometry() * * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); * query.where('loc').within({ polygon: [[],[],[],[]] }); * * query.where('loc').within([], [], []) // polygon * query.where('loc').within([], []) // box * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry * * ####NOTE: * * Must be used after `where()`. * * @memberOf Query * @return {Query} this * @api public */ Query.prototype.within = function within() { // opinionated, must be used after where this._ensurePath('within'); this._geoComparison = $withinCmd; if (0 === arguments.length) { return this; } if (2 === arguments.length) { return this.box.apply(this, arguments); } else if (2 < arguments.length) { return this.polygon.apply(this, arguments); } var area = arguments[0]; if (!area) throw new TypeError('Invalid argument'); if (area.center) return this.circle(area); if (area.box) return this.box.apply(this, area.box); if (area.polygon) return this.polygon.apply(this, area.polygon); if (area.type && area.coordinates) return this.geometry(area); throw new TypeError('Invalid argument'); }; /** * Specifies a $box condition * * ####Example * * var lowerLeft = [40.73083, -73.99756] * var upperRight= [40.741404, -73.988135] * * query.where('loc').within().box(lowerLeft, upperRight) * query.box('loc', lowerLeft, upperRight ) * * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @see Query#within #query_Query-within * @param {String} path * @param {Object} val * @return {Query} this * @api public */ Query.prototype.box = function() { var path, box; if (3 === arguments.length) { // box('loc', [], []) path = arguments[0]; box = [arguments[1], arguments[2]]; } else if (2 === arguments.length) { // box([], []) this._ensurePath('box'); path = this._path; box = [arguments[0], arguments[1]]; } else { throw new TypeError('Invalid argument'); } var conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison || $withinCmd] = { '$box': box }; return this; }; /** * Specifies a $polygon condition * * ####Example * * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) * query.polygon('loc', [10,20], [13, 25], [7,15]) * * @param {String|Array} [path] * @param {Array|Object} [val] * @return {Query} this * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @api public */ Query.prototype.polygon = function() { var val, path; if ('string' == typeof arguments[0]) { // polygon('loc', [],[],[]) path = arguments[0]; val = slice(arguments, 1); } else { // polygon([],[],[]) this._ensurePath('polygon'); path = this._path; val = slice(arguments); } var conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison || $withinCmd] = { '$polygon': val }; return this; }; /** * Specifies a $center or $centerSphere condition. * * ####Example * * var area = { center: [50, 50], radius: 10, unique: true } * query.where('loc').within().circle(area) * query.center('loc', area); * * // for spherical calculations * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } * query.where('loc').within().circle(area) * query.center('loc', area); * * @param {String} [path] * @param {Object} area * @return {Query} this * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @api public */ Query.prototype.circle = function() { var path, val; if (1 === arguments.length) { this._ensurePath('circle'); path = this._path; val = arguments[0]; } else if (2 === arguments.length) { path = arguments[0]; val = arguments[1]; } else { throw new TypeError('Invalid argument'); } if (!('radius' in val && val.center)) throw new Error('center and radius are required'); var conds = this._conditions[path] || (this._conditions[path] = {}); var type = val.spherical ? '$centerSphere' : '$center'; var wKey = this._geoComparison || $withinCmd; conds[wKey] = {}; conds[wKey][type] = [val.center, val.radius]; if ('unique' in val) conds[wKey].$uniqueDocs = !!val.unique; return this; }; /** * Specifies a `$near` or `$nearSphere` condition * * These operators return documents sorted by distance. * * ####Example * * query.where('loc').near({ center: [10, 10] }); * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); * query.near('loc', { center: [10, 10], maxDistance: 5 }); * query.near({ center: { type: 'Point', coordinates: [..] }}) * query.near().geometry({ type: 'Point', coordinates: [..] }) * * @param {String} [path] * @param {Object} val * @return {Query} this * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @api public */ Query.prototype.near = function near() { var path, val; this._geoComparison = '$near'; if (0 === arguments.length) { return this; } else if (1 === arguments.length) { this._ensurePath('near'); path = this._path; val = arguments[0]; } else if (2 === arguments.length) { path = arguments[0]; val = arguments[1]; } else { throw new TypeError('Invalid argument'); } if (!val.center) { throw new Error('center is required'); } var conds = this._conditions[path] || (this._conditions[path] = {}); var type = val.spherical ? '$nearSphere' : '$near'; // center could be a GeoJSON object or an Array if (Array.isArray(val.center)) { conds[type] = val.center; var radius = 'maxDistance' in val ? val.maxDistance : null; if (null != radius) { conds.$maxDistance = radius; } if (null != val.minDistance) { conds.$minDistance = val.minDistance; } } else { // GeoJSON? if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { throw new Error(util.format('Invalid GeoJSON specified for %s', type)); } conds[type] = { $geometry : val.center }; // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere if ('maxDistance' in val) { conds[type]['$maxDistance'] = val.maxDistance; } if ('minDistance' in val) { conds[type]['$minDistance'] = val.minDistance; } } return this; }; /** * Declares an intersects query for `geometry()`. * * ####Example * * query.where('path').intersects().geometry({ * type: 'LineString' * , coordinates: [[180.0, 11.0], [180, 9.0]] * }) * * query.where('path').intersects({ * type: 'LineString' * , coordinates: [[180.0, 11.0], [180, 9.0]] * }) * * @param {Object} [arg] * @return {Query} this * @api public */ Query.prototype.intersects = function intersects() { // opinionated, must be used after where this._ensurePath('intersects'); this._geoComparison = '$geoIntersects'; if (0 === arguments.length) { return this; } var area = arguments[0]; if (null != area && area.type && area.coordinates) return this.geometry(area); throw new TypeError('Invalid argument'); }; /** * Specifies a `$geometry` condition * * ####Example * * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) * * // or * var polyB = [[ 0, 0 ], [ 1, 1 ]] * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) * * // or * var polyC = [ 0, 0 ] * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) * * // or * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) * * ####NOTE: * * `geometry()` **must** come after either `intersects()` or `within()`. * * The `object` argument must contain `type` and `coordinates` properties. * - type {String} * - coordinates {Array} * * The most recent path passed to `where()` is used. * * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. * @return {Query} this * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ * @api public */ Query.prototype.geometry = function geometry() { if (!('$within' == this._geoComparison || '$geoWithin' == this._geoComparison || '$near' == this._geoComparison || '$geoIntersects' == this._geoComparison)) { throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); } var val, path; if (1 === arguments.length) { this._ensurePath('geometry'); path = this._path; val = arguments[0]; } else { throw new TypeError('Invalid argument'); } if (!(val.type && Array.isArray(val.coordinates))) { throw new TypeError('Invalid argument'); } var conds = this._conditions[path] || (this._conditions[path] = {}); conds[this._geoComparison] = { $geometry: val }; return this; }; // end spatial /** * Specifies which document fields to include or exclude * * ####String syntax * * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. * * ####Example * * // include a and b, exclude c * query.select('a b -c'); * * // or you may use object notation, useful when * // you have keys already prefixed with a "-" * query.select({a: 1, b: 1, c: 0}); * * ####Note * * Cannot be used with `distinct()` * * @param {Object|String} arg * @return {Query} this * @see SchemaType * @api public */ Query.prototype.select = function select() { var arg = arguments[0]; if (!arg) return this; if (arguments.length !== 1) { throw new Error('Invalid select: select only takes 1 argument'); } this._validate('select'); var fields = this._fields || (this._fields = {}); var type = typeof arg; var i, len; if (('string' == type || utils.isArgumentsObject(arg)) && 'number' == typeof arg.length || Array.isArray(arg)) { if ('string' == type) arg = arg.split(/\s+/); for (i = 0, len = arg.length; i < len; ++i) { var field = arg[i]; if (!field) continue; var include = '-' == field[0] ? 0 : 1; if (include === 0) field = field.substring(1); fields[field] = include; } return this; } if (utils.isObject(arg)) { var keys = utils.keys(arg); for (i = 0; i < keys.length; ++i) { fields[keys[i]] = arg[keys[i]]; } return this; } throw new TypeError('Invalid select() argument. Must be string or object.'); }; /** * Specifies a $slice condition for a `path` * * ####Example * * query.slice('comments', 5) * query.slice('comments', -5) * query.slice('comments', [10, 5]) * query.where('comments').slice(5) * query.where('comments').slice([-10, 5]) * * @param {String} [path] * @param {Number} val number/range of elements to slice * @return {Query} this * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements * @api public */ Query.prototype.slice = function() { if (0 === arguments.length) return this; this._validate('slice'); var path, val; if (1 === arguments.length) { var arg = arguments[0]; if (typeof arg === 'object' && !Array.isArray(arg)) { var keys = Object.keys(arg); var numKeys = keys.length; for (var i = 0; i < numKeys; ++i) { this.slice(keys[i], arg[keys[i]]); } return this; } this._ensurePath('slice'); path = this._path; val = arguments[0]; } else if (2 === arguments.length) { if ('number' === typeof arguments[0]) { this._ensurePath('slice'); path = this._path; val = slice(arguments); } else { path = arguments[0]; val = arguments[1]; } } else if (3 === arguments.length) { path = arguments[0]; val = slice(arguments, 1); } var myFields = this._fields || (this._fields = {}); myFields[path] = { '$slice': val }; return this; }; /** * Sets the sort order * * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. * * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. * * ####Example * * // these are equivalent * query.sort({ field: 'asc', test: -1 }); * query.sort('field -test'); * query.sort([['field', 1], ['test', -1]]); * * ####Note * * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15). * - Cannot be used with `distinct()` * * @param {Object|String|Array} arg * @return {Query} this * @api public */ Query.prototype.sort = function(arg) { if (!arg) return this; var i, len, field; this._validate('sort'); var type = typeof arg; // .sort([['field', 1], ['test', -1]]) if (Array.isArray(arg)) { len = arg.length; for (i = 0; i < arg.length; ++i) { if (!Array.isArray(arg[i])) { throw new Error('Invalid sort() argument, must be array of arrays'); } _pushArr(this.options, arg[i][0], arg[i][1]); } return this; } // .sort('field -test') if (1 === arguments.length && 'string' == type) { arg = arg.split(/\s+/); len = arg.length; for (i = 0; i < len; ++i) { field = arg[i]; if (!field) continue; var ascend = '-' == field[0] ? -1 : 1; if (ascend === -1) field = field.substring(1); push(this.options, field, ascend); } return this; } // .sort({ field: 1, test: -1 }) if (utils.isObject(arg)) { var keys = utils.keys(arg); for (i = 0; i < keys.length; ++i) { field = keys[i]; push(this.options, field, arg[field]); } return this; } if (typeof Map !== 'undefined' && arg instanceof Map) { _pushMap(this.options, arg); return this; } throw new TypeError('Invalid sort() argument. Must be a string, object, or array.'); }; /*! * @ignore */ var _validSortValue = { '1': 1, '-1': -1, 'asc': 1, 'ascending': 1, 'desc': -1, 'descending': -1 }; function push(opts, field, value) { if (Array.isArray(opts.sort)) { throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + '\n- `.sort({ field: 1, test: -1 })`'); } var s; if (value && value.$meta) { s = opts.sort || (opts.sort = {}); s[field] = { $meta : value.$meta }; return; } s = opts.sort || (opts.sort = {}); var val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError('Invalid sort value: { ' + field + ': ' + value + ' }'); s[field] = val; } function _pushArr(opts, field, value) { opts.sort = opts.sort || []; if (!Array.isArray(opts.sort)) { throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + '\n- `.sort({ field: 1, test: -1 })`'); } var val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError('Invalid sort value: [ ' + field + ', ' + value + ' ]'); opts.sort.push([field, val]); } function _pushMap(opts, map) { opts.sort = opts.sort || new Map(); if (!(opts.sort instanceof Map)) { throw new TypeError('Can\'t mix sort syntaxes. Use either array or ' + 'object or map consistently'); } map.forEach(function(value, key) { var val = String(value || 1).toLowerCase(); val = _validSortValue[val]; if (!val) throw new TypeError('Invalid sort value: < ' + key + ': ' + value + ' >'); opts.sort.set(key, val); }); } /** * Specifies the limit option. * * ####Example * * query.limit(20) * * ####Note * * Cannot be used with `distinct()` * * @method limit * @memberOf Query * @param {Number} val * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D * @api public */ /** * Specifies the skip option. * * ####Example * * query.skip(100).limit(20) * * ####Note * * Cannot be used with `distinct()` * * @method skip * @memberOf Query * @param {Number} val * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D * @api public */ /** * Specifies the maxScan option. * * ####Example * * query.maxScan(100) * * ####Note * * Cannot be used with `distinct()` * * @method maxScan * @memberOf Query * @param {Number} val * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan * @api public */ /** * Specifies the batchSize option. * * ####Example * * query.batchSize(100) * * ####Note * * Cannot be used with `distinct()` * * @method batchSize * @memberOf Query * @param {Number} val * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D * @api public */ /** * Specifies the `comment` option. * * ####Example * * query.comment('login query') * * ####Note * * Cannot be used with `distinct()` * * @method comment * @memberOf Query * @param {Number} val * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment * @api public */ /*! * limit, skip, maxScan, batchSize, comment * * Sets these associated options. * * query.comment('feed query'); */ ['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function(method) { Query.prototype[method] = function(v) { this._validate(method); this.options[method] = v; return this; }; }); /** * Specifies the maxTimeMS option. * * ####Example * * query.maxTime(100) * query.maxTimeMS(100) * * @method maxTime * @memberOf Query * @param {Number} ms * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS * @api public */ Query.prototype.maxTime = Query.prototype.maxTimeMS = function(ms) { this._validate('maxTime'); this.options.maxTimeMS = ms; return this; }; /** * Specifies this query as a `snapshot` query. * * ####Example * * mquery().snapshot() // true * mquery().snapshot(true) * mquery().snapshot(false) * * ####Note * * Cannot be used with `distinct()` * * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D * @return {Query} this * @api public */ Query.prototype.snapshot = function() { this._validate('snapshot'); this.options.snapshot = arguments.length ? !!arguments[0] : true; return this; }; /** * Sets query hints. * * ####Example * * query.hint({ indexA: 1, indexB: -1}); * query.hint('indexA_1_indexB_1'); * * ####Note * * Cannot be used with `distinct()` * * @param {Object|string} val a hint object or the index name * @return {Query} this * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint * @api public */ Query.prototype.hint = function() { if (0 === arguments.length) return this; this._validate('hint'); var arg = arguments[0]; if (utils.isObject(arg)) { var hint = this.options.hint || (this.options.hint = {}); // must keep object keys in order so don't use Object.keys() for (var k in arg) { hint[k] = arg[k]; } return this; } if (typeof arg === 'string') { this.options.hint = arg; return this; } throw new TypeError('Invalid hint. ' + arg); }; /** * Requests acknowledgement that this operation has been persisted to MongoDB's * on-disk journal. * This option is only valid for operations that write to the database: * * - `deleteOne()` * - `deleteMany()` * - `findOneAndDelete()` * - `findOneAndUpdate()` * - `remove()` * - `update()` * - `updateOne()` * - `updateMany()` * * Defaults to the `j` value if it is specified in writeConcern options * * ####Example: * * mquery().w(2).j(true).wtimeout(2000); * * @method j * @memberOf Query * @instance * @param {boolean} val * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option * @return {Query} this * @api public */ Query.prototype.j = function j(val) { this.options.j = val; return this; }; /** * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. * * ####Example: * * query.slaveOk() // true * query.slaveOk(true) * query.slaveOk(false) * * @deprecated use read() preferences instead if on mongodb >= 2.2 * @param {Boolean} v defaults to true * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference * @see read() * @return {Query} this * @api public */ Query.prototype.slaveOk = function(v) { this.options.slaveOk = arguments.length ? !!v : true; return this; }; /** * Sets the readPreference option for the query. * * ####Example: * * new Query().read('primary') * new Query().read('p') // same as primary * * new Query().read('primaryPreferred') * new Query().read('pp') // same as primaryPreferred * * new Query().read('secondary') * new Query().read('s') // same as secondary * * new Query().read('secondaryPreferred') * new Query().read('sp') // same as secondaryPreferred * * new Query().read('nearest') * new Query().read('n') // same as nearest * * // you can also use mongodb.ReadPreference class to also specify tags * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) * * new Query().setReadPreference('primary') // alias of .read() * * ####Preferences: * * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. * secondary Read from secondary if available, otherwise error. * primaryPreferred Read from primary if available, otherwise a secondary. * secondaryPreferred Read from a secondary if available, otherwise read from the primary. * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. * * Aliases * * p primary * pp primaryPreferred * s secondary * sp secondaryPreferred * n nearest * * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). * * @param {String|ReadPreference} pref one of the listed preference options or their aliases * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences * @return {Query} this * @api public */ Query.prototype.read = Query.prototype.setReadPreference = function(pref) { if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { console.error('Deprecation warning: \'tags\' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead.'); Query.prototype.read.deprecationWarningIssued = true; } this.options.readPreference = utils.readPref(pref); return this; }; /** * Sets the readConcern option for the query. * * ####Example: * * new Query().readConcern('local') * new Query().readConcern('l') // same as local * * new Query().readConcern('available') * new Query().readConcern('a') // same as available * * new Query().readConcern('majority') * new Query().readConcern('m') // same as majority * * new Query().readConcern('linearizable') * new Query().readConcern('lz') // same as linearizable * * new Query().readConcern('snapshot') * new Query().readConcern('s') // same as snapshot * * new Query().r('s') // r is alias of readConcern * * * ####Read Concern Level: * * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. * * * Aliases * * l local * a available * m majority * lz linearizable * s snapshot * * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). * * @param {String} level one of the listed read concern level or their aliases * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ * @return {Query} this * @api public */ Query.prototype.readConcern = Query.prototype.r = function(level) { this.options.readConcern = utils.readConcern(level); return this; }; /** * Sets tailable option. * * ####Example * * query.tailable() <== true * query.tailable(true) * query.tailable(false) * * ####Note * * Cannot be used with `distinct()` * * @param {Boolean} v defaults to true * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors * @api public */ Query.prototype.tailable = function() { this._validate('tailable'); this.options.tailable = arguments.length ? !!arguments[0] : true; return this; }; /** * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, * that must acknowledge this write before this write is considered successful. * This option is only valid for operations that write to the database: * * - `deleteOne()` * - `deleteMany()` * - `findOneAndDelete()` * - `findOneAndUpdate()` * - `remove()` * - `update()` * - `updateOne()` * - `updateMany()` * * Defaults to the `w` value if it is specified in writeConcern options * * ####Example: * * mquery().writeConcern(0) * mquery().writeConcern(1) * mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) * mquery().writeConcern('majority') * mquery().writeConcern('m') // same as majority * mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead * mquery().w(1) // w is alias of writeConcern * * @method writeConcern * @memberOf Query * @instance * @param {String|number|object} concern 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option * @return {Query} this * @api public */ Query.prototype.writeConcern = Query.prototype.w = function writeConcern(concern) { if ('object' === typeof concern) { if ('undefined' !== typeof concern.j) this.options.j = concern.j; if ('undefined' !== typeof concern.w) this.options.w = concern.w; if ('undefined' !== typeof concern.wtimeout) this.options.wtimeout = concern.wtimeout; } else { this.options.w = 'm' === concern ? 'majority' : concern; } return this; }; /** * Specifies a time limit, in milliseconds, for the write concern. * If `ms > 1`, it is maximum amount of time to wait for this write * to propagate through the replica set before this operation fails. * The default is `0`, which means no timeout. * * This option is only valid for operations that write to the database: * * - `deleteOne()` * - `deleteMany()` * - `findOneAndDelete()` * - `findOneAndUpdate()` * - `remove()` * - `update()` * - `updateOne()` * - `updateMany()` * * Defaults to `wtimeout` value if it is specified in writeConcern * * ####Example: * * mquery().w(2).j(true).wtimeout(2000) * * @method wtimeout * @memberOf Query * @instance * @param {number} ms number of milliseconds to wait * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout * @return {Query} this * @api public */ Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout(ms) { this.options.wtimeout = ms; return this; }; /** * Merges another Query or conditions object into this one. * * When a Query is passed, conditions, field selection and options are merged. * * @param {Query|Object} source * @return {Query} this */ Query.prototype.merge = function(source) { if (!source) return this; if (!Query.canMerge(source)) throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); if (source instanceof Query) { // if source has a feature, apply it to ourselves if (source._conditions) { utils.merge(this._conditions, source._conditions); } if (source._fields) { this._fields || (this._fields = {}); utils.merge(this._fields, source._fields); } if (source.options) { this.options || (this.options = {}); utils.merge(this.options, source.options); } if (source._update) { this._update || (this._update = {}); utils.mergeClone(this._update, source._update); } if (source._distinct) { this._distinct = source._distinct; } return this; } // plain object utils.merge(this._conditions, source); return this; }; /** * Finds documents. * * Passing a `callback` executes the query. * * ####Example * * query.find() * query.find(callback) * query.find({ name: 'Burning Lights' }, callback) * * @param {Object} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.find = function(criteria, callback) { this.op = 'find'; if ('function' === typeof criteria) { callback = criteria; criteria = undefined; } else if (Query.canMerge(criteria)) { this.merge(criteria); } if (!callback) return this; var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('find', this._collection.collectionName, conds, options); callback = this._wrapCallback('find', callback, { conditions: conds, options: options }); this._collection.find(conds, options, utils.tick(callback)); return this; }; /** * Returns the query cursor * * ####Examples * * query.find().cursor(); * query.cursor({ name: 'Burning Lights' }); * * @param {Object} [criteria] mongodb selector * @return {Object} cursor * @api public */ Query.prototype.cursor = function cursor(criteria) { if (this.op) { if (this.op !== 'find') { throw new TypeError('.cursor only support .find method'); } } else { this.find(criteria); } var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('findCursor', this._collection.collectionName, conds, options); return this._collection.findCursor(conds, options); }; /** * Executes the query as a findOne() operation. * * Passing a `callback` executes the query. * * ####Example * * query.findOne().where('name', /^Burning/); * * query.findOne({ name: /^Burning/ }) * * query.findOne({ name: /^Burning/ }, callback); // executes * * query.findOne(function (err, doc) { * if (err) return handleError(err); * if (doc) { * // doc may be null if no document matched * * } * }); * * @param {Object|Query} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.findOne = function(criteria, callback) { this.op = 'findOne'; if ('function' === typeof criteria) { callback = criteria; criteria = undefined; } else if (Query.canMerge(criteria)) { this.merge(criteria); } if (!callback) return this; var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('findOne', this._collection.collectionName, conds, options); callback = this._wrapCallback('findOne', callback, { conditions: conds, options: options }); this._collection.findOne(conds, options, utils.tick(callback)); return this; }; /** * Exectues the query as a count() operation. * * Passing a `callback` executes the query. * * ####Example * * query.count().where('color', 'black').exec(callback); * * query.count({ color: 'black' }).count(callback) * * query.count({ color: 'black' }, callback) * * query.where('color', 'black').count(function (err, count) { * if (err) return handleError(err); * console.log('there are %d kittens', count); * }) * * @param {Object} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count * @api public */ Query.prototype.count = function(criteria, callback) { this.op = 'count'; this._validate(); if ('function' === typeof criteria) { callback = criteria; criteria = undefined; } else if (Query.canMerge(criteria)) { this.merge(criteria); } if (!callback) return this; var conds = this._conditions, options = this._optionsForExec(); debug('count', this._collection.collectionName, conds, options); callback = this._wrapCallback('count', callback, { conditions: conds, options: options }); this._collection.count(conds, options, utils.tick(callback)); return this; }; /** * Declares or executes a distinct() operation. * * Passing a `callback` executes the query. * * ####Example * * distinct(criteria, field, fn) * distinct(criteria, field) * distinct(field, fn) * distinct(field) * distinct(fn) * distinct() * * @param {Object|Query} [criteria] * @param {String} [field] * @param {Function} [callback] * @return {Query} this * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct * @api public */ Query.prototype.distinct = function(criteria, field, callback) { this.op = 'distinct'; this._validate(); if (!callback) { switch (typeof field) { case 'function': callback = field; if ('string' == typeof criteria) { field = criteria; criteria = undefined; } break; case 'undefined': case 'string': break; default: throw new TypeError('Invalid `field` argument. Must be string or function'); } switch (typeof criteria) { case 'function': callback = criteria; criteria = field = undefined; break; case 'string': field = criteria; criteria = undefined; break; } } if ('string' == typeof field) { this._distinct = field; } if (Query.canMerge(criteria)) { this.merge(criteria); } if (!callback) { return this; } if (!this._distinct) { throw new Error('No value for `distinct` has been declared'); } var conds = this._conditions, options = this._optionsForExec(); debug('distinct', this._collection.collectionName, conds, options); callback = this._wrapCallback('distinct', callback, { conditions: conds, options: options }); this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); return this; }; /** * Declare and/or execute this query as an update() operation. By default, * `update()` only modifies the _first_ document that matches `criteria`. * * _All paths passed that are not $atomic operations will become $set ops._ * * ####Example * * mquery({ _id: id }).update({ title: 'words' }, ...) * * becomes * * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) * * ####Note * * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. * * ####Note * * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. * * var q = mquery(collection).where({ _id: id }); * q.update({ $set: { name: 'bob' }}).update(); // not executed * * var q = mquery(collection).where({ _id: id }); * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe * * // keys that are not $atomic ops become $set. * // this executes the same command as the previous example. * q.update({ name: 'bob' }).where({ _id: id }).exec(); * * var q = mquery(collection).update(); // not executed * * // overwriting with empty docs * var q.where({ _id: id }).setOptions({ overwrite: true }) * q.update({ }, callback); // executes * * // multi update with overwrite to empty doc * var q = mquery(collection).where({ _id: id }); * q.setOptions({ multi: true, overwrite: true }) * q.update({ }); * q.update(callback); // executed * * // multi updates * mquery() * .collection(coll) * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) * // more multi updates * mquery({ }) * .collection(coll) * .setOptions({ multi: true }) * .update({ $set: { arr: [] }}, callback) * * // single update by default * mquery({ email: 'address@example.com' }) * .collection(coll) * .update({ $inc: { counter: 1 }}, callback) * * // summary * update(criteria, doc, opts, cb) // executes * update(criteria, doc, opts) * update(criteria, doc, cb) // executes * update(criteria, doc) * update(doc, cb) // executes * update(doc) * update(cb) // executes * update(true) // executes (unsafe write) * update() * * @param {Object} [criteria] * @param {Object} [doc] the update command * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.update = function update(criteria, doc, options, callback) { var force; switch (arguments.length) { case 3: if ('function' == typeof options) { callback = options; options = undefined; } break; case 2: if ('function' == typeof doc) { callback = doc; doc = criteria; criteria = undefined; } break; case 1: switch (typeof criteria) { case 'function': callback = criteria; criteria = options = doc = undefined; break; case 'boolean': // execution with no callback (unsafe write) force = criteria; criteria = undefined; break; default: doc = criteria; criteria = options = undefined; break; } } return _update(this, 'update', criteria, doc, options, force, callback); }; /** * Declare and/or execute this query as an `updateMany()` operation. Identical * to `update()` except `updateMany()` will update _all_ documents that match * `criteria`, rather than just the first one. * * _All paths passed that are not $atomic operations will become $set ops._ * * ####Example * * // Update every document whose `title` contains 'test' * mquery().updateMany({ title: /test/ }, { year: 2017 }) * * @param {Object} [criteria] * @param {Object} [doc] the update command * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.updateMany = function updateMany(criteria, doc, options, callback) { var force; switch (arguments.length) { case 3: if ('function' == typeof options) { callback = options; options = undefined; } break; case 2: if ('function' == typeof doc) { callback = doc; doc = criteria; criteria = undefined; } break; case 1: switch (typeof criteria) { case 'function': callback = criteria; criteria = options = doc = undefined; break; case 'boolean': // execution with no callback (unsafe write) force = criteria; criteria = undefined; break; default: doc = criteria; criteria = options = undefined; break; } } return _update(this, 'updateMany', criteria, doc, options, force, callback); }; /** * Declare and/or execute this query as an `updateOne()` operation. Identical * to `update()` except `updateOne()` will _always_ update just one document, * regardless of the `multi` option. * * _All paths passed that are not $atomic operations will become $set ops._ * * ####Example * * // Update the first document whose `title` contains 'test' * mquery().updateMany({ title: /test/ }, { year: 2017 }) * * @param {Object} [criteria] * @param {Object} [doc] the update command * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.updateOne = function updateOne(criteria, doc, options, callback) { var force; switch (arguments.length) { case 3: if ('function' == typeof options) { callback = options; options = undefined; } break; case 2: if ('function' == typeof doc) { callback = doc; doc = criteria; criteria = undefined; } break; case 1: switch (typeof criteria) { case 'function': callback = criteria; criteria = options = doc = undefined; break; case 'boolean': // execution with no callback (unsafe write) force = criteria; criteria = undefined; break; default: doc = criteria; criteria = options = undefined; break; } } return _update(this, 'updateOne', criteria, doc, options, force, callback); }; /** * Declare and/or execute this query as an `replaceOne()` operation. Similar * to `updateOne()`, except `replaceOne()` is not allowed to use atomic * modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always * replace the existing doc. * * ####Example * * // Replace the document with `_id` 1 with `{ _id: 1, year: 2017 }` * mquery().replaceOne({ _id: 1 }, { year: 2017 }) * * @param {Object} [criteria] * @param {Object} [doc] the update command * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.replaceOne = function replaceOne(criteria, doc, options, callback) { var force; switch (arguments.length) { case 3: if ('function' == typeof options) { callback = options; options = undefined; } break; case 2: if ('function' == typeof doc) { callback = doc; doc = criteria; criteria = undefined; } break; case 1: switch (typeof criteria) { case 'function': callback = criteria; criteria = options = doc = undefined; break; case 'boolean': // execution with no callback (unsafe write) force = criteria; criteria = undefined; break; default: doc = criteria; criteria = options = undefined; break; } } this.setOptions({ overwrite: true }); return _update(this, 'replaceOne', criteria, doc, options, force, callback); }; /*! * Internal helper for update, updateMany, updateOne */ function _update(query, op, criteria, doc, options, force, callback) { query.op = op; if (Query.canMerge(criteria)) { query.merge(criteria); } if (doc) { query._mergeUpdate(doc); } if (utils.isObject(options)) { // { overwrite: true } query.setOptions(options); } // we are done if we don't have callback and they are // not forcing an unsafe write. if (!(force || callback)) { return query; } if (!query._update || !query.options.overwrite && 0 === utils.keys(query._update).length) { callback && utils.soon(callback.bind(null, null, 0)); return query; } options = query._optionsForExec(); if (!callback) options.safe = false; criteria = query._conditions; doc = query._updateForExec(); debug('update', query._collection.collectionName, criteria, doc, options); callback = query._wrapCallback(op, callback, { conditions: criteria, doc: doc, options: options }); query._collection[op](criteria, doc, options, utils.tick(callback)); return query; } /** * Declare and/or execute this query as a remove() operation. * * ####Example * * mquery(collection).remove({ artist: 'Anne Murray' }, callback) * * ####Note * * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. * * // not executed * var query = mquery(collection).remove({ name: 'Anne Murray' }) * * // executed * mquery(collection).remove({ name: 'Anne Murray' }, callback) * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) * * // executed without a callback (unsafe write) * query.exec() * * // summary * query.remove(conds, fn); // executes * query.remove(conds) * query.remove(fn) // executes * query.remove() * * @param {Object|Query} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.remove = function(criteria, callback) { this.op = 'remove'; var force; if ('function' === typeof criteria) { callback = criteria; criteria = undefined; } else if (Query.canMerge(criteria)) { this.merge(criteria); } else if (true === criteria) { force = criteria; criteria = undefined; } if (!(force || callback)) return this; var options = this._optionsForExec(); if (!callback) options.safe = false; var conds = this._conditions; debug('remove', this._collection.collectionName, conds, options); callback = this._wrapCallback('remove', callback, { conditions: conds, options: options }); this._collection.remove(conds, options, utils.tick(callback)); return this; }; /** * Declare and/or execute this query as a `deleteOne()` operation. Behaves like * `remove()`, except for ignores the `justOne` option and always deletes at * most one document. * * ####Example * * mquery(collection).deleteOne({ artist: 'Anne Murray' }, callback) * * @param {Object|Query} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.deleteOne = function(criteria, callback) { this.op = 'deleteOne'; var force; if ('function' === typeof criteria) { callback = criteria; criteria = undefined; } else if (Query.canMerge(criteria)) { this.merge(criteria); } else if (true === criteria) { force = criteria; criteria = undefined; } if (!(force || callback)) return this; var options = this._optionsForExec(); if (!callback) options.safe = false; delete options.justOne; var conds = this._conditions; debug('deleteOne', this._collection.collectionName, conds, options); callback = this._wrapCallback('deleteOne', callback, { conditions: conds, options: options }); this._collection.deleteOne(conds, options, utils.tick(callback)); return this; }; /** * Declare and/or execute this query as a `deleteMany()` operation. Behaves like * `remove()`, except for ignores the `justOne` option and always deletes * _every_ document that matches `criteria`. * * ####Example * * mquery(collection).deleteMany({ artist: 'Anne Murray' }, callback) * * @param {Object|Query} [criteria] mongodb selector * @param {Function} [callback] * @return {Query} this * @api public */ Query.prototype.deleteMany = function(criteria, callback) { this.op = 'deleteMany'; var force; if ('function' === typeof criteria) { callback = criteria; criteria = undefined; } else if (Query.canMerge(criteria)) { this.merge(criteria); } else if (true === criteria) { force = criteria; criteria = undefined; } if (!(force || callback)) return this; var options = this._optionsForExec(); if (!callback) options.safe = false; delete options.justOne; var conds = this._conditions; debug('deleteOne', this._collection.collectionName, conds, options); callback = this._wrapCallback('deleteOne', callback, { conditions: conds, options: options }); this._collection.deleteMany(conds, options, utils.tick(callback)); return this; }; /** * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. * * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. * * ####Available options * * - `new`: bool - true to return the modified document rather than the original. defaults to true * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * * ####Examples * * query.findOneAndUpdate(conditions, update, options, callback) // executes * query.findOneAndUpdate(conditions, update, options) // returns Query * query.findOneAndUpdate(conditions, update, callback) // executes * query.findOneAndUpdate(conditions, update) // returns Query * query.findOneAndUpdate(update, callback) // returns Query * query.findOneAndUpdate(update) // returns Query * query.findOneAndUpdate(callback) // executes * query.findOneAndUpdate() // returns Query * * @param {Object|Query} [query] * @param {Object} [doc] * @param {Object} [options] * @param {Function} [callback] * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @return {Query} this * @api public */ Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { this.op = 'findOneAndUpdate'; this._validate(); switch (arguments.length) { case 3: if ('function' == typeof options) { callback = options; options = {}; } break; case 2: if ('function' == typeof doc) { callback = doc; doc = criteria; criteria = undefined; } options = undefined; break; case 1: if ('function' == typeof criteria) { callback = criteria; criteria = options = doc = undefined; } else { doc = criteria; criteria = options = undefined; } } if (Query.canMerge(criteria)) { this.merge(criteria); } // apply doc if (doc) { this._mergeUpdate(doc); } options && this.setOptions(options); if (!callback) return this; return this._findAndModify('update', callback); }; /** * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. * * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. * * ####Available options * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * * ####Examples * * A.where().findOneAndRemove(conditions, options, callback) // executes * A.where().findOneAndRemove(conditions, options) // return Query * A.where().findOneAndRemove(conditions, callback) // executes * A.where().findOneAndRemove(conditions) // returns Query * A.where().findOneAndRemove(callback) // executes * A.where().findOneAndRemove() // returns Query * A.where().findOneAndDelete() // alias of .findOneAndRemove() * * @param {Object} [conditions] * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ Query.prototype.findOneAndRemove = Query.prototype.findOneAndDelete = function(conditions, options, callback) { this.op = 'findOneAndRemove'; this._validate(); if ('function' == typeof options) { callback = options; options = undefined; } else if ('function' == typeof conditions) { callback = conditions; conditions = undefined; } // apply conditions if (Query.canMerge(conditions)) { this.merge(conditions); } // apply options options && this.setOptions(options); if (!callback) return this; return this._findAndModify('remove', callback); }; /** * _findAndModify * * @param {String} type - either "remove" or "update" * @param {Function} callback * @api private */ Query.prototype._findAndModify = function(type, callback) { assert.equal('function', typeof callback); var options = this._optionsForExec(); var fields; var doc; if ('remove' == type) { options.remove = true; } else { if (!('new' in options)) options.new = true; if (!('upsert' in options)) options.upsert = false; doc = this._updateForExec(); if (!doc) { if (options.upsert) { // still need to do the upsert to empty doc doc = { $set: {} }; } else { return this.findOne(callback); } } } fields = this._fieldsForExec(); if (fields != null) { if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } } var conds = this._conditions; debug('findAndModify', this._collection.collectionName, conds, doc, options); callback = this._wrapCallback('findAndModify', callback, { conditions: conds, doc: doc, options: options }); this._collection.findAndModify(conds, doc, options, utils.tick(callback)); return this; }; /** * Wrap callback to add tracing * * @param {Function} callback * @param {Object} [queryInfo] * @api private */ Query.prototype._wrapCallback = function(method, callback, queryInfo) { var traceFunction = this._traceFunction || Query.traceFunction; if (traceFunction) { queryInfo.collectionName = this._collection.collectionName; var traceCallback = traceFunction && traceFunction.call(null, method, queryInfo, this); var startTime = new Date().getTime(); return function wrapperCallback(err, result) { if (traceCallback) { var millis = new Date().getTime() - startTime; traceCallback.call(null, err, result, millis); } if (callback) { callback.apply(null, arguments); } }; } return callback; }; /** * Add trace function that gets called when the query is executed. * The function will be called with (method, queryInfo, query) and * should return a callback function which will be called * with (err, result, millis) when the query is complete. * * queryInfo is an object containing: { * collectionName: , * conditions: , * options: , * doc: [document to update, if applicable] * } * * NOTE: Does not trace stream queries. * * @param {Function} traceFunction * @return {Query} this * @api public */ Query.prototype.setTraceFunction = function(traceFunction) { this._traceFunction = traceFunction; return this; }; /** * Executes the query * * ####Examples * * query.exec(); * query.exec(callback); * query.exec('update'); * query.exec('find', callback); * * @param {String|Function} [operation] * @param {Function} [callback] * @api public */ Query.prototype.exec = function exec(op, callback) { switch (typeof op) { case 'function': callback = op; op = null; break; case 'string': this.op = op; break; } assert.ok(this.op, 'Missing query type: (find, update, etc)'); if ('update' == this.op || 'remove' == this.op) { callback || (callback = true); } var _this = this; if ('function' == typeof callback) { this[this.op](callback); } else { return new Query.Promise(function(success, error) { _this[_this.op](function(err, val) { if (err) error(err); else success(val); success = error = null; }); }); } }; /** * Returns a thunk which when called runs this.exec() * * The thunk receives a callback function which will be * passed to `this.exec()` * * @return {Function} * @api public */ Query.prototype.thunk = function() { var _this = this; return function(cb) { _this.exec(cb); }; }; /** * Executes the query returning a `Promise` which will be * resolved with either the doc(s) or rejected with the error. * * @param {Function} [resolve] * @param {Function} [reject] * @return {Promise} * @api public */ Query.prototype.then = function(resolve, reject) { var _this = this; var promise = new Query.Promise(function(success, error) { _this.exec(function(err, val) { if (err) error(err); else success(val); success = error = null; }); }); return promise.then(resolve, reject); }; /** * Returns a stream for the given find query. * * @throws Error if operation is not a find * @returns {Stream} Node 0.8 style */ Query.prototype.stream = function(streamOptions) { if ('find' != this.op) throw new Error('stream() is only available for find'); var conds = this._conditions; var options = this._optionsForExec(); if (this.$useProjection) { options.projection = this._fieldsForExec(); } else { options.fields = this._fieldsForExec(); } debug('stream', this._collection.collectionName, conds, options, streamOptions); return this._collection.findStream(conds, options, streamOptions); }; /** * Determines if field selection has been made. * * @return {Boolean} * @api public */ Query.prototype.selected = function selected() { return !!(this._fields && Object.keys(this._fields).length > 0); }; /** * Determines if inclusive field selection has been made. * * query.selectedInclusively() // false * query.select('name') * query.selectedInclusively() // true * query.selectedExlusively() // false * * @returns {Boolean} */ Query.prototype.selectedInclusively = function selectedInclusively() { if (!this._fields) return false; var keys = Object.keys(this._fields); if (0 === keys.length) return false; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (0 === this._fields[key]) return false; if (this._fields[key] && typeof this._fields[key] === 'object' && this._fields[key].$meta) { return false; } } return true; }; /** * Determines if exclusive field selection has been made. * * query.selectedExlusively() // false * query.select('-name') * query.selectedExlusively() // true * query.selectedInclusively() // false * * @returns {Boolean} */ Query.prototype.selectedExclusively = function selectedExclusively() { if (!this._fields) return false; var keys = Object.keys(this._fields); if (0 === keys.length) return false; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (0 === this._fields[key]) return true; } return false; }; /** * Merges `doc` with the current update object. * * @param {Object} doc */ Query.prototype._mergeUpdate = function(doc) { if (!this._update) this._update = {}; if (doc instanceof Query) { if (doc._update) { utils.mergeClone(this._update, doc._update); } } else { utils.mergeClone(this._update, doc); } }; /** * Returns default options. * * @return {Object} * @api private */ Query.prototype._optionsForExec = function() { var options = utils.clone(this.options); return options; }; /** * Returns fields selection for this query. * * @return {Object} * @api private */ Query.prototype._fieldsForExec = function() { return utils.clone(this._fields); }; /** * Return an update document with corrected $set operations. * * @api private */ Query.prototype._updateForExec = function() { var update = utils.clone(this._update), ops = utils.keys(update), i = ops.length, ret = {}; while (i--) { var op = ops[i]; if (this.options.overwrite) { ret[op] = update[op]; continue; } if ('$' !== op[0]) { // fix up $set sugar if (!ret.$set) { if (update.$set) { ret.$set = update.$set; } else { ret.$set = {}; } } ret.$set[op] = update[op]; ops.splice(i, 1); if (!~ops.indexOf('$set')) ops.push('$set'); } else if ('$set' === op) { if (!ret.$set) { ret[op] = update[op]; } } else { ret[op] = update[op]; } } this._compiledUpdate = ret; return ret; }; /** * Make sure _path is set. * * @parmam {String} method */ Query.prototype._ensurePath = function(method) { if (!this._path) { var msg = method + '() must be used after where() ' + 'when called with these arguments'; throw new Error(msg); } }; /*! * Permissions */ Query.permissions = require('./permissions'); Query._isPermitted = function(a, b) { var denied = Query.permissions[b]; if (!denied) return true; return true !== denied[a]; }; Query.prototype._validate = function(action) { var fail; var validator; if (undefined === action) { validator = Query.permissions[this.op]; if ('function' != typeof validator) return true; fail = validator(this); } else if (!Query._isPermitted(action, this.op)) { fail = action; } if (fail) { throw new Error(fail + ' cannot be used with ' + this.op); } }; /** * Determines if `conds` can be merged using `mquery().merge()` * * @param {Object} conds * @return {Boolean} */ Query.canMerge = function(conds) { return conds instanceof Query || utils.isObject(conds); }; /** * Set a trace function that will get called whenever a * query is executed. * * See `setTraceFunction()` for details. * * @param {Object} conds * @return {Boolean} */ Query.setGlobalTraceFunction = function(traceFunction) { Query.traceFunction = traceFunction; }; /*! * Exports. */ Query.utils = utils; Query.env = require('./env'); Query.Collection = require('./collection'); Query.BaseCollection = require('./collection/collection'); Query.Promise = require('bluebird'); module.exports = exports = Query; // TODO // test utils },{"./collection":388,"./collection/collection":387,"./env":390,"./permissions":392,"./utils":393,"assert":89,"bluebird":94,"debug":394,"sliced":402,"util":414}],392:[function(require,module,exports){ 'use strict'; var denied = exports; denied.distinct = function(self) { if (self._fields && Object.keys(self._fields).length > 0) { return 'field selection and slice'; } var keys = Object.keys(denied.distinct); var err; keys.every(function(option) { if (self.options[option]) { err = option; return false; } return true; }); return err; }; denied.distinct.select = denied.distinct.slice = denied.distinct.sort = denied.distinct.limit = denied.distinct.skip = denied.distinct.batchSize = denied.distinct.comment = denied.distinct.maxScan = denied.distinct.snapshot = denied.distinct.hint = denied.distinct.tailable = true; // aggregation integration denied.findOneAndUpdate = denied.findOneAndRemove = function(self) { var keys = Object.keys(denied.findOneAndUpdate); var err; keys.every(function(option) { if (self.options[option]) { err = option; return false; } return true; }); return err; }; denied.findOneAndUpdate.limit = denied.findOneAndUpdate.skip = denied.findOneAndUpdate.batchSize = denied.findOneAndUpdate.maxScan = denied.findOneAndUpdate.snapshot = denied.findOneAndUpdate.hint = denied.findOneAndUpdate.tailable = denied.findOneAndUpdate.comment = true; denied.count = function(self) { if (self._fields && Object.keys(self._fields).length > 0) { return 'field selection and slice'; } var keys = Object.keys(denied.count); var err; keys.every(function(option) { if (self.options[option]) { err = option; return false; } return true; }); return err; }; denied.count.slice = denied.count.batchSize = denied.count.comment = denied.count.maxScan = denied.count.snapshot = denied.count.tailable = true; },{}],393:[function(require,module,exports){ (function (process,setImmediate){ 'use strict'; /*! * Module dependencies. */ var Buffer = require('safe-buffer').Buffer; var RegExpClone = require('regexp-clone'); var specialProperties = ['__proto__', 'constructor', 'prototype']; /** * Clones objects * * @param {Object} obj the object to clone * @param {Object} options * @return {Object} the cloned object * @api private */ var clone = exports.clone = function clone(obj, options) { if (obj === undefined || obj === null) return obj; if (Array.isArray(obj)) return exports.cloneArray(obj, options); if (obj.constructor) { if (/ObjectI[dD]$/.test(obj.constructor.name)) { return 'function' == typeof obj.clone ? obj.clone() : new obj.constructor(obj.id); } if (obj.constructor.name === 'ReadPreference') { return new obj.constructor(obj.mode, clone(obj.tags, options)); } if ('Binary' == obj._bsontype && obj.buffer && obj.value) { return 'function' == typeof obj.clone ? obj.clone() : new obj.constructor(obj.value(true), obj.sub_type); } if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) return new obj.constructor(+obj); if ('RegExp' === obj.constructor.name) return RegExpClone(obj); if ('Buffer' === obj.constructor.name) return exports.cloneBuffer(obj); } if (isObject(obj)) return exports.cloneObject(obj, options); if (obj.valueOf) return obj.valueOf(); }; /*! * ignore */ exports.cloneObject = function cloneObject(obj, options) { var minimize = options && options.minimize; var ret = {}; var hasKeys; var val; var k; for (k in obj) { // Not technically prototype pollution because this wouldn't merge properties // onto `Object.prototype`, but avoid properties like __proto__ as a precaution. if (specialProperties.indexOf(k) !== -1) { continue; } val = clone(obj[k], options); if (!minimize || ('undefined' !== typeof val)) { hasKeys || (hasKeys = true); ret[k] = val; } } return minimize ? hasKeys && ret : ret; }; exports.cloneArray = function cloneArray(arr, options) { var ret = []; for (var i = 0, l = arr.length; i < l; i++) ret.push(clone(arr[i], options)); return ret; }; /** * process.nextTick helper. * * Wraps the given `callback` in a try/catch. If an error is * caught it will be thrown on nextTick. * * node-mongodb-native had a habit of state corruption when * an error was immediately thrown from within a collection * method (find, update, etc) callback. * * @param {Function} [callback] * @api private */ exports.tick = function tick(callback) { if ('function' !== typeof callback) return; return function() { // callbacks should always be fired on the next // turn of the event loop. A side benefit is // errors thrown from executing the callback // will not cause drivers state to be corrupted // which has historically been a problem. var args = arguments; soon(function() { callback.apply(this, args); }); }; }; /** * Merges `from` into `to` without overwriting existing properties. * * @param {Object} to * @param {Object} from * @api private */ exports.merge = function merge(to, from) { var keys = Object.keys(from), i = keys.length, key; while (i--) { key = keys[i]; if (specialProperties.indexOf(key) !== -1) { continue; } if ('undefined' === typeof to[key]) { to[key] = from[key]; } else { if (exports.isObject(from[key])) { merge(to[key], from[key]); } else { to[key] = from[key]; } } } }; /** * Same as merge but clones the assigned values. * * @param {Object} to * @param {Object} from * @api private */ exports.mergeClone = function mergeClone(to, from) { var keys = Object.keys(from), i = keys.length, key; while (i--) { key = keys[i]; if ('undefined' === typeof to[key]) { to[key] = clone(from[key]); } else { if (exports.isObject(from[key])) { mergeClone(to[key], from[key]); } else { to[key] = clone(from[key]); } } } }; /** * Read pref helper (mongo 2.2 drivers support this) * * Allows using aliases instead of full preference names: * * p primary * pp primaryPreferred * s secondary * sp secondaryPreferred * n nearest * * @param {String} pref */ exports.readPref = function readPref(pref) { switch (pref) { case 'p': pref = 'primary'; break; case 'pp': pref = 'primaryPreferred'; break; case 's': pref = 'secondary'; break; case 'sp': pref = 'secondaryPreferred'; break; case 'n': pref = 'nearest'; break; } return pref; }; /** * Read Concern helper (mongo 3.2 drivers support this) * * Allows using string to specify read concern level: * * local 3.2+ * available 3.6+ * majority 3.2+ * linearizable 3.4+ * snapshot 4.0+ * * @param {String|Object} concern */ exports.readConcern = function readConcern(concern) { if ('string' === typeof concern) { switch (concern) { case 'l': concern = 'local'; break; case 'a': concern = 'available'; break; case 'm': concern = 'majority'; break; case 'lz': concern = 'linearizable'; break; case 's': concern = 'snapshot'; break; } concern = { level: concern }; } return concern; }; /** * Object.prototype.toString.call helper */ var _toString = Object.prototype.toString; exports.toString = function(arg) { return _toString.call(arg); }; /** * Determines if `arg` is an object. * * @param {Object|Array|String|Function|RegExp|any} arg * @return {Boolean} */ var isObject = exports.isObject = function(arg) { return '[object Object]' == exports.toString(arg); }; /** * Determines if `arg` is an array. * * @param {Object} * @return {Boolean} * @see nodejs utils */ exports.isArray = function(arg) { return Array.isArray(arg) || 'object' == typeof arg && '[object Array]' == exports.toString(arg); }; /** * Object.keys helper */ exports.keys = Object.keys || function(obj) { var keys = []; for (var k in obj) if (obj.hasOwnProperty(k)) { keys.push(k); } return keys; }; /** * Basic Object.create polyfill. * Only one argument is supported. * * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create */ exports.create = 'function' == typeof Object.create ? Object.create : create; function create(proto) { if (arguments.length > 1) { throw new Error('Adding properties is not supported'); } function F() {} F.prototype = proto; return new F; } /** * inheritance */ exports.inherits = function(ctor, superCtor) { ctor.prototype = exports.create(superCtor.prototype); ctor.prototype.constructor = ctor; }; /** * nextTick helper * compat with node 0.10 which behaves differently than previous versions */ var soon = exports.soon = 'function' == typeof setImmediate ? setImmediate : process.nextTick; /** * Clones the contents of a buffer. * * @param {Buffer} buff * @return {Buffer} */ exports.cloneBuffer = function(buff) { var dupe = Buffer.alloc(buff.length); buff.copy(dupe, 0, 0, buff.length); return dupe; }; /** * Check if this object is an arguments object * * @param {Any} v * @return {Boolean} */ exports.isArgumentsObject = function(v) { return Object.prototype.toString.call(v) === '[object Arguments]'; }; }).call(this,require('_process'),require("timers").setImmediate) },{"_process":399,"regexp-clone":400,"safe-buffer":396,"timers":403}],394:[function(require,module,exports){ (function (process){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } }).call(this,require('_process')) },{"./debug":395,"_process":399}],395:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * Active `debug` instances. */ exports.instances = []; /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { var prevTime; function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); debug.destroy = destroy; // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } exports.instances.push(debug); return debug; } function destroy () { var index = exports.instances.indexOf(this); if (index !== -1) { exports.instances.splice(index, 1); return true; } else { return false; } } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var i; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } for (i = 0; i < exports.instances.length; i++) { var instance = exports.instances[i]; instance.enabled = exports.enabled(instance.namespace); } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":397}],396:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":115}],397:[function(require,module,exports){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } },{}],398:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}],399:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],400:[function(require,module,exports){ const toString = Object.prototype.toString; function isRegExp (o) { return 'object' == typeof o && '[object RegExp]' == toString.call(o); } module.exports = exports = function (regexp) { if (!isRegExp(regexp)) { throw new TypeError('Not a RegExp'); } const flags = []; if (regexp.global) flags.push('g'); if (regexp.multiline) flags.push('m'); if (regexp.ignoreCase) flags.push('i'); if (regexp.dotAll) flags.push('s'); if (regexp.unicode) flags.push('u'); if (regexp.sticky) flags.push('y'); const result = new RegExp(regexp.source, flags.join('')); if (typeof regexp.lastIndex === 'number') { result.lastIndex = regexp.lastIndex; } return result; } },{}],401:[function(require,module,exports){ /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } SafeBuffer.prototype = Object.create(Buffer.prototype) // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":115}],402:[function(require,module,exports){ /** * An Array.prototype.slice.call(arguments) alternative * * @param {Object} args something with a length * @param {Number} slice * @param {Number} sliceEnd * @api public */ module.exports = function (args, slice, sliceEnd) { var ret = []; var len = args.length; if (0 === len) return ret; var start = slice < 0 ? Math.max(0, slice + len) : slice || 0; if (sliceEnd !== undefined) { len = sliceEnd < 0 ? sliceEnd + len : sliceEnd } while (len-- > start) { ret[len - start] = args[len]; } return ret; } },{}],403:[function(require,module,exports){ (function (setImmediate,clearImmediate){ var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { if (immediateIds[id]) { // fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu if (args) { fn.apply(null, args); } else { fn.call(null); } // Prevent ids from leaking exports.clearImmediate(id); } }); return id; }; exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { delete immediateIds[id]; }; }).call(this,require("timers").setImmediate,require("timers").clearImmediate) },{"process/browser.js":399,"timers":403}],404:[function(require,module,exports){ module.exports={ "10*": { "value": 10, "ucum": "1" }, "10^": { "value": 10, "ucum": "1" }, "[pi]": { "value": 3.141592653589793, "ucum": "1" }, "%": { "value": 1, "ucum": "10*-2" }, "[ppth]": { "value": 1, "ucum": "10*-3" }, "[ppm]": { "value": 1, "ucum": "10*-6" }, "[ppb]": { "value": 1, "ucum": "10*-9" }, "[pptr]": { "value": 1, "ucum": "10*-12" }, "mol": { "value": 6.0221367, "ucum": "10*23" }, "sr": { "value": 1, "ucum": "rad2" }, "Hz": { "value": 1, "ucum": "s-1" }, "N": { "value": 1, "ucum": "kg.m/s2" }, "Pa": { "value": 1, "ucum": "N/m2" }, "J": { "value": 1, "ucum": "N.m" }, "W": { "value": 1, "ucum": "J/s" }, "A": { "value": 1, "ucum": "C/s" }, "V": { "value": 1, "ucum": "J/C" }, "F": { "value": 1, "ucum": "C/V" }, "Ohm": { "value": 1, "ucum": "V/A" }, "S": { "value": 1, "ucum": "Ohm-1" }, "Wb": { "value": 1, "ucum": "V.s" }, "Cel": { "value": null, "ucum": "cel(1 K)" }, "T": { "value": 1, "ucum": "Wb/m2" }, "H": { "value": 1, "ucum": "Wb/A" }, "lm": { "value": 1, "ucum": "cd.sr" }, "lx": { "value": 1, "ucum": "lm/m2" }, "Bq": { "value": 1, "ucum": "s-1" }, "Gy": { "value": 1, "ucum": "J/kg" }, "Sv": { "value": 1, "ucum": "J/kg" }, "gon": { "value": 0.9, "ucum": "deg" }, "deg": { "value": 2, "ucum": "[pi].rad/360" }, "'": { "value": 1, "ucum": "deg/60" }, "''": { "value": 1, "ucum": "'/60" }, "l": { "value": 1, "ucum": "dm3" }, "L": { "value": 1, "ucum": "l" }, "ar": { "value": 100, "ucum": "m2" }, "min": { "value": 60, "ucum": "s" }, "h": { "value": 60, "ucum": "min" }, "d": { "value": 24, "ucum": "h" }, "a_t": { "value": 365.24219, "ucum": "d" }, "a_j": { "value": 365.25, "ucum": "d" }, "a_g": { "value": 365.2425, "ucum": "d" }, "a": { "value": 1, "ucum": "a_j" }, "wk": { "value": 7, "ucum": "d" }, "mo_s": { "value": 29.53059, "ucum": "d" }, "mo_j": { "value": 1, "ucum": "a_j/12" }, "mo_g": { "value": 1, "ucum": "a_g/12" }, "mo": { "value": 1, "ucum": "mo_j" }, "t": { "value": 1000, "ucum": "kg" }, "bar": { "value": 100000, "ucum": "Pa" }, "u": { "value": 1.6605402e-24, "ucum": "g" }, "eV": { "value": 1, "ucum": "[e].V" }, "AU": { "value": 149597.870691, "ucum": "Mm" }, "pc": { "value": 30856780000000000, "ucum": "m" }, "[c]": { "value": 299792458, "ucum": "m/s" }, "[h]": { "value": 6.6260755e-24, "ucum": "J.s" }, "[k]": { "value": 1.380658e-23, "ucum": "J/K" }, "[eps_0]": { "value": 8.854187817e-12, "ucum": "F/m" }, "[mu_0]": { "value": 1, "ucum": "4.[pi].10*-7.N/A2" }, "[e]": { "value": 1.60217733e-19, "ucum": "C" }, "[m_e]": { "value": 9.1093897e-28, "ucum": "g" }, "[m_p]": { "value": 1.6726231e-24, "ucum": "g" }, "[G]": { "value": 6.67259e-11, "ucum": "m3.kg-1.s-2" }, "[g]": { "value": 9.80665, "ucum": "m/s2" }, "atm": { "value": 101325, "ucum": "Pa" }, "[ly]": { "value": 1, "ucum": "[c].a_j" }, "gf": { "value": 1, "ucum": "g.[g]" }, "[lbf_av]": { "value": 1, "ucum": "[lb_av].[g]" }, "Ky": { "value": 1, "ucum": "cm-1" }, "Gal": { "value": 1, "ucum": "cm/s2" }, "dyn": { "value": 1, "ucum": "g.cm/s2" }, "erg": { "value": 1, "ucum": "dyn.cm" }, "P": { "value": 1, "ucum": "dyn.s/cm2" }, "Bi": { "value": 10, "ucum": "A" }, "St": { "value": 1, "ucum": "cm2/s" }, "Mx": { "value": 1e-8, "ucum": "Wb" }, "G": { "value": 0.0001, "ucum": "T" }, "Oe": { "value": 250, "ucum": "/[pi].A/m" }, "Gb": { "value": 1, "ucum": "Oe.cm" }, "sb": { "value": 1, "ucum": "cd/cm2" }, "Lmb": { "value": 1, "ucum": "cd/cm2/[pi]" }, "ph": { "value": 0.0001, "ucum": "lx" }, "Ci": { "value": 37000000000, "ucum": "Bq" }, "R": { "value": 0.000258, "ucum": "C/kg" }, "RAD": { "value": 100, "ucum": "erg/g" }, "REM": { "value": 1, "ucum": "RAD" }, "[in_i]": { "value": 2.54, "ucum": "cm" }, "[ft_i]": { "value": 12, "ucum": "[in_i]" }, "[yd_i]": { "value": 3, "ucum": "[ft_i]" }, "[mi_i]": { "value": 5280, "ucum": "[ft_i]" }, "[fth_i]": { "value": 6, "ucum": "[ft_i]" }, "[nmi_i]": { "value": 1852, "ucum": "m" }, "[kn_i]": { "value": 1, "ucum": "[nmi_i]/h" }, "[sin_i]": { "value": 1, "ucum": "[in_i]2" }, "[sft_i]": { "value": 1, "ucum": "[ft_i]2" }, "[syd_i]": { "value": 1, "ucum": "[yd_i]2" }, "[cin_i]": { "value": 1, "ucum": "[in_i]3" }, "[cft_i]": { "value": 1, "ucum": "[ft_i]3" }, "[cyd_i]": { "value": 1, "ucum": "[yd_i]3" }, "[bf_i]": { "value": 144, "ucum": "[in_i]3" }, "[cr_i]": { "value": 128, "ucum": "[ft_i]3" }, "[mil_i]": { "value": 0.001, "ucum": "[in_i]" }, "[cml_i]": { "value": 1, "ucum": "[pi]/4.[mil_i]2" }, "[hd_i]": { "value": 4, "ucum": "[in_i]" }, "[ft_us]": { "value": 1200, "ucum": "m/3937" }, "[yd_us]": { "value": 3, "ucum": "[ft_us]" }, "[in_us]": { "value": 1, "ucum": "[ft_us]/12" }, "[rd_us]": { "value": 16.5, "ucum": "[ft_us]" }, "[ch_us]": { "value": 4, "ucum": "[rd_us]" }, "[lk_us]": { "value": 1, "ucum": "[ch_us]/100" }, "[rch_us]": { "value": 100, "ucum": "[ft_us]" }, "[rlk_us]": { "value": 1, "ucum": "[rch_us]/100" }, "[fth_us]": { "value": 6, "ucum": "[ft_us]" }, "[fur_us]": { "value": 40, "ucum": "[rd_us]" }, "[mi_us]": { "value": 8, "ucum": "[fur_us]" }, "[acr_us]": { "value": 160, "ucum": "[rd_us]2" }, "[srd_us]": { "value": 1, "ucum": "[rd_us]2" }, "[smi_us]": { "value": 1, "ucum": "[mi_us]2" }, "[sct]": { "value": 1, "ucum": "[mi_us]2" }, "[twp]": { "value": 36, "ucum": "[sct]" }, "[mil_us]": { "value": 0.001, "ucum": "[in_us]" }, "[in_br]": { "value": 2.539998, "ucum": "cm" }, "[ft_br]": { "value": 12, "ucum": "[in_br]" }, "[rd_br]": { "value": 16.5, "ucum": "[ft_br]" }, "[ch_br]": { "value": 4, "ucum": "[rd_br]" }, "[lk_br]": { "value": 1, "ucum": "[ch_br]/100" }, "[fth_br]": { "value": 6, "ucum": "[ft_br]" }, "[pc_br]": { "value": 2.5, "ucum": "[ft_br]" }, "[yd_br]": { "value": 3, "ucum": "[ft_br]" }, "[mi_br]": { "value": 5280, "ucum": "[ft_br]" }, "[nmi_br]": { "value": 6080, "ucum": "[ft_br]" }, "[kn_br]": { "value": 1, "ucum": "[nmi_br]/h" }, "[acr_br]": { "value": 4840, "ucum": "[yd_br]2" }, "[gal_us]": { "value": 231, "ucum": "[in_i]3" }, "[bbl_us]": { "value": 42, "ucum": "[gal_us]" }, "[qt_us]": { "value": 1, "ucum": "[gal_us]/4" }, "[pt_us]": { "value": 1, "ucum": "[qt_us]/2" }, "[gil_us]": { "value": 1, "ucum": "[pt_us]/4" }, "[foz_us]": { "value": 1, "ucum": "[gil_us]/4" }, "[fdr_us]": { "value": 1, "ucum": "[foz_us]/8" }, "[min_us]": { "value": 1, "ucum": "[fdr_us]/60" }, "[crd_us]": { "value": 128, "ucum": "[ft_i]3" }, "[bu_us]": { "value": 2150.42, "ucum": "[in_i]3" }, "[gal_wi]": { "value": 1, "ucum": "[bu_us]/8" }, "[pk_us]": { "value": 1, "ucum": "[bu_us]/4" }, "[dqt_us]": { "value": 1, "ucum": "[pk_us]/8" }, "[dpt_us]": { "value": 1, "ucum": "[dqt_us]/2" }, "[tbs_us]": { "value": 1, "ucum": "[foz_us]/2" }, "[tsp_us]": { "value": 1, "ucum": "[tbs_us]/3" }, "[cup_us]": { "value": 16, "ucum": "[tbs_us]" }, "[foz_m]": { "value": 30, "ucum": "mL" }, "[cup_m]": { "value": 240, "ucum": "mL" }, "[tsp_m]": { "value": 5, "ucum": "mL" }, "[tbs_m]": { "value": 15, "ucum": "mL" }, "[gal_br]": { "value": 4.54609, "ucum": "l" }, "[pk_br]": { "value": 2, "ucum": "[gal_br]" }, "[bu_br]": { "value": 4, "ucum": "[pk_br]" }, "[qt_br]": { "value": 1, "ucum": "[gal_br]/4" }, "[pt_br]": { "value": 1, "ucum": "[qt_br]/2" }, "[gil_br]": { "value": 1, "ucum": "[pt_br]/4" }, "[foz_br]": { "value": 1, "ucum": "[gil_br]/5" }, "[fdr_br]": { "value": 1, "ucum": "[foz_br]/8" }, "[min_br]": { "value": 1, "ucum": "[fdr_br]/60" }, "[gr]": { "value": 64.79891, "ucum": "mg" }, "[lb_av]": { "value": 7000, "ucum": "[gr]" }, "[oz_av]": { "value": 1, "ucum": "[lb_av]/16" }, "[dr_av]": { "value": 1, "ucum": "[oz_av]/16" }, "[scwt_av]": { "value": 100, "ucum": "[lb_av]" }, "[lcwt_av]": { "value": 112, "ucum": "[lb_av]" }, "[ston_av]": { "value": 20, "ucum": "[scwt_av]" }, "[lton_av]": { "value": 20, "ucum": "[lcwt_av]" }, "[stone_av]": { "value": 14, "ucum": "[lb_av]" }, "[pwt_tr]": { "value": 24, "ucum": "[gr]" }, "[oz_tr]": { "value": 20, "ucum": "[pwt_tr]" }, "[lb_tr]": { "value": 12, "ucum": "[oz_tr]" }, "[sc_ap]": { "value": 20, "ucum": "[gr]" }, "[dr_ap]": { "value": 3, "ucum": "[sc_ap]" }, "[oz_ap]": { "value": 8, "ucum": "[dr_ap]" }, "[lb_ap]": { "value": 12, "ucum": "[oz_ap]" }, "[oz_m]": { "value": 28, "ucum": "g" }, "[lne]": { "value": 1, "ucum": "[in_i]/12" }, "[pnt]": { "value": 1, "ucum": "[lne]/6" }, "[pca]": { "value": 12, "ucum": "[pnt]" }, "[pnt_pr]": { "value": 0.013837, "ucum": "[in_i]" }, "[pca_pr]": { "value": 12, "ucum": "[pnt_pr]" }, "[pied]": { "value": 32.48, "ucum": "cm" }, "[pouce]": { "value": 1, "ucum": "[pied]/12" }, "[ligne]": { "value": 1, "ucum": "[pouce]/12" }, "[didot]": { "value": 1, "ucum": "[ligne]/6" }, "[cicero]": { "value": 12, "ucum": "[didot]" }, "[degF]": { "value": null, "ucum": "degf(5 K/9)" }, "[degR]": { "value": 5, "ucum": "K/9" }, "cal_[15]": { "value": 4.1858, "ucum": "J" }, "cal_[20]": { "value": 4.1819, "ucum": "J" }, "cal_m": { "value": 4.19002, "ucum": "J" }, "cal_IT": { "value": 4.1868, "ucum": "J" }, "cal_th": { "value": 4.184, "ucum": "J" }, "cal": { "value": 1, "ucum": "cal_th" }, "[Cal]": { "value": 1, "ucum": "kcal_th" }, "[Btu_39]": { "value": 1.05967, "ucum": "kJ" }, "[Btu_59]": { "value": 1.0548, "ucum": "kJ" }, "[Btu_60]": { "value": 1.05468, "ucum": "kJ" }, "[Btu_m]": { "value": 1.05587, "ucum": "kJ" }, "[Btu_IT]": { "value": 1.05505585262, "ucum": "kJ" }, "[Btu_th]": { "value": 1.05435, "ucum": "kJ" }, "[Btu]": { "value": 1, "ucum": "[Btu_th]" }, "[HP]": { "value": 550, "ucum": "[ft_i].[lbf_av]/s" }, "tex": { "value": 1, "ucum": "g/km" }, "[den]": { "value": 1, "ucum": "g/9/km" }, "m[H2O]": { "value": 9.80665, "ucum": "kPa" }, "m[Hg]": { "value": 133.322, "ucum": "kPa" }, "[in_i'H2O]": { "value": 1, "ucum": "m[H2O].[in_i]/m" }, "[in_i'Hg]": { "value": 1, "ucum": "m[Hg].[in_i]/m" }, "[PRU]": { "value": 1, "ucum": "mm[Hg].s/ml" }, "[wood'U]": { "value": 1, "ucum": "mm[Hg].min/L" }, "[diop]": { "value": 1, "ucum": "/m" }, "[p'diop]": { "value": null, "ucum": "100tan(1 rad)" }, "%[slope]": { "value": null, "ucum": "100tan(1 rad)" }, "[mesh_i]": { "value": 1, "ucum": "/[in_i]" }, "[Ch]": { "value": 1, "ucum": "mm/3" }, "[drp]": { "value": 1, "ucum": "ml/20" }, "[hnsf'U]": { "value": 1, "ucum": "1" }, "[MET]": { "value": 3.5, "ucum": "mL/min/kg" }, "[hp'_X]": { "value": null, "ucum": "hpX(1 1)" }, "[hp'_C]": { "value": null, "ucum": "hpC(1 1)" }, "[hp'_M]": { "value": null, "ucum": "hpM(1 1)" }, "[hp'_Q]": { "value": null, "ucum": "hpQ(1 1)" }, "[hp_X]": { "value": 1, "ucum": "1" }, "[hp_C]": { "value": 1, "ucum": "1" }, "[hp_M]": { "value": 1, "ucum": "1" }, "[hp_Q]": { "value": 1, "ucum": "1" }, "[kp_X]": { "value": 1, "ucum": "1" }, "[kp_C]": { "value": 1, "ucum": "1" }, "[kp_M]": { "value": 1, "ucum": "1" }, "[kp_Q]": { "value": 1, "ucum": "1" }, "eq": { "value": 1, "ucum": "mol" }, "osm": { "value": 1, "ucum": "mol" }, "[pH]": { "value": null, "ucum": "pH(1 mol/l)" }, "g%": { "value": 1, "ucum": "g/dl" }, "[S]": { "value": 1, "ucum": "10*-13.s" }, "[HPF]": { "value": 1, "ucum": "1" }, "[LPF]": { "value": 100, "ucum": "1" }, "kat": { "value": 1, "ucum": "mol/s" }, "U": { "value": 1, "ucum": "umol/min" }, "[iU]": { "value": 1, "ucum": "1" }, "[IU]": { "value": 1, "ucum": "[iU]" }, "[arb'U]": { "value": 1, "ucum": "1" }, "[USP'U]": { "value": 1, "ucum": "1" }, "[GPL'U]": { "value": 1, "ucum": "1" }, "[MPL'U]": { "value": 1, "ucum": "1" }, "[APL'U]": { "value": 1, "ucum": "1" }, "[beth'U]": { "value": 1, "ucum": "1" }, "[anti'Xa'U]": { "value": 1, "ucum": "1" }, "[todd'U]": { "value": 1, "ucum": "1" }, "[dye'U]": { "value": 1, "ucum": "1" }, "[smgy'U]": { "value": 1, "ucum": "1" }, "[bdsk'U]": { "value": 1, "ucum": "1" }, "[ka'U]": { "value": 1, "ucum": "1" }, "[knk'U]": { "value": 1, "ucum": "1" }, "[mclg'U]": { "value": 1, "ucum": "1" }, "[tb'U]": { "value": 1, "ucum": "1" }, "[CCID_50]": { "value": 1, "ucum": "1" }, "[TCID_50]": { "value": 1, "ucum": "1" }, "[EID_50]": { "value": 1, "ucum": "1" }, "[PFU]": { "value": 1, "ucum": "1" }, "[FFU]": { "value": 1, "ucum": "1" }, "[CFU]": { "value": 1, "ucum": "1" }, "[BAU]": { "value": 1, "ucum": "1" }, "[AU]": { "value": 1, "ucum": "1" }, "[Amb'a'1'U]": { "value": 1, "ucum": "1" }, "[PNU]": { "value": 1, "ucum": "1" }, "[Lf]": { "value": 1, "ucum": "1" }, "[D'ag'U]": { "value": 1, "ucum": "1" }, "[FEU]": { "value": 1, "ucum": "1" }, "[ELU]": { "value": 1, "ucum": "1" }, "[EU]": { "value": 1, "ucum": "1" }, "Np": { "value": null, "ucum": "ln(1 1)" }, "B": { "value": null, "ucum": "lg(1 1)" }, "B[SPL]": { "value": null, "ucum": "2lg(2 10*-5.Pa)" }, "B[V]": { "value": null, "ucum": "2lg(1 V)" }, "B[mV]": { "value": null, "ucum": "2lg(1 mV)" }, "B[uV]": { "value": null, "ucum": "2lg(1 uV)" }, "B[10.nV]": { "value": null, "ucum": "2lg(10 nV)" }, "B[W]": { "value": null, "ucum": "lg(1 W)" }, "B[kW]": { "value": null, "ucum": "lg(1 kW)" }, "st": { "value": 1, "ucum": "m3" }, "Ao": { "value": 0.1, "ucum": "nm" }, "b": { "value": 100, "ucum": "fm2" }, "att": { "value": 1, "ucum": "kgf/cm2" }, "mho": { "value": 1, "ucum": "S" }, "[psi]": { "value": 1, "ucum": "[lbf_av]/[in_i]2" }, "circ": { "value": 2, "ucum": "[pi].rad" }, "sph": { "value": 4, "ucum": "[pi].sr" }, "[car_m]": { "value": 0.2, "ucum": "g" }, "[car_Au]": { "value": 1, "ucum": "/24" }, "[smoot]": { "value": 67, "ucum": "[in_i]" }, "bit_s": { "value": null, "ucum": "ld(1 1)" }, "bit": { "value": 1, "ucum": "1" }, "By": { "value": 8, "ucum": "bit" }, "Bd": { "value": 1, "ucum": "/s" } } },{}],405:[function(require,module,exports){ module.exports={"mol":true,"sr":true,"Hz":true,"N":true,"Pa":true,"J":true,"W":true,"A":true,"V":true,"F":true,"Ohm":true,"S":true,"Wb":true,"Cel":true,"T":true,"H":true,"lm":true,"lx":true,"Bq":true,"Gy":true,"Sv":true,"l":true,"L":true,"ar":true,"t":true,"bar":true,"u":true,"eV":true,"pc":true,"[c]":true,"[h]":true,"[k]":true,"[eps_0]":true,"[mu_0]":true,"[e]":true,"[m_e]":true,"[m_p]":true,"[G]":true,"[g]":true,"[ly]":true,"gf":true,"Ky":true,"Gal":true,"dyn":true,"erg":true,"P":true,"Bi":true,"St":true,"Mx":true,"G":true,"Oe":true,"Gb":true,"sb":true,"Lmb":true,"ph":true,"Ci":true,"R":true,"RAD":true,"REM":true,"cal_[15]":true,"cal_[20]":true,"cal_m":true,"cal_IT":true,"cal_th":true,"cal":true,"tex":true,"m[H2O]":true,"m[Hg]":true,"eq":true,"osm":true,"g%":true,"kat":true,"U":true,"[iU]":true,"[IU]":true,"Np":true,"B":true,"B[SPL]":true,"B[V]":true,"B[mV]":true,"B[uV]":true,"B[10.nV]":true,"B[W]":true,"B[kW]":true,"st":true,"mho":true,"bit":true,"By":true,"Bd":true,"m":true,"s":true,"g":true,"rad":true,"K":true,"C":true,"cd":true} },{}],406:[function(require,module,exports){ module.exports={ "Y": { "CODE": "YA", "names": [ "yotta" ], "printSymbols": [ "Y" ], "values": [ { "printable": "1 × 1024", "numeric": 1e+24 } ] }, "Z": { "CODE": "ZA", "names": [ "zetta" ], "printSymbols": [ "Z" ], "values": [ { "printable": "1 × 1021", "numeric": 1e+21 } ] }, "E": { "CODE": "EX", "names": [ "exa" ], "printSymbols": [ "E" ], "values": [ { "printable": "1 × 1018", "numeric": 1000000000000000000 } ] }, "P": { "CODE": "PT", "names": [ "peta" ], "printSymbols": [ "P" ], "values": [ { "printable": "1 × 1015", "numeric": 1000000000000000 } ] }, "T": { "CODE": "TR", "names": [ "tera" ], "printSymbols": [ "T" ], "values": [ { "printable": "1 × 1012", "numeric": 1000000000000 } ] }, "G": { "CODE": "GA", "names": [ "giga" ], "printSymbols": [ "G" ], "values": [ { "printable": "1 × 109", "numeric": 1000000000 } ] }, "M": { "CODE": "MA", "names": [ "mega" ], "printSymbols": [ "M" ], "values": [ { "printable": "1 × 106", "numeric": 1000000 } ] }, "k": { "CODE": "K", "names": [ "kilo" ], "printSymbols": [ "k" ], "values": [ { "printable": "1 × 103", "numeric": 1000 } ] }, "h": { "CODE": "H", "names": [ "hecto" ], "printSymbols": [ "h" ], "values": [ { "printable": "1 × 102", "numeric": 100 } ] }, "da": { "CODE": "DA", "names": [ "deka" ], "printSymbols": [ "da" ], "values": [ { "printable": "1 × 101", "numeric": 10 } ] }, "d": { "CODE": "D", "names": [ "deci" ], "printSymbols": [ "d" ], "values": [ { "printable": "1 × 10-1", "numeric": 0.1 } ] }, "c": { "CODE": "C", "names": [ "centi" ], "printSymbols": [ "c" ], "values": [ { "printable": "1 × 10-2", "numeric": 0.01 } ] }, "m": { "CODE": "M", "names": [ "milli" ], "printSymbols": [ "m" ], "values": [ { "printable": "1 × 10-3", "numeric": 0.001 } ] }, "u": { "CODE": "U", "names": [ "micro" ], "printSymbols": [ "μ" ], "values": [ { "printable": "1 × 10-6", "numeric": 0.000001 } ] }, "n": { "CODE": "N", "names": [ "nano" ], "printSymbols": [ "n" ], "values": [ { "printable": "1 × 10-9", "numeric": 1e-9 } ] }, "p": { "CODE": "P", "names": [ "pico" ], "printSymbols": [ "p" ], "values": [ { "printable": "1 × 10-12", "numeric": 1e-12 } ] }, "f": { "CODE": "F", "names": [ "femto" ], "printSymbols": [ "f" ], "values": [ { "printable": "1 × 10-15", "numeric": 1e-15 } ] }, "a": { "CODE": "A", "names": [ "atto" ], "printSymbols": [ "a" ], "values": [ { "printable": "1 × 10-18", "numeric": 1e-18 } ] }, "z": { "CODE": "ZO", "names": [ "zepto" ], "printSymbols": [ "z" ], "values": [ { "printable": "1 × 10-21", "numeric": 1e-21 } ] }, "y": { "CODE": "YO", "names": [ "yocto" ], "printSymbols": [ "y" ], "values": [ { "printable": "1 × 10-24", "numeric": 1e-24 } ] }, "Ki": { "CODE": "KIB", "names": [ "kibi" ], "printSymbols": [ "Ki" ], "values": [ { "printable": "1024", "numeric": 1024 } ] }, "Mi": { "CODE": "MIB", "names": [ "mebi" ], "printSymbols": [ "Mi" ], "values": [ { "printable": "1048576", "numeric": 1048576 } ] }, "Gi": { "CODE": "GIB", "names": [ "gibi" ], "printSymbols": [ "Gi" ], "values": [ { "printable": "1073741824", "numeric": 1073741824 } ] }, "Ti": { "CODE": "TIB", "names": [ "tebi" ], "printSymbols": [ "Ti" ], "values": [ { "printable": "1099511627776", "numeric": 1099511627776 } ] } } },{}],407:[function(require,module,exports){ module.exports={ "Y": 1e+24, "Z": 1e+21, "E": 1000000000000000000, "P": 1000000000000000, "T": 1000000000000, "G": 1000000000, "M": 1000000, "k": 1000, "h": 100, "da": 10, "d": 0.1, "c": 0.01, "m": 0.001, "u": 0.000001, "n": 1e-9, "p": 1e-12, "f": 1e-15, "a": 1e-18, "z": 1e-21, "y": 1e-24, "Ki": 1024, "Mi": 1048576, "Gi": 1073741824, "Ti": 1099511627776 } },{}],408:[function(require,module,exports){ module.exports = (function() { /* * Generated by PEG.js 0.8.0. * * http://pegjs.majda.cz/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function SyntaxError(message, expected, found, offset, line, column) { this.message = message; this.expected = expected; this.found = found; this.offset = offset; this.line = line; this.column = column; this.name = "SyntaxError"; } peg$subclass(SyntaxError, Error); function parse(input) { var options = arguments.length > 1 ? arguments[1] : {}, peg$FAILED = {}, peg$startRuleIndices = { start: 0 }, peg$startRuleIndex = 0, peg$consts = [ function(e) { return e ; // cleanup(e); }, peg$FAILED, "/", { type: "literal", value: "/", description: "\"/\"" }, function(e) {return multiply({value:1, units:{}}, [["/", e]]);}, ".", { type: "literal", value: ".", description: "\".\"" }, [], function(t, ms) { return multiply(t, ms); }, null, function(e, exp) {return e.ann && exp;}, void 0, function(e, exp) { return topower(e, exp); }, function(d) { var ret = { value: d, units: {} }; return ret; }, function(u) {return u;}, "(", { type: "literal", value: "(", description: "\"(\"" }, ")", { type: "literal", value: ")", description: "\")\"" }, function(e) {return e;}, /^[+\-]/, { type: "class", value: "[+\\-]", description: "[+\\-]" }, function(s, d) {return (s=="-") ? (-1*d) : d}, function(p, a) {return(p && !ismetric(a));}, function(p, a) { var ret = a; var u = Object.keys(ret.units)[0]; // console.log("simpleUnit: p:", JSON.stringify(p, null, 2), "a: ", JSON.stringify(a, null, 2)); if (p){ ret.value = ret.value * prefixes[p]; ret.metadata = {}; if(prefixMetadata[p]){ // if this prefix has metadata, augment the return with it Object.keys(prefixMetadata[p]).forEach(function(key){ if(!ret.metadata[u]){ ret.metadata[u] = { prefix: {} }; } ret.metadata[u].prefix[key] = prefixMetadata[p][key]; }); } // merge in the unit metadata if(unitMetadata[u]){ //console.log("simpleUnit: ", JSON.stringify(unitMetadata[u], null ,2)); Object.keys(unitMetadata[u]).forEach(function(key){ if(!ret.metadata[u]){ ret.metadata[u] = {}; } ret.metadata[u][key] = unitMetadata[u][key]; }); } } //console.log("simpleUnit: ret: ", JSON.stringify(ret, null ,2)); return ret; }, /^[0-9]/, { type: "class", value: "[0-9]", description: "[0-9]" }, "e", { type: "literal", value: "e", description: "\"e\"" }, function(v, epresent, e) {return (!epresent && !!e);}, function(v, epresent, e) { return parseInt(v.join(""))*Math.pow(10, e||0); }, "{", { type: "literal", value: "{", description: "\"{\"" }, /^[^}]/, { type: "class", value: "[^}]", description: "[^}]" }, "}", { type: "literal", value: "}", description: "\"}\"" }, function(m) {return /[^\x00-\x7F]/.test(m);}, function(m) { return {value: 1, units:{}, ann: m} }, "[anti'Xa'U]", { type: "literal", value: "[anti'Xa'U]", description: "\"[anti'Xa'U]\"" }, function(u) {return {"value": 1, "units": {"[anti'Xa'U]": 1}, "metadata": {"[anti'Xa'U]":{"isBase":false,"CODE":"[ANTI'XA'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["anti factor Xa unit"],"properties":["biologic activity of factor Xa inhibitor (heparin)"],"values":[{"printable":"1","numeric":1}]}}};}, "[Amb'a'1'U]", { type: "literal", value: "[Amb'a'1'U]", description: "\"[Amb'a'1'U]\"" }, function(u) {return {"value": 1, "units": {"[Amb'a'1'U]": 1}, "metadata": {"[Amb'a'1'U]":{"isBase":false,"CODE":"[AMB'A'1'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["allergen unit for Ambrosia artemisiifolia"],"printSymbols":["Amb a 1 U"],"properties":["procedure defined amount of the major allergen of ragweed."],"values":[{"printable":"1","numeric":1}]}}};}, "[stone_av]", { type: "literal", value: "[stone_av]", description: "\"[stone_av]\"" }, function(u) {return {"value": 1, "units": {"[stone_av]": 1}, "metadata": {"[stone_av]":{"isBase":false,"CODE":"[STONE_AV]","isMetric":"no","class":"avoirdupois","names":["stone","British stone"],"properties":["mass"],"values":[{"printable":"14","numeric":14}]}}};}, "[in_i'H2O]", { type: "literal", value: "[in_i'H2O]", description: "\"[in_i'H2O]\"" }, function(u) {return {"value": 1, "units": {"[in_i'H2O]": 1}, "metadata": {"[in_i'H2O]":{"isBase":false,"CODE":"[IN_I'H2O]","isMetric":"no","class":"clinical","names":["inch of water column"],"printSymbols":["in H\n 2\n O"],"properties":["pressure"],"values":[{"printable":"1","numeric":1}]}}};}, "[ston_av]", { type: "literal", value: "[ston_av]", description: "\"[ston_av]\"" }, function(u) {return {"value": 1, "units": {"[ston_av]": 1}, "metadata": {"[ston_av]":{"isBase":false,"CODE":"[STON_AV]","isMetric":"no","class":"avoirdupois","names":["short ton","U.S. ton"],"properties":["mass"],"values":[{"printable":"20","numeric":20}]}}};}, "[TCID_50]", { type: "literal", value: "[TCID_50]", description: "\"[TCID_50]\"" }, function(u) {return {"value": 1, "units": {"[TCID_50]": 1}, "metadata": {"[TCID_50]":{"isBase":false,"CODE":"[TCID_50]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["50% tissue culture infectious dose"],"printSymbols":["TCID50"],"properties":["biologic activity (infectivity) of an infectious agent preparation"],"values":[{"printable":"1","numeric":1}]}}};}, "[CCID_50]", { type: "literal", value: "[CCID_50]", description: "\"[CCID_50]\"" }, function(u) {return {"value": 1, "units": {"[CCID_50]": 1}, "metadata": {"[CCID_50]":{"isBase":false,"CODE":"[CCID_50]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["50% cell culture infectious dose"],"printSymbols":["CCID50"],"properties":["biologic activity (infectivity) of an infectious agent preparation"],"values":[{"printable":"1","numeric":1}]}}};}, "[scwt_av]", { type: "literal", value: "[scwt_av]", description: "\"[scwt_av]\"" }, function(u) {return {"value": 1, "units": {"[scwt_av]": 1}, "metadata": {"[scwt_av]":{"isBase":false,"CODE":"[SCWT_AV]","isMetric":"no","class":"avoirdupois","names":["short hundredweight","U.S. hundredweight"],"properties":["mass"],"values":[{"printable":"100","numeric":100}]}}};}, "[lcwt_av]", { type: "literal", value: "[lcwt_av]", description: "\"[lcwt_av]\"" }, function(u) {return {"value": 1, "units": {"[lcwt_av]": 1}, "metadata": {"[lcwt_av]":{"isBase":false,"CODE":"[LCWT_AV]","isMetric":"no","class":"avoirdupois","names":["long hunderdweight","British hundredweight"],"properties":["mass"],"values":[{"printable":"112","numeric":112}]}}};}, "[lton_av]", { type: "literal", value: "[lton_av]", description: "\"[lton_av]\"" }, function(u) {return {"value": 1, "units": {"[lton_av]": 1}, "metadata": {"[lton_av]":{"isBase":false,"CODE":"[LTON_AV]","isMetric":"no","class":"avoirdupois","names":["long ton","British ton"],"properties":["mass"],"values":[{"printable":"20","numeric":20}]}}};}, "[in_i'Hg]", { type: "literal", value: "[in_i'Hg]", description: "\"[in_i'Hg]\"" }, function(u) {return {"value": 1, "units": {"[in_i'Hg]": 1}, "metadata": {"[in_i'Hg]":{"isBase":false,"CODE":"[IN_I'HG]","isMetric":"no","class":"clinical","names":["inch of mercury column"],"printSymbols":["in Hg"],"properties":["pressure"],"values":[{"printable":"1","numeric":1}]}}};}, "[tbs_us]", { type: "literal", value: "[tbs_us]", description: "\"[tbs_us]\"" }, function(u) {return {"value": 1, "units": {"[tbs_us]": 1}, "metadata": {"[tbs_us]":{"isBase":false,"CODE":"[TBS_US]","isMetric":"no","class":"us-volumes","names":["tablespoon"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[dpt_us]", { type: "literal", value: "[dpt_us]", description: "\"[dpt_us]\"" }, function(u) {return {"value": 1, "units": {"[dpt_us]": 1}, "metadata": {"[dpt_us]":{"isBase":false,"CODE":"[DPT_US]","isMetric":"no","class":"us-volumes","names":["dry pint"],"properties":["dry volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[bdsk'U]", { type: "literal", value: "[bdsk'U]", description: "\"[bdsk'U]\"" }, function(u) {return {"value": 1, "units": {"[bdsk'U]": 1}, "metadata": {"[bdsk'U]":{"isBase":false,"CODE":"[BDSK'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Bodansky unit"],"properties":["biologic activity of phosphatase"],"values":[{"printable":"1","numeric":1}]}}};}, "[smgy'U]", { type: "literal", value: "[smgy'U]", description: "\"[smgy'U]\"" }, function(u) {return {"value": 1, "units": {"[smgy'U]": 1}, "metadata": {"[smgy'U]":{"isBase":false,"CODE":"[SMGY'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Somogyi unit"],"properties":["biologic activity of amylase"],"values":[{"printable":"1","numeric":1}]}}};}, "[dqt_us]", { type: "literal", value: "[dqt_us]", description: "\"[dqt_us]\"" }, function(u) {return {"value": 1, "units": {"[dqt_us]": 1}, "metadata": {"[dqt_us]":{"isBase":false,"CODE":"[DQT_US]","isMetric":"no","class":"us-volumes","names":["dry quart"],"properties":["dry volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[todd'U]", { type: "literal", value: "[todd'U]", description: "\"[todd'U]\"" }, function(u) {return {"value": 1, "units": {"[todd'U]": 1}, "metadata": {"[todd'U]":{"isBase":false,"CODE":"[TODD'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Todd unit"],"properties":["biologic activity antistreptolysin O"],"values":[{"printable":"1","numeric":1}]}}};}, "[D'ag'U]", { type: "literal", value: "[D'ag'U]", description: "\"[D'ag'U]\"" }, function(u) {return {"value": 1, "units": {"[D'ag'U]": 1}, "metadata": {"[D'ag'U]":{"isBase":false,"CODE":"[D'AG'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["D-antigen unit"],"printSymbols":[""],"properties":["procedure defined amount of a poliomyelitis d-antigen substance"],"values":[{"printable":"1","numeric":1}]}}};}, "[beth'U]", { type: "literal", value: "[beth'U]", description: "\"[beth'U]\"" }, function(u) {return {"value": 1, "units": {"[beth'U]": 1}, "metadata": {"[beth'U]":{"isBase":false,"CODE":"[BETH'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Bethesda unit"],"properties":["biologic activity of factor VIII inhibitor"],"values":[{"printable":"1","numeric":1}]}}};}, "[gal_wi]", { type: "literal", value: "[gal_wi]", description: "\"[gal_wi]\"" }, function(u) {return {"value": 1, "units": {"[gal_wi]": 1}, "metadata": {"[gal_wi]":{"isBase":false,"CODE":"[GAL_WI]","isMetric":"no","class":"us-volumes","names":["historical winchester gallon"],"properties":["dry volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[crd_us]", { type: "literal", value: "[crd_us]", description: "\"[crd_us]\"" }, function(u) {return {"value": 1, "units": {"[crd_us]": 1}, "metadata": {"[crd_us]":{"isBase":false,"CODE":"[CRD_US]","isMetric":"no","class":"us-volumes","names":["cord"],"properties":["fluid volume"],"values":[{"printable":"128","numeric":128}]}}};}, "[min_us]", { type: "literal", value: "[min_us]", description: "\"[min_us]\"" }, function(u) {return {"value": 1, "units": {"[min_us]": 1}, "metadata": {"[min_us]":{"isBase":false,"CODE":"[MIN_US]","isMetric":"no","class":"us-volumes","names":["minim"],"properties":["fluid volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[fdr_us]", { type: "literal", value: "[fdr_us]", description: "\"[fdr_us]\"" }, function(u) {return {"value": 1, "units": {"[fdr_us]": 1}, "metadata": {"[fdr_us]":{"isBase":false,"CODE":"[FDR_US]","isMetric":"no","class":"us-volumes","names":["fluid dram"],"properties":["fluid volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[foz_us]", { type: "literal", value: "[foz_us]", description: "\"[foz_us]\"" }, function(u) {return {"value": 1, "units": {"[foz_us]": 1}, "metadata": {"[foz_us]":{"isBase":false,"CODE":"[FOZ_US]","isMetric":"no","class":"us-volumes","names":["fluid ounce"],"printSymbols":["oz fl"],"properties":["fluid volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[gil_us]", { type: "literal", value: "[gil_us]", description: "\"[gil_us]\"" }, function(u) {return {"value": 1, "units": {"[gil_us]": 1}, "metadata": {"[gil_us]":{"isBase":false,"CODE":"[GIL_US]","isMetric":"no","class":"us-volumes","names":["gill"],"properties":["fluid volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[bbl_us]", { type: "literal", value: "[bbl_us]", description: "\"[bbl_us]\"" }, function(u) {return {"value": 1, "units": {"[bbl_us]": 1}, "metadata": {"[bbl_us]":{"isBase":false,"CODE":"[BBL_US]","isMetric":"no","class":"us-volumes","names":["barrel"],"properties":["fluid volume"],"values":[{"printable":"42","numeric":42}]}}};}, "[gal_us]", { type: "literal", value: "[gal_us]", description: "\"[gal_us]\"" }, function(u) {return {"value": 1, "units": {"[gal_us]": 1}, "metadata": {"[gal_us]":{"isBase":false,"CODE":"[GAL_US]","isMetric":"no","class":"us-volumes","names":["Queen Anne's wine gallon"],"properties":["fluid volume"],"values":[{"printable":"231","numeric":231}]}}};}, "[acr_br]", { type: "literal", value: "[acr_br]", description: "\"[acr_br]\"" }, function(u) {return {"value": 1, "units": {"[acr_br]": 1}, "metadata": {"[acr_br]":{"isBase":false,"CODE":"[ACR_BR]","isMetric":"no","class":"brit-length","names":["acre"],"properties":["area"],"values":[{"printable":"4840","numeric":4840}]}}};}, "[nmi_br]", { type: "literal", value: "[nmi_br]", description: "\"[nmi_br]\"" }, function(u) {return {"value": 1, "units": {"[nmi_br]": 1}, "metadata": {"[nmi_br]":{"isBase":false,"CODE":"[NMI_BR]","isMetric":"no","class":"brit-length","names":["nautical mile"],"properties":["length"],"values":[{"printable":"6080","numeric":6080}]}}};}, "[fth_br]", { type: "literal", value: "[fth_br]", description: "\"[fth_br]\"" }, function(u) {return {"value": 1, "units": {"[fth_br]": 1}, "metadata": {"[fth_br]":{"isBase":false,"CODE":"[FTH_BR]","isMetric":"no","class":"brit-length","names":["fathom"],"properties":["length"],"values":[{"printable":"6","numeric":6}]}}};}, "[mil_us]", { type: "literal", value: "[mil_us]", description: "\"[mil_us]\"" }, function(u) {return {"value": 1, "units": {"[mil_us]": 1}, "metadata": {"[mil_us]":{"isBase":false,"CODE":"[MIL_US]","isMetric":"no","class":"us-lengths","names":["mil"],"properties":["length"],"values":[{"printable":"1 × 10-3","numeric":0.001}]}}};}, "[smi_us]", { type: "literal", value: "[smi_us]", description: "\"[smi_us]\"" }, function(u) {return {"value": 1, "units": {"[smi_us]": 1}, "metadata": {"[smi_us]":{"isBase":false,"CODE":"[SMI_US]","isMetric":"no","class":"us-lengths","names":["square mile"],"properties":["area"],"values":[{"printable":"1","numeric":1}]}}};}, "[acr_us]", { type: "literal", value: "[acr_us]", description: "\"[acr_us]\"" }, function(u) {return {"value": 1, "units": {"[acr_us]": 1}, "metadata": {"[acr_us]":{"isBase":false,"CODE":"[ACR_US]","isMetric":"no","class":"us-lengths","names":["acre"],"properties":["area"],"values":[{"printable":"160","numeric":160}]}}};}, "[fur_us]", { type: "literal", value: "[fur_us]", description: "\"[fur_us]\"" }, function(u) {return {"value": 1, "units": {"[fur_us]": 1}, "metadata": {"[fur_us]":{"isBase":false,"CODE":"[FUR_US]","isMetric":"no","class":"us-lengths","names":["furlong"],"properties":["length"],"values":[{"printable":"40","numeric":40}]}}};}, "[fth_us]", { type: "literal", value: "[fth_us]", description: "\"[fth_us]\"" }, function(u) {return {"value": 1, "units": {"[fth_us]": 1}, "metadata": {"[fth_us]":{"isBase":false,"CODE":"[FTH_US]","isMetric":"no","class":"us-lengths","names":["fathom"],"properties":["length"],"values":[{"printable":"6","numeric":6}]}}};}, "[rlk_us]", { type: "literal", value: "[rlk_us]", description: "\"[rlk_us]\"" }, function(u) {return {"value": 1, "units": {"[rlk_us]": 1}, "metadata": {"[rlk_us]":{"isBase":false,"CODE":"[RLK_US]","isMetric":"no","class":"us-lengths","names":["link for Ramden's chain"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[rch_us]", { type: "literal", value: "[rch_us]", description: "\"[rch_us]\"" }, function(u) {return {"value": 1, "units": {"[rch_us]": 1}, "metadata": {"[rch_us]":{"isBase":false,"CODE":"[RCH_US]","isMetric":"no","class":"us-lengths","names":["Ramden's chain","Engineer's chain"],"properties":["length"],"values":[{"printable":"100","numeric":100}]}}};}, "[lbf_av]", { type: "literal", value: "[lbf_av]", description: "\"[lbf_av]\"" }, function(u) {return {"value": 1, "units": {"[lbf_av]": 1}, "metadata": {"[lbf_av]":{"isBase":false,"CODE":"[LBF_AV]","isMetric":"no","class":"const","names":["pound force"],"printSymbols":["lbf"],"properties":["force"],"values":[{"printable":"1","numeric":1}]}}};}, "[hnsf'U]", { type: "literal", value: "[hnsf'U]", description: "\"[hnsf'U]\"" }, function(u) {return {"value": 1, "units": {"[hnsf'U]": 1}, "metadata": {"[hnsf'U]":{"isBase":false,"CODE":"[HNSF'U]","isMetric":"no","class":"clinical","names":["Hounsfield unit"],"printSymbols":["HF"],"properties":["x-ray attenuation"],"values":[{"printable":"1","numeric":1}]}}};}, "[mesh_i]", { type: "literal", value: "[mesh_i]", description: "\"[mesh_i]\"" }, function(u) {return {"value": 1, "units": {"[mesh_i]": 1}, "metadata": {"[mesh_i]":{"isBase":false,"CODE":"[MESH_I]","isMetric":"no","class":"clinical","names":["mesh"],"properties":["lineic number"],"values":[{"printable":"1","numeric":1}]}}};}, "%[slope]", { type: "literal", value: "%[slope]", description: "\"%[slope]\"" }, function(u) {return {"value": 1, "units": {"%[slope]": 1}, "metadata": {"%[slope]":{"isBase":false,"CODE":"%[SLOPE]","isMetric":"no","isSpecial":"yes","class":"clinical","names":["percent of slope"],"printSymbols":["%"],"properties":["slope"],"values":[{"printable":"","numeric":null}]}}};}, "[p'diop]", { type: "literal", value: "[p'diop]", description: "\"[p'diop]\"" }, function(u) {return {"value": 1, "units": {"[p'diop]": 1}, "metadata": {"[p'diop]":{"isBase":false,"CODE":"[P'DIOP]","isMetric":"no","isSpecial":"yes","class":"clinical","names":["prism diopter"],"printSymbols":["PD"],"properties":["refraction of a prism"],"values":[{"printable":"","numeric":null}]}}};}, "[gil_br]", { type: "literal", value: "[gil_br]", description: "\"[gil_br]\"" }, function(u) {return {"value": 1, "units": {"[gil_br]": 1}, "metadata": {"[gil_br]":{"isBase":false,"CODE":"[GIL_BR]","isMetric":"no","class":"brit-volumes","names":["gill"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[wood'U]", { type: "literal", value: "[wood'U]", description: "\"[wood'U]\"" }, function(u) {return {"value": 1, "units": {"[wood'U]": 1}, "metadata": {"[wood'U]":{"isBase":false,"CODE":"[WOOD'U]","isMetric":"no","class":"clinical","names":["Wood unit"],"printSymbols":["Wood U."],"properties":["fluid resistance"],"values":[{"printable":"1","numeric":1}]}}};}, "cal_[15]", { type: "literal", value: "cal_[15]", description: "\"cal_[15]\"" }, function(u) {return {"value": 1, "units": {"cal_[15]": 1}, "metadata": {"cal_[15]":{"isBase":false,"CODE":"CAL_[15]","isMetric":"yes","class":"heat","names":["calorie at 15 °C"],"printSymbols":["cal15°C"],"properties":["energy"],"values":[{"printable":"4.18580","numeric":4.1858}]}}};}, "cal_[20]", { type: "literal", value: "cal_[20]", description: "\"cal_[20]\"" }, function(u) {return {"value": 1, "units": {"cal_[20]": 1}, "metadata": {"cal_[20]":{"isBase":false,"CODE":"CAL_[20]","isMetric":"yes","class":"heat","names":["calorie at 20 °C"],"printSymbols":["cal20°C"],"properties":["energy"],"values":[{"printable":"4.18190","numeric":4.1819}]}}};}, "[foz_br]", { type: "literal", value: "[foz_br]", description: "\"[foz_br]\"" }, function(u) {return {"value": 1, "units": {"[foz_br]": 1}, "metadata": {"[foz_br]":{"isBase":false,"CODE":"[FOZ_BR]","isMetric":"no","class":"brit-volumes","names":["fluid ounce"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[fdr_br]", { type: "literal", value: "[fdr_br]", description: "\"[fdr_br]\"" }, function(u) {return {"value": 1, "units": {"[fdr_br]": 1}, "metadata": {"[fdr_br]":{"isBase":false,"CODE":"[FDR_BR]","isMetric":"no","class":"brit-volumes","names":["fluid dram"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[srd_us]", { type: "literal", value: "[srd_us]", description: "\"[srd_us]\"" }, function(u) {return {"value": 1, "units": {"[srd_us]": 1}, "metadata": {"[srd_us]":{"isBase":false,"CODE":"[SRD_US]","isMetric":"no","class":"us-lengths","names":["square rod"],"properties":["area"],"values":[{"printable":"1","numeric":1}]}}};}, "[min_br]", { type: "literal", value: "[min_br]", description: "\"[min_br]\"" }, function(u) {return {"value": 1, "units": {"[min_br]": 1}, "metadata": {"[min_br]":{"isBase":false,"CODE":"[MIN_BR]","isMetric":"no","class":"brit-volumes","names":["minim"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[EID_50]", { type: "literal", value: "[EID_50]", description: "\"[EID_50]\"" }, function(u) {return {"value": 1, "units": {"[EID_50]": 1}, "metadata": {"[EID_50]":{"isBase":false,"CODE":"[EID_50]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["50% embryo infectious dose"],"printSymbols":["EID50"],"properties":["biologic activity (infectivity) of an infectious agent preparation"],"values":[{"printable":"1","numeric":1}]}}};}, "[Btu_th]", { type: "literal", value: "[Btu_th]", description: "\"[Btu_th]\"" }, function(u) {return {"value": 1, "units": {"[Btu_th]": 1}, "metadata": {"[Btu_th]":{"isBase":false,"CODE":"[BTU_TH]","isMetric":"no","class":"heat","names":["thermochemical British thermal unit"],"printSymbols":["Btuth"],"properties":["energy"],"values":[{"printable":"1.054350","numeric":1.05435}]}}};}, "[Btu_IT]", { type: "literal", value: "[Btu_IT]", description: "\"[Btu_IT]\"" }, function(u) {return {"value": 1, "units": {"[Btu_IT]": 1}, "metadata": {"[Btu_IT]":{"isBase":false,"CODE":"[BTU_IT]","isMetric":"no","class":"heat","names":["international table British thermal unit"],"printSymbols":["BtuIT"],"properties":["energy"],"values":[{"printable":"1.05505585262","numeric":1.05505585262}]}}};}, "[car_Au]", { type: "literal", value: "[car_Au]", description: "\"[car_Au]\"" }, function(u) {return {"value": 1, "units": {"[car_Au]": 1}, "metadata": {"[car_Au]":{"isBase":false,"CODE":"[CAR_AU]","isMetric":"no","class":"misc","names":["carat of gold alloys"],"printSymbols":["ct\n Au\n "],"properties":["mass fraction"],"values":[{"printable":"1","numeric":1}]}}};}, "[Btu_60]", { type: "literal", value: "[Btu_60]", description: "\"[Btu_60]\"" }, function(u) {return {"value": 1, "units": {"[Btu_60]": 1}, "metadata": {"[Btu_60]":{"isBase":false,"CODE":"[BTU_60]","isMetric":"no","class":"heat","names":["British thermal unit at 60 °F"],"printSymbols":["Btu60°F"],"properties":["energy"],"values":[{"printable":"1.05468","numeric":1.05468}]}}};}, "[Btu_59]", { type: "literal", value: "[Btu_59]", description: "\"[Btu_59]\"" }, function(u) {return {"value": 1, "units": {"[Btu_59]": 1}, "metadata": {"[Btu_59]":{"isBase":false,"CODE":"[BTU_59]","isMetric":"no","class":"heat","names":["British thermal unit at 59 °F"],"printSymbols":["Btu59°F"],"properties":["energy"],"values":[{"printable":"1.05480","numeric":1.0548}]}}};}, "[Btu_39]", { type: "literal", value: "[Btu_39]", description: "\"[Btu_39]\"" }, function(u) {return {"value": 1, "units": {"[Btu_39]": 1}, "metadata": {"[Btu_39]":{"isBase":false,"CODE":"[BTU_39]","isMetric":"no","class":"heat","names":["British thermal unit at 39 °F"],"printSymbols":["Btu39°F"],"properties":["energy"],"values":[{"printable":"1.05967","numeric":1.05967}]}}};}, "[cup_us]", { type: "literal", value: "[cup_us]", description: "\"[cup_us]\"" }, function(u) {return {"value": 1, "units": {"[cup_us]": 1}, "metadata": {"[cup_us]":{"isBase":false,"CODE":"[CUP_US]","isMetric":"no","class":"us-volumes","names":["cup"],"properties":["volume"],"values":[{"printable":"16","numeric":16}]}}};}, "B[10.nV]", { type: "literal", value: "B[10.nV]", description: "\"B[10.nV]\"" }, function(u) {return {"value": 1, "units": {"B[10.nV]": 1}, "metadata": {"B[10.nV]":{"isBase":false,"CODE":"B[10.NV]","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel 10 nanovolt"],"printSymbols":["B(10 nV)"],"properties":["electric potential level"],"values":[{"printable":"","numeric":null}]}}};}, "[tsp_us]", { type: "literal", value: "[tsp_us]", description: "\"[tsp_us]\"" }, function(u) {return {"value": 1, "units": {"[tsp_us]": 1}, "metadata": {"[tsp_us]":{"isBase":false,"CODE":"[TSP_US]","isMetric":"no","class":"us-volumes","names":["teaspoon"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[mclg'U]", { type: "literal", value: "[mclg'U]", description: "\"[mclg'U]\"" }, function(u) {return {"value": 1, "units": {"[mclg'U]": 1}, "metadata": {"[mclg'U]":{"isBase":false,"CODE":"[MCLG'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Mac Lagan unit"],"properties":["arbitrary biologic activity"],"values":[{"printable":"1","numeric":1}]}}};}, "[cicero]", { type: "literal", value: "[cicero]", description: "\"[cicero]\"" }, function(u) {return {"value": 1, "units": {"[cicero]": 1}, "metadata": {"[cicero]":{"isBase":false,"CODE":"[CICERO]","isMetric":"no","class":"typeset","names":["cicero","Didot's pica"],"properties":["length"],"values":[{"printable":"12","numeric":12}]}}};}, "[pwt_tr]", { type: "literal", value: "[pwt_tr]", description: "\"[pwt_tr]\"" }, function(u) {return {"value": 1, "units": {"[pwt_tr]": 1}, "metadata": {"[pwt_tr]":{"isBase":false,"CODE":"[PWT_TR]","isMetric":"no","class":"troy","names":["pennyweight"],"printSymbols":["dwt"],"properties":["mass"],"values":[{"printable":"24","numeric":24}]}}};}, "[pnt_pr]", { type: "literal", value: "[pnt_pr]", description: "\"[pnt_pr]\"" }, function(u) {return {"value": 1, "units": {"[pnt_pr]": 1}, "metadata": {"[pnt_pr]":{"isBase":false,"CODE":"[PNT_PR]","isMetric":"no","class":"typeset","names":["Printer's point"],"properties":["length"],"values":[{"printable":"0.013837","numeric":0.013837}]}}};}, "[pca_pr]", { type: "literal", value: "[pca_pr]", description: "\"[pca_pr]\"" }, function(u) {return {"value": 1, "units": {"[pca_pr]": 1}, "metadata": {"[pca_pr]":{"isBase":false,"CODE":"[PCA_PR]","isMetric":"no","class":"typeset","names":["Printer's pica"],"properties":["length"],"values":[{"printable":"12","numeric":12}]}}};}, "[gal_br]", { type: "literal", value: "[gal_br]", description: "\"[gal_br]\"" }, function(u) {return {"value": 1, "units": {"[gal_br]": 1}, "metadata": {"[gal_br]":{"isBase":false,"CODE":"[GAL_BR]","isMetric":"no","class":"brit-volumes","names":["gallon"],"properties":["volume"],"values":[{"printable":"4.54609","numeric":4.54609}]}}};}, "[yd_us]", { type: "literal", value: "[yd_us]", description: "\"[yd_us]\"" }, function(u) {return {"value": 1, "units": {"[yd_us]": 1}, "metadata": {"[yd_us]":{"isBase":false,"CODE":"[YD_US]","isMetric":"no","class":"us-lengths","names":["yard"],"properties":["length"],"values":[{"printable":"3","numeric":3}]}}};}, "[ligne]", { type: "literal", value: "[ligne]", description: "\"[ligne]\"" }, function(u) {return {"value": 1, "units": {"[ligne]": 1}, "metadata": {"[ligne]":{"isBase":false,"CODE":"[LIGNE]","isMetric":"no","class":"typeset","names":["ligne","French line"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[tbs_m]", { type: "literal", value: "[tbs_m]", description: "\"[tbs_m]\"" }, function(u) {return {"value": 1, "units": {"[tbs_m]": 1}, "metadata": {"[tbs_m]":{"isBase":false,"CODE":"[TBS_M]","isMetric":"no","class":"us-volumes","names":["metric tablespoon"],"properties":["volume"],"values":[{"printable":"15","numeric":15}]}}};}, "[lb_ap]", { type: "literal", value: "[lb_ap]", description: "\"[lb_ap]\"" }, function(u) {return {"value": 1, "units": {"[lb_ap]": 1}, "metadata": {"[lb_ap]":{"isBase":false,"CODE":"[LB_AP]","isMetric":"no","class":"apoth","names":["pound"],"printSymbols":["lb"],"properties":["mass"],"values":[{"printable":"12","numeric":12}]}}};}, "[oz_ap]", { type: "literal", value: "[oz_ap]", description: "\"[oz_ap]\"" }, function(u) {return {"value": 1, "units": {"[oz_ap]": 1}, "metadata": {"[oz_ap]":{"isBase":false,"CODE":"[OZ_AP]","isMetric":"no","class":"apoth","names":["ounce"],"printSymbols":["℥"],"properties":["mass"],"values":[{"printable":"8","numeric":8}]}}};}, "[dr_ap]", { type: "literal", value: "[dr_ap]", description: "\"[dr_ap]\"" }, function(u) {return {"value": 1, "units": {"[dr_ap]": 1}, "metadata": {"[dr_ap]":{"isBase":false,"CODE":"[DR_AP]","isMetric":"no","class":"apoth","names":["dram","drachm"],"printSymbols":["ʒ"],"properties":["mass"],"values":[{"printable":"3","numeric":3}]}}};}, "[sc_ap]", { type: "literal", value: "[sc_ap]", description: "\"[sc_ap]\"" }, function(u) {return {"value": 1, "units": {"[sc_ap]": 1}, "metadata": {"[sc_ap]":{"isBase":false,"CODE":"[SC_AP]","isMetric":"no","class":"apoth","names":["scruple"],"printSymbols":["℈"],"properties":["mass"],"values":[{"printable":"20","numeric":20}]}}};}, "[tsp_m]", { type: "literal", value: "[tsp_m]", description: "\"[tsp_m]\"" }, function(u) {return {"value": 1, "units": {"[tsp_m]": 1}, "metadata": {"[tsp_m]":{"isBase":false,"CODE":"[TSP_M]","isMetric":"no","class":"us-volumes","names":["metric teaspoon"],"properties":["volume"],"values":[{"printable":"5","numeric":5}]}}};}, "[cup_m]", { type: "literal", value: "[cup_m]", description: "\"[cup_m]\"" }, function(u) {return {"value": 1, "units": {"[cup_m]": 1}, "metadata": {"[cup_m]":{"isBase":false,"CODE":"[CUP_M]","isMetric":"no","class":"us-volumes","names":["metric cup"],"properties":["volume"],"values":[{"printable":"240","numeric":240}]}}};}, "[lb_tr]", { type: "literal", value: "[lb_tr]", description: "\"[lb_tr]\"" }, function(u) {return {"value": 1, "units": {"[lb_tr]": 1}, "metadata": {"[lb_tr]":{"isBase":false,"CODE":"[LB_TR]","isMetric":"no","class":"troy","names":["troy pound"],"printSymbols":["lb t"],"properties":["mass"],"values":[{"printable":"12","numeric":12}]}}};}, "[oz_tr]", { type: "literal", value: "[oz_tr]", description: "\"[oz_tr]\"" }, function(u) {return {"value": 1, "units": {"[oz_tr]": 1}, "metadata": {"[oz_tr]":{"isBase":false,"CODE":"[OZ_TR]","isMetric":"no","class":"troy","names":["troy ounce"],"printSymbols":["oz t"],"properties":["mass"],"values":[{"printable":"20","numeric":20}]}}};}, "[didot]", { type: "literal", value: "[didot]", description: "\"[didot]\"" }, function(u) {return {"value": 1, "units": {"[didot]": 1}, "metadata": {"[didot]":{"isBase":false,"CODE":"[DIDOT]","isMetric":"no","class":"typeset","names":["didot","Didot's point"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[foz_m]", { type: "literal", value: "[foz_m]", description: "\"[foz_m]\"" }, function(u) {return {"value": 1, "units": {"[foz_m]": 1}, "metadata": {"[foz_m]":{"isBase":false,"CODE":"[FOZ_M]","isMetric":"no","class":"us-volumes","names":["metric fluid ounce"],"printSymbols":["oz fl"],"properties":["fluid volume"],"values":[{"printable":"30","numeric":30}]}}};}, "[car_m]", { type: "literal", value: "[car_m]", description: "\"[car_m]\"" }, function(u) {return {"value": 1, "units": {"[car_m]": 1}, "metadata": {"[car_m]":{"isBase":false,"CODE":"[CAR_M]","isMetric":"no","class":"misc","names":["metric carat"],"printSymbols":["ctm"],"properties":["mass"],"values":[{"printable":"0.2","numeric":0.2}]}}};}, "[smoot]", { type: "literal", value: "[smoot]", description: "\"[smoot]\"" }, function(u) {return {"value": 1, "units": {"[smoot]": 1}, "metadata": {"[smoot]":{"isBase":false,"CODE":"[SMOOT]","isMetric":"no","class":"misc","names":["Smoot"],"printSymbols":[""],"properties":["length"],"values":[{"printable":"67","numeric":67}]}}};}, "[knk'U]", { type: "literal", value: "[knk'U]", description: "\"[knk'U]\"" }, function(u) {return {"value": 1, "units": {"[knk'U]": 1}, "metadata": {"[knk'U]":{"isBase":false,"CODE":"[KNK'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Kunkel unit"],"properties":["arbitrary biologic activity"],"values":[{"printable":"1","numeric":1}]}}};}, "[Btu_m]", { type: "literal", value: "[Btu_m]", description: "\"[Btu_m]\"" }, function(u) {return {"value": 1, "units": {"[Btu_m]": 1}, "metadata": {"[Btu_m]":{"isBase":false,"CODE":"[BTU_M]","isMetric":"no","class":"heat","names":["mean British thermal unit"],"printSymbols":["Btum"],"properties":["energy"],"values":[{"printable":"1.05587","numeric":1.05587}]}}};}, "[dr_av]", { type: "literal", value: "[dr_av]", description: "\"[dr_av]\"" }, function(u) {return {"value": 1, "units": {"[dr_av]": 1}, "metadata": {"[dr_av]":{"isBase":false,"CODE":"[DR_AV]","isMetric":"no","class":"avoirdupois","names":["dram"],"properties":["mass"],"values":[{"printable":"1","numeric":1}]}}};}, "[oz_av]", { type: "literal", value: "[oz_av]", description: "\"[oz_av]\"" }, function(u) {return {"value": 1, "units": {"[oz_av]": 1}, "metadata": {"[oz_av]":{"isBase":false,"CODE":"[OZ_AV]","isMetric":"no","class":"avoirdupois","names":["ounce"],"printSymbols":["oz"],"properties":["mass"],"values":[{"printable":"1","numeric":1}]}}};}, "[lb_av]", { type: "literal", value: "[lb_av]", description: "\"[lb_av]\"" }, function(u) {return {"value": 1, "units": {"[lb_av]": 1}, "metadata": {"[lb_av]":{"isBase":false,"CODE":"[LB_AV]","isMetric":"no","class":"avoirdupois","names":["pound"],"printSymbols":["lb"],"properties":["mass"],"values":[{"printable":"7000","numeric":7000}]}}};}, "[dye'U]", { type: "literal", value: "[dye'U]", description: "\"[dye'U]\"" }, function(u) {return {"value": 1, "units": {"[dye'U]": 1}, "metadata": {"[dye'U]":{"isBase":false,"CODE":"[DYE'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Dye unit"],"properties":["biologic activity of amylase"],"values":[{"printable":"1","numeric":1}]}}};}, "[pk_us]", { type: "literal", value: "[pk_us]", description: "\"[pk_us]\"" }, function(u) {return {"value": 1, "units": {"[pk_us]": 1}, "metadata": {"[pk_us]":{"isBase":false,"CODE":"[PK_US]","isMetric":"no","class":"us-volumes","names":["peck"],"properties":["dry volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[APL'U]", { type: "literal", value: "[APL'U]", description: "\"[APL'U]\"" }, function(u) {return {"value": 1, "units": {"[APL'U]": 1}, "metadata": {"[APL'U]":{"isBase":false,"CODE":"[APL'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["APL unit"],"properties":["biologic activity of anticardiolipin IgA"],"values":[{"printable":"1","numeric":1}]}}};}, "[bu_us]", { type: "literal", value: "[bu_us]", description: "\"[bu_us]\"" }, function(u) {return {"value": 1, "units": {"[bu_us]": 1}, "metadata": {"[bu_us]":{"isBase":false,"CODE":"[BU_US]","isMetric":"no","class":"us-volumes","names":["bushel"],"properties":["dry volume"],"values":[{"printable":"2150.42","numeric":2150.42}]}}};}, "[pt_br]", { type: "literal", value: "[pt_br]", description: "\"[pt_br]\"" }, function(u) {return {"value": 1, "units": {"[pt_br]": 1}, "metadata": {"[pt_br]":{"isBase":false,"CODE":"[PT_BR]","isMetric":"no","class":"brit-volumes","names":["pint"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[qt_br]", { type: "literal", value: "[qt_br]", description: "\"[qt_br]\"" }, function(u) {return {"value": 1, "units": {"[qt_br]": 1}, "metadata": {"[qt_br]":{"isBase":false,"CODE":"[QT_BR]","isMetric":"no","class":"brit-volumes","names":["quart"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[bu_br]", { type: "literal", value: "[bu_br]", description: "\"[bu_br]\"" }, function(u) {return {"value": 1, "units": {"[bu_br]": 1}, "metadata": {"[bu_br]":{"isBase":false,"CODE":"[BU_BR]","isMetric":"no","class":"brit-volumes","names":["bushel"],"properties":["volume"],"values":[{"printable":"4","numeric":4}]}}};}, "[hp'_X]", { type: "literal", value: "[hp'_X]", description: "\"[hp'_X]\"" }, function(u) {return {"value": 1, "units": {"[hp'_X]": 1}, "metadata": {"[hp'_X]":{"isBase":false,"CODE":"[HP'_X]","isMetric":"no","isSpecial":"yes","class":"clinical","names":["homeopathic potency of decimal series (retired)"],"printSymbols":["X"],"properties":["homeopathic potency (retired)"],"values":[{"printable":"","numeric":null}]}}};}, "[MPL'U]", { type: "literal", value: "[MPL'U]", description: "\"[MPL'U]\"" }, function(u) {return {"value": 1, "units": {"[MPL'U]": 1}, "metadata": {"[MPL'U]":{"isBase":false,"CODE":"[MPL'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["MPL unit"],"properties":["biologic activity of anticardiolipin IgM"],"values":[{"printable":"1","numeric":1}]}}};}, "[GPL'U]", { type: "literal", value: "[GPL'U]", description: "\"[GPL'U]\"" }, function(u) {return {"value": 1, "units": {"[GPL'U]": 1}, "metadata": {"[GPL'U]":{"isBase":false,"CODE":"[GPL'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["GPL unit"],"properties":["biologic activity of anticardiolipin IgG"],"values":[{"printable":"1","numeric":1}]}}};}, "[USP'U]", { type: "literal", value: "[USP'U]", description: "\"[USP'U]\"" }, function(u) {return {"value": 1, "units": {"[USP'U]": 1}, "metadata": {"[USP'U]":{"isBase":false,"CODE":"[USP'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["United States Pharmacopeia unit"],"printSymbols":["U.S.P."],"properties":["arbitrary"],"values":[{"printable":"1","numeric":1}]}}};}, "[eps_0]", { type: "literal", value: "[eps_0]", description: "\"[eps_0]\"" }, function(u) {return {"value": 1, "units": {"[eps_0]": 1}, "metadata": {"[eps_0]":{"isBase":false,"CODE":"[EPS_0]","isMetric":"yes","class":"const","names":["permittivity of vacuum"],"printSymbols":["ε\n 0\n \n "],"properties":["electric permittivity"],"values":[{"printable":"8.854187817 × 10-12","numeric":8.854187817e-12}]}}};}, "[fth_i]", { type: "literal", value: "[fth_i]", description: "\"[fth_i]\"" }, function(u) {return {"value": 1, "units": {"[fth_i]": 1}, "metadata": {"[fth_i]":{"isBase":false,"CODE":"[FTH_I]","isMetric":"no","class":"intcust","names":["fathom"],"printSymbols":["fth"],"properties":["depth of water"],"values":[{"printable":"6","numeric":6}]}}};}, "[nmi_i]", { type: "literal", value: "[nmi_i]", description: "\"[nmi_i]\"" }, function(u) {return {"value": 1, "units": {"[nmi_i]": 1}, "metadata": {"[nmi_i]":{"isBase":false,"CODE":"[NMI_I]","isMetric":"no","class":"intcust","names":["nautical mile"],"printSymbols":["n.mi"],"properties":["length"],"values":[{"printable":"1852","numeric":1852}]}}};}, "[pt_us]", { type: "literal", value: "[pt_us]", description: "\"[pt_us]\"" }, function(u) {return {"value": 1, "units": {"[pt_us]": 1}, "metadata": {"[pt_us]":{"isBase":false,"CODE":"[PT_US]","isMetric":"no","class":"us-volumes","names":["pint"],"properties":["fluid volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[sin_i]", { type: "literal", value: "[sin_i]", description: "\"[sin_i]\"" }, function(u) {return {"value": 1, "units": {"[sin_i]": 1}, "metadata": {"[sin_i]":{"isBase":false,"CODE":"[SIN_I]","isMetric":"no","class":"intcust","names":["square inch"],"properties":["area"],"values":[{"printable":"1","numeric":1}]}}};}, "[sft_i]", { type: "literal", value: "[sft_i]", description: "\"[sft_i]\"" }, function(u) {return {"value": 1, "units": {"[sft_i]": 1}, "metadata": {"[sft_i]":{"isBase":false,"CODE":"[SFT_I]","isMetric":"no","class":"intcust","names":["square foot"],"properties":["area"],"values":[{"printable":"1","numeric":1}]}}};}, "[syd_i]", { type: "literal", value: "[syd_i]", description: "\"[syd_i]\"" }, function(u) {return {"value": 1, "units": {"[syd_i]": 1}, "metadata": {"[syd_i]":{"isBase":false,"CODE":"[SYD_I]","isMetric":"no","class":"intcust","names":["square yard"],"properties":["area"],"values":[{"printable":"1","numeric":1}]}}};}, "[cin_i]", { type: "literal", value: "[cin_i]", description: "\"[cin_i]\"" }, function(u) {return {"value": 1, "units": {"[cin_i]": 1}, "metadata": {"[cin_i]":{"isBase":false,"CODE":"[CIN_I]","isMetric":"no","class":"intcust","names":["cubic inch"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[cft_i]", { type: "literal", value: "[cft_i]", description: "\"[cft_i]\"" }, function(u) {return {"value": 1, "units": {"[cft_i]": 1}, "metadata": {"[cft_i]":{"isBase":false,"CODE":"[CFT_I]","isMetric":"no","class":"intcust","names":["cubic foot"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[cyd_i]", { type: "literal", value: "[cyd_i]", description: "\"[cyd_i]\"" }, function(u) {return {"value": 1, "units": {"[cyd_i]": 1}, "metadata": {"[cyd_i]":{"isBase":false,"CODE":"[CYD_I]","isMetric":"no","class":"intcust","names":["cubic yard"],"printSymbols":["cu.yd"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[qt_us]", { type: "literal", value: "[qt_us]", description: "\"[qt_us]\"" }, function(u) {return {"value": 1, "units": {"[qt_us]": 1}, "metadata": {"[qt_us]":{"isBase":false,"CODE":"[QT_US]","isMetric":"no","class":"us-volumes","names":["quart"],"properties":["fluid volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[arb'U]", { type: "literal", value: "[arb'U]", description: "\"[arb'U]\"" }, function(u) {return {"value": 1, "units": {"[arb'U]": 1}, "metadata": {"[arb'U]":{"isBase":false,"CODE":"[ARB'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["arbitary unit"],"printSymbols":["arb. U"],"properties":["arbitrary"],"values":[{"printable":"1","numeric":1}]}}};}, "[mil_i]", { type: "literal", value: "[mil_i]", description: "\"[mil_i]\"" }, function(u) {return {"value": 1, "units": {"[mil_i]": 1}, "metadata": {"[mil_i]":{"isBase":false,"CODE":"[MIL_I]","isMetric":"no","class":"intcust","names":["mil"],"printSymbols":["mil"],"properties":["length"],"values":[{"printable":"1 × 10-3","numeric":0.001}]}}};}, "[cml_i]", { type: "literal", value: "[cml_i]", description: "\"[cml_i]\"" }, function(u) {return {"value": 1, "units": {"[cml_i]": 1}, "metadata": {"[cml_i]":{"isBase":false,"CODE":"[CML_I]","isMetric":"no","class":"intcust","names":["circular mil"],"printSymbols":["circ.mil"],"properties":["area"],"values":[{"printable":"1","numeric":1}]}}};}, "[kn_br]", { type: "literal", value: "[kn_br]", description: "\"[kn_br]\"" }, function(u) {return {"value": 1, "units": {"[kn_br]": 1}, "metadata": {"[kn_br]":{"isBase":false,"CODE":"[KN_BR]","isMetric":"no","class":"brit-length","names":["knot"],"properties":["velocity"],"values":[{"printable":"1","numeric":1}]}}};}, "[ft_us]", { type: "literal", value: "[ft_us]", description: "\"[ft_us]\"" }, function(u) {return {"value": 1, "units": {"[ft_us]": 1}, "metadata": {"[ft_us]":{"isBase":false,"CODE":"[FT_US]","isMetric":"no","class":"us-lengths","names":["foot"],"printSymbols":["ftus"],"properties":["length"],"values":[{"printable":"1200","numeric":1200}]}}};}, "[pouce]", { type: "literal", value: "[pouce]", description: "\"[pouce]\"" }, function(u) {return {"value": 1, "units": {"[pouce]": 1}, "metadata": {"[pouce]":{"isBase":false,"CODE":"[POUCE]","isMetric":"no","class":"typeset","names":["pouce","French inch"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[in_us]", { type: "literal", value: "[in_us]", description: "\"[in_us]\"" }, function(u) {return {"value": 1, "units": {"[in_us]": 1}, "metadata": {"[in_us]":{"isBase":false,"CODE":"[IN_US]","isMetric":"no","class":"us-lengths","names":["inch"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[rd_us]", { type: "literal", value: "[rd_us]", description: "\"[rd_us]\"" }, function(u) {return {"value": 1, "units": {"[rd_us]": 1}, "metadata": {"[rd_us]":{"isBase":false,"CODE":"[RD_US]","isMetric":"no","class":"us-lengths","names":["rod"],"properties":["length"],"values":[{"printable":"16.5","numeric":16.5}]}}};}, "[ch_us]", { type: "literal", value: "[ch_us]", description: "\"[ch_us]\"" }, function(u) {return {"value": 1, "units": {"[ch_us]": 1}, "metadata": {"[ch_us]":{"isBase":false,"CODE":"[CH_US]","isMetric":"no","class":"us-lengths","names":["Gunter's chain","Surveyor's chain"],"properties":["length"],"values":[{"printable":"4","numeric":4}]}}};}, "[lk_us]", { type: "literal", value: "[lk_us]", description: "\"[lk_us]\"" }, function(u) {return {"value": 1, "units": {"[lk_us]": 1}, "metadata": {"[lk_us]":{"isBase":false,"CODE":"[LK_US]","isMetric":"no","class":"us-lengths","names":["link for Gunter's chain"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[hp'_C]", { type: "literal", value: "[hp'_C]", description: "\"[hp'_C]\"" }, function(u) {return {"value": 1, "units": {"[hp'_C]": 1}, "metadata": {"[hp'_C]":{"isBase":false,"CODE":"[HP'_C]","isMetric":"no","isSpecial":"yes","class":"clinical","names":["homeopathic potency of centesimal series (retired)"],"printSymbols":["C"],"properties":["homeopathic potency (retired)"],"values":[{"printable":"","numeric":null}]}}};}, "[hp'_M]", { type: "literal", value: "[hp'_M]", description: "\"[hp'_M]\"" }, function(u) {return {"value": 1, "units": {"[hp'_M]": 1}, "metadata": {"[hp'_M]":{"isBase":false,"CODE":"[HP'_M]","isMetric":"no","isSpecial":"yes","class":"clinical","names":["homeopathic potency of millesimal series (retired)"],"printSymbols":["M"],"properties":["homeopathic potency (retired)"],"values":[{"printable":"","numeric":null}]}}};}, "[hp'_Q]", { type: "literal", value: "[hp'_Q]", description: "\"[hp'_Q]\"" }, function(u) {return {"value": 1, "units": {"[hp'_Q]": 1}, "metadata": {"[hp'_Q]":{"isBase":false,"CODE":"[HP'_Q]","isMetric":"no","isSpecial":"yes","class":"clinical","names":["homeopathic potency of quintamillesimal series (retired)"],"printSymbols":["Q"],"properties":["homeopathic potency (retired)"],"values":[{"printable":"","numeric":null}]}}};}, "[mi_br]", { type: "literal", value: "[mi_br]", description: "\"[mi_br]\"" }, function(u) {return {"value": 1, "units": {"[mi_br]": 1}, "metadata": {"[mi_br]":{"isBase":false,"CODE":"[MI_BR]","isMetric":"no","class":"brit-length","names":["mile"],"properties":["length"],"values":[{"printable":"5280","numeric":5280}]}}};}, "[mi_us]", { type: "literal", value: "[mi_us]", description: "\"[mi_us]\"" }, function(u) {return {"value": 1, "units": {"[mi_us]": 1}, "metadata": {"[mi_us]":{"isBase":false,"CODE":"[MI_US]","isMetric":"no","class":"us-lengths","names":["mile"],"properties":["length"],"values":[{"printable":"8","numeric":8}]}}};}, "[yd_br]", { type: "literal", value: "[yd_br]", description: "\"[yd_br]\"" }, function(u) {return {"value": 1, "units": {"[yd_br]": 1}, "metadata": {"[yd_br]":{"isBase":false,"CODE":"[YD_BR]","isMetric":"no","class":"brit-length","names":["yard"],"properties":["length"],"values":[{"printable":"3","numeric":3}]}}};}, "[pk_br]", { type: "literal", value: "[pk_br]", description: "\"[pk_br]\"" }, function(u) {return {"value": 1, "units": {"[pk_br]": 1}, "metadata": {"[pk_br]":{"isBase":false,"CODE":"[PK_BR]","isMetric":"no","class":"brit-volumes","names":["peck"],"properties":["volume"],"values":[{"printable":"2","numeric":2}]}}};}, "[pc_br]", { type: "literal", value: "[pc_br]", description: "\"[pc_br]\"" }, function(u) {return {"value": 1, "units": {"[pc_br]": 1}, "metadata": {"[pc_br]":{"isBase":false,"CODE":"[PC_BR]","isMetric":"no","class":"brit-length","names":["pace"],"properties":["length"],"values":[{"printable":"2.5","numeric":2.5}]}}};}, "[lk_br]", { type: "literal", value: "[lk_br]", description: "\"[lk_br]\"" }, function(u) {return {"value": 1, "units": {"[lk_br]": 1}, "metadata": {"[lk_br]":{"isBase":false,"CODE":"[LK_BR]","isMetric":"no","class":"brit-length","names":["link for Gunter's chain"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[in_br]", { type: "literal", value: "[in_br]", description: "\"[in_br]\"" }, function(u) {return {"value": 1, "units": {"[in_br]": 1}, "metadata": {"[in_br]":{"isBase":false,"CODE":"[IN_BR]","isMetric":"no","class":"brit-length","names":["inch"],"properties":["length"],"values":[{"printable":"2.539998","numeric":2.539998}]}}};}, "[ft_br]", { type: "literal", value: "[ft_br]", description: "\"[ft_br]\"" }, function(u) {return {"value": 1, "units": {"[ft_br]": 1}, "metadata": {"[ft_br]":{"isBase":false,"CODE":"[FT_BR]","isMetric":"no","class":"brit-length","names":["foot"],"properties":["length"],"values":[{"printable":"12","numeric":12}]}}};}, "[rd_br]", { type: "literal", value: "[rd_br]", description: "\"[rd_br]\"" }, function(u) {return {"value": 1, "units": {"[rd_br]": 1}, "metadata": {"[rd_br]":{"isBase":false,"CODE":"[RD_BR]","isMetric":"no","class":"brit-length","names":["rod"],"properties":["length"],"values":[{"printable":"16.5","numeric":16.5}]}}};}, "[ch_br]", { type: "literal", value: "[ch_br]", description: "\"[ch_br]\"" }, function(u) {return {"value": 1, "units": {"[ch_br]": 1}, "metadata": {"[ch_br]":{"isBase":false,"CODE":"[CH_BR]","isMetric":"no","class":"brit-length","names":["Gunter's chain"],"properties":["length"],"values":[{"printable":"4","numeric":4}]}}};}, "[ft_i]", { type: "literal", value: "[ft_i]", description: "\"[ft_i]\"" }, function(u) {return {"value": 1, "units": {"[ft_i]": 1}, "metadata": {"[ft_i]":{"isBase":false,"CODE":"[FT_I]","isMetric":"no","class":"intcust","names":["foot"],"printSymbols":["ft"],"properties":["length"],"values":[{"printable":"12","numeric":12}]}}};}, "[hp_Q]", { type: "literal", value: "[hp_Q]", description: "\"[hp_Q]\"" }, function(u) {return {"value": 1, "units": {"[hp_Q]": 1}, "metadata": {"[hp_Q]":{"isBase":false,"CODE":"[HP_Q]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of quintamillesimal hahnemannian series"],"printSymbols":["Q"],"properties":["homeopathic potency (Hahnemann)"],"values":[{"printable":"1","numeric":1}]}}};}, "[hp_M]", { type: "literal", value: "[hp_M]", description: "\"[hp_M]\"" }, function(u) {return {"value": 1, "units": {"[hp_M]": 1}, "metadata": {"[hp_M]":{"isBase":false,"CODE":"[HP_M]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of millesimal hahnemannian series"],"printSymbols":["M"],"properties":["homeopathic potency (Hahnemann)"],"values":[{"printable":"1","numeric":1}]}}};}, "[hp_C]", { type: "literal", value: "[hp_C]", description: "\"[hp_C]\"" }, function(u) {return {"value": 1, "units": {"[hp_C]": 1}, "metadata": {"[hp_C]":{"isBase":false,"CODE":"[HP_C]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of centesimal hahnemannian series"],"printSymbols":["C"],"properties":["homeopathic potency (Hahnemann)"],"values":[{"printable":"1","numeric":1}]}}};}, "[hp_X]", { type: "literal", value: "[hp_X]", description: "\"[hp_X]\"" }, function(u) {return {"value": 1, "units": {"[hp_X]": 1}, "metadata": {"[hp_X]":{"isBase":false,"CODE":"[HP_X]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of decimal hahnemannian series"],"printSymbols":["X"],"properties":["homeopathic potency (Hahnemann)"],"values":[{"printable":"1","numeric":1}]}}};}, "[kp_C]", { type: "literal", value: "[kp_C]", description: "\"[kp_C]\"" }, function(u) {return {"value": 1, "units": {"[kp_C]": 1}, "metadata": {"[kp_C]":{"isBase":false,"CODE":"[KP_C]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of centesimal korsakovian series"],"printSymbols":["C"],"properties":["homeopathic potency (Korsakov)"],"values":[{"printable":"1","numeric":1}]}}};}, "[hd_i]", { type: "literal", value: "[hd_i]", description: "\"[hd_i]\"" }, function(u) {return {"value": 1, "units": {"[hd_i]": 1}, "metadata": {"[hd_i]":{"isBase":false,"CODE":"[HD_I]","isMetric":"no","class":"intcust","names":["hand"],"printSymbols":["hd"],"properties":["height of horses"],"values":[{"printable":"4","numeric":4}]}}};}, "[kp_M]", { type: "literal", value: "[kp_M]", description: "\"[kp_M]\"" }, function(u) {return {"value": 1, "units": {"[kp_M]": 1}, "metadata": {"[kp_M]":{"isBase":false,"CODE":"[KP_M]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of millesimal korsakovian series"],"printSymbols":["M"],"properties":["homeopathic potency (Korsakov)"],"values":[{"printable":"1","numeric":1}]}}};}, "[kp_Q]", { type: "literal", value: "[kp_Q]", description: "\"[kp_Q]\"" }, function(u) {return {"value": 1, "units": {"[kp_Q]": 1}, "metadata": {"[kp_Q]":{"isBase":false,"CODE":"[KP_Q]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of quintamillesimal korsakovian series"],"printSymbols":["Q"],"properties":["homeopathic potency (Korsakov)"],"values":[{"printable":"1","numeric":1}]}}};}, "[cr_i]", { type: "literal", value: "[cr_i]", description: "\"[cr_i]\"" }, function(u) {return {"value": 1, "units": {"[cr_i]": 1}, "metadata": {"[cr_i]":{"isBase":false,"CODE":"[CR_I]","isMetric":"no","class":"intcust","names":["cord"],"properties":["volume"],"values":[{"printable":"128","numeric":128}]}}};}, "[bf_i]", { type: "literal", value: "[bf_i]", description: "\"[bf_i]\"" }, function(u) {return {"value": 1, "units": {"[bf_i]": 1}, "metadata": {"[bf_i]":{"isBase":false,"CODE":"[BF_I]","isMetric":"no","class":"intcust","names":["board foot"],"properties":["volume"],"values":[{"printable":"144","numeric":144}]}}};}, "[kn_i]", { type: "literal", value: "[kn_i]", description: "\"[kn_i]\"" }, function(u) {return {"value": 1, "units": {"[kn_i]": 1}, "metadata": {"[kn_i]":{"isBase":false,"CODE":"[KN_I]","isMetric":"no","class":"intcust","names":["knot"],"printSymbols":["knot"],"properties":["velocity"],"values":[{"printable":"1","numeric":1}]}}};}, "[mu_0]", { type: "literal", value: "[mu_0]", description: "\"[mu_0]\"" }, function(u) {return {"value": 1, "units": {"[mu_0]": 1}, "metadata": {"[mu_0]":{"isBase":false,"CODE":"[MU_0]","isMetric":"yes","class":"const","names":["permeability of vacuum"],"printSymbols":["μ\n 0\n \n "],"properties":["magnetic permeability"],"values":[{"printable":"1","numeric":1}]}}};}, "[mi_i]", { type: "literal", value: "[mi_i]", description: "\"[mi_i]\"" }, function(u) {return {"value": 1, "units": {"[mi_i]": 1}, "metadata": {"[mi_i]":{"isBase":false,"CODE":"[MI_I]","isMetric":"no","class":"intcust","names":["statute mile"],"printSymbols":["mi"],"properties":["length"],"values":[{"printable":"5280","numeric":5280}]}}};}, "[yd_i]", { type: "literal", value: "[yd_i]", description: "\"[yd_i]\"" }, function(u) {return {"value": 1, "units": {"[yd_i]": 1}, "metadata": {"[yd_i]":{"isBase":false,"CODE":"[YD_I]","isMetric":"no","class":"intcust","names":["yard"],"printSymbols":["yd"],"properties":["length"],"values":[{"printable":"3","numeric":3}]}}};}, "[kp_X]", { type: "literal", value: "[kp_X]", description: "\"[kp_X]\"" }, function(u) {return {"value": 1, "units": {"[kp_X]": 1}, "metadata": {"[kp_X]":{"isBase":false,"CODE":"[KP_X]","isMetric":"no","isArbitrary":"yes","class":"clinical","names":["homeopathic potency of decimal korsakovian series"],"printSymbols":["X"],"properties":["homeopathic potency (Korsakov)"],"values":[{"printable":"1","numeric":1}]}}};}, "[in_i]", { type: "literal", value: "[in_i]", description: "\"[in_i]\"" }, function(u) {return {"value": 1, "units": {"[in_i]": 1}, "metadata": {"[in_i]":{"isBase":false,"CODE":"[IN_I]","isMetric":"no","class":"intcust","names":["inch"],"printSymbols":["in"],"properties":["length"],"values":[{"printable":"2.54","numeric":2.54}]}}};}, "[diop]", { type: "literal", value: "[diop]", description: "\"[diop]\"" }, function(u) {return {"value": 1, "units": {"[diop]": 1}, "metadata": {"[diop]":{"isBase":false,"CODE":"[DIOP]","isMetric":"no","class":"clinical","names":["diopter"],"printSymbols":["dpt"],"properties":["refraction of a lens"],"values":[{"printable":"1","numeric":1}]}}};}, "cal_IT", { type: "literal", value: "cal_IT", description: "\"cal_IT\"" }, function(u) {return {"value": 1, "units": {"cal_IT": 1}, "metadata": {"cal_IT":{"isBase":false,"CODE":"CAL_IT","isMetric":"yes","class":"heat","names":["international table calorie"],"printSymbols":["calIT"],"properties":["energy"],"values":[{"printable":"4.1868","numeric":4.1868}]}}};}, "cal_th", { type: "literal", value: "cal_th", description: "\"cal_th\"" }, function(u) {return {"value": 1, "units": {"cal_th": 1}, "metadata": {"cal_th":{"isBase":false,"CODE":"CAL_TH","isMetric":"yes","class":"heat","names":["thermochemical calorie"],"printSymbols":["calth"],"properties":["energy"],"values":[{"printable":"4.184","numeric":4.184}]}}};}, "m[H2O]", { type: "literal", value: "m[H2O]", description: "\"m[H2O]\"" }, function(u) {return {"value": 1, "units": {"m[H2O]": 1}, "metadata": {"m[H2O]":{"isBase":false,"CODE":"M[H2O]","isMetric":"yes","class":"clinical","names":["meter of water column"],"printSymbols":["m H\n 2\n O"],"properties":["pressure"],"values":[{"printable":"9.80665","numeric":9.80665}]}}};}, "[ka'U]", { type: "literal", value: "[ka'U]", description: "\"[ka'U]\"" }, function(u) {return {"value": 1, "units": {"[ka'U]": 1}, "metadata": {"[ka'U]":{"isBase":false,"CODE":"[KA'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["King-Armstrong unit"],"properties":["biologic activity of phosphatase"],"values":[{"printable":"1","numeric":1}]}}};}, "B[SPL]", { type: "literal", value: "B[SPL]", description: "\"B[SPL]\"" }, function(u) {return {"value": 1, "units": {"B[SPL]": 1}, "metadata": {"B[SPL]":{"isBase":false,"CODE":"B[SPL]","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel sound pressure"],"printSymbols":["B(SPL)"],"properties":["pressure level"],"values":[{"printable":"","numeric":null}]}}};}, "[tb'U]", { type: "literal", value: "[tb'U]", description: "\"[tb'U]\"" }, function(u) {return {"value": 1, "units": {"[tb'U]": 1}, "metadata": {"[tb'U]":{"isBase":false,"CODE":"[TB'U]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["tuberculin unit"],"properties":["biologic activity of tuberculin"],"values":[{"printable":"1","numeric":1}]}}};}, "[degR]", { type: "literal", value: "[degR]", description: "\"[degR]\"" }, function(u) {return {"value": 1, "units": {"[degR]": 1}, "metadata": {"[degR]":{"isBase":false,"CODE":"[degR]","isMetric":"no","class":"heat","names":["degree Rankine"],"printSymbols":["°R"],"properties":["temperature"],"values":[{"printable":"5","numeric":5}]}}};}, "[degF]", { type: "literal", value: "[degF]", description: "\"[degF]\"" }, function(u) {return {"value": 1, "units": {"[degF]": 1}, "metadata": {"[degF]":{"isBase":false,"CODE":"[DEGF]","isMetric":"no","isSpecial":"yes","class":"heat","names":["degree Fahrenheit"],"printSymbols":["°F"],"properties":["temperature"],"values":[{"printable":"","numeric":null}]}}};}, "[pptr]", { type: "literal", value: "[pptr]", description: "\"[pptr]\"" }, function(u) {return {"value": 1, "units": {"[pptr]": 1}, "metadata": {"[pptr]":{"isBase":false,"CODE":"[PPTR]","isMetric":"no","class":"dimless","names":["parts per trillion"],"printSymbols":["pptr"],"properties":["fraction"],"values":[{"printable":"1","numeric":1}]}}};}, "[ppth]", { type: "literal", value: "[ppth]", description: "\"[ppth]\"" }, function(u) {return {"value": 1, "units": {"[ppth]": 1}, "metadata": {"[ppth]":{"isBase":false,"CODE":"[PPTH]","isMetric":"no","class":"dimless","names":["parts per thousand"],"printSymbols":["ppth"],"properties":["fraction"],"values":[{"printable":"1","numeric":1}]}}};}, "[oz_m]", { type: "literal", value: "[oz_m]", description: "\"[oz_m]\"" }, function(u) {return {"value": 1, "units": {"[oz_m]": 1}, "metadata": {"[oz_m]":{"isBase":false,"CODE":"[OZ_M]","isMetric":"no","class":"apoth","names":["metric ounce"],"properties":["mass"],"values":[{"printable":"28","numeric":28}]}}};}, "[pied]", { type: "literal", value: "[pied]", description: "\"[pied]\"" }, function(u) {return {"value": 1, "units": {"[pied]": 1}, "metadata": {"[pied]":{"isBase":false,"CODE":"[PIED]","isMetric":"no","class":"typeset","names":["pied","French foot"],"properties":["length"],"values":[{"printable":"32.48","numeric":32.48}]}}};}, "[ppm]", { type: "literal", value: "[ppm]", description: "\"[ppm]\"" }, function(u) {return {"value": 1, "units": {"[ppm]": 1}, "metadata": {"[ppm]":{"isBase":false,"CODE":"[PPM]","isMetric":"no","class":"dimless","names":["parts per million"],"printSymbols":["ppm"],"properties":["fraction"],"values":[{"printable":"1","numeric":1}]}}};}, "[ppb]", { type: "literal", value: "[ppb]", description: "\"[ppb]\"" }, function(u) {return {"value": 1, "units": {"[ppb]": 1}, "metadata": {"[ppb]":{"isBase":false,"CODE":"[PPB]","isMetric":"no","class":"dimless","names":["parts per billion"],"printSymbols":["ppb"],"properties":["fraction"],"values":[{"printable":"1","numeric":1}]}}};}, "bit_s", { type: "literal", value: "bit_s", description: "\"bit_s\"" }, function(u) {return {"value": 1, "units": {"bit_s": 1}, "metadata": {"bit_s":{"isBase":false,"CODE":"BIT_S","isMetric":"no","isSpecial":"yes","class":"infotech","names":["bit"],"printSymbols":["bits"],"properties":["amount of information"],"values":[{"printable":"","numeric":null}]}}};}, "[PNU]", { type: "literal", value: "[PNU]", description: "\"[PNU]\"" }, function(u) {return {"value": 1, "units": {"[PNU]": 1}, "metadata": {"[PNU]":{"isBase":false,"CODE":"[PNU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["protein nitrogen unit"],"printSymbols":["PNU"],"properties":["procedure defined amount of a protein substance"],"values":[{"printable":"1","numeric":1}]}}};}, "[psi]", { type: "literal", value: "[psi]", description: "\"[psi]\"" }, function(u) {return {"value": 1, "units": {"[psi]": 1}, "metadata": {"[psi]":{"isBase":false,"CODE":"[PSI]","isMetric":"no","class":"misc","names":["pound per sqare inch"],"printSymbols":["psi"],"properties":["pressure"],"values":[{"printable":"1","numeric":1}]}}};}, "[BAU]", { type: "literal", value: "[BAU]", description: "\"[BAU]\"" }, function(u) {return {"value": 1, "units": {"[BAU]": 1}, "metadata": {"[BAU]":{"isBase":false,"CODE":"[BAU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["bioequivalent allergen unit"],"printSymbols":["BAU"],"properties":["amount of an allergen callibrated through in-vivo testing based on the ID50EAL method of (intradermal dilution for 50mm sum of erythema diameters"],"values":[{"printable":"1","numeric":1}]}}};}, "[Cal]", { type: "literal", value: "[Cal]", description: "\"[Cal]\"" }, function(u) {return {"value": 1, "units": {"[Cal]": 1}, "metadata": {"[Cal]":{"isBase":false,"CODE":"[CAL]","isMetric":"no","class":"heat","names":["nutrition label Calories"],"printSymbols":["Cal"],"properties":["energy"],"values":[{"printable":"1","numeric":1}]}}};}, "B[mV]", { type: "literal", value: "B[mV]", description: "\"B[mV]\"" }, function(u) {return {"value": 1, "units": {"B[mV]": 1}, "metadata": {"B[mV]":{"isBase":false,"CODE":"B[MV]","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel millivolt"],"printSymbols":["B(mV)"],"properties":["electric potential level"],"values":[{"printable":"","numeric":null}]}}};}, "B[uV]", { type: "literal", value: "B[uV]", description: "\"B[uV]\"" }, function(u) {return {"value": 1, "units": {"B[uV]": 1}, "metadata": {"B[uV]":{"isBase":false,"CODE":"B[UV]","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel microvolt"],"printSymbols":["B(μV)"],"properties":["electric potential level"],"values":[{"printable":"","numeric":null}]}}};}, "[CFU]", { type: "literal", value: "[CFU]", description: "\"[CFU]\"" }, function(u) {return {"value": 1, "units": {"[CFU]": 1}, "metadata": {"[CFU]":{"isBase":false,"CODE":"[CFU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["colony forming units"],"printSymbols":["CFU"],"properties":["amount of a proliferating organism"],"values":[{"printable":"1","numeric":1}]}}};}, "[FFU]", { type: "literal", value: "[FFU]", description: "\"[FFU]\"" }, function(u) {return {"value": 1, "units": {"[FFU]": 1}, "metadata": {"[FFU]":{"isBase":false,"CODE":"[FFU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["focus forming units"],"printSymbols":["FFU"],"properties":["amount of an infectious agent"],"values":[{"printable":"1","numeric":1}]}}};}, "B[kW]", { type: "literal", value: "B[kW]", description: "\"B[kW]\"" }, function(u) {return {"value": 1, "units": {"B[kW]": 1}, "metadata": {"B[kW]":{"isBase":false,"CODE":"B[KW]","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel kilowatt"],"printSymbols":["B(kW)"],"properties":["power level"],"values":[{"printable":"","numeric":null}]}}};}, "[PFU]", { type: "literal", value: "[PFU]", description: "\"[PFU]\"" }, function(u) {return {"value": 1, "units": {"[PFU]": 1}, "metadata": {"[PFU]":{"isBase":false,"CODE":"[PFU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["plaque forming units"],"printSymbols":["PFU"],"properties":["amount of an infectious agent"],"values":[{"printable":"1","numeric":1}]}}};}, "cal_m", { type: "literal", value: "cal_m", description: "\"cal_m\"" }, function(u) {return {"value": 1, "units": {"cal_m": 1}, "metadata": {"cal_m":{"isBase":false,"CODE":"CAL_M","isMetric":"yes","class":"heat","names":["mean calorie"],"printSymbols":["calm"],"properties":["energy"],"values":[{"printable":"4.19002","numeric":4.19002}]}}};}, "[ELU]", { type: "literal", value: "[ELU]", description: "\"[ELU]\"" }, function(u) {return {"value": 1, "units": {"[ELU]": 1}, "metadata": {"[ELU]":{"isBase":false,"CODE":"[ELU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["ELISA unit"],"printSymbols":[""],"properties":["arbitrary ELISA unit"],"values":[{"printable":"1","numeric":1}]}}};}, "[FEU]", { type: "literal", value: "[FEU]", description: "\"[FEU]\"" }, function(u) {return {"value": 1, "units": {"[FEU]": 1}, "metadata": {"[FEU]":{"isBase":false,"CODE":"[FEU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["fibrinogen equivalent unit"],"printSymbols":[""],"properties":["amount of fibrinogen broken down into the measured d-dimers"],"values":[{"printable":"1","numeric":1}]}}};}, "[PRU]", { type: "literal", value: "[PRU]", description: "\"[PRU]\"" }, function(u) {return {"value": 1, "units": {"[PRU]": 1}, "metadata": {"[PRU]":{"isBase":false,"CODE":"[PRU]","isMetric":"no","class":"clinical","names":["peripheral vascular resistance unit"],"printSymbols":["P.R.U."],"properties":["fluid resistance"],"values":[{"printable":"1","numeric":1}]}}};}, "[m_e]", { type: "literal", value: "[m_e]", description: "\"[m_e]\"" }, function(u) {return {"value": 1, "units": {"[m_e]": 1}, "metadata": {"[m_e]":{"isBase":false,"CODE":"[M_E]","isMetric":"yes","class":"const","names":["electron mass"],"printSymbols":["m\n e\n \n "],"properties":["mass"],"values":[{"printable":"9.1093897 × 10-28","numeric":9.1093897e-28}]}}};}, "[m_p]", { type: "literal", value: "[m_p]", description: "\"[m_p]\"" }, function(u) {return {"value": 1, "units": {"[m_p]": 1}, "metadata": {"[m_p]":{"isBase":false,"CODE":"[M_P]","isMetric":"yes","class":"const","names":["proton mass"],"printSymbols":["m\n p\n \n "],"properties":["mass"],"values":[{"printable":"1.6726231 × 10-24","numeric":1.6726231e-24}]}}};}, "m[Hg]", { type: "literal", value: "m[Hg]", description: "\"m[Hg]\"" }, function(u) {return {"value": 1, "units": {"m[Hg]": 1}, "metadata": {"m[Hg]":{"isBase":false,"CODE":"M[HG]","isMetric":"yes","class":"clinical","names":["meter of mercury column"],"printSymbols":["m Hg"],"properties":["pressure"],"values":[{"printable":"133.3220","numeric":133.322}]}}};}, "[pca]", { type: "literal", value: "[pca]", description: "\"[pca]\"" }, function(u) {return {"value": 1, "units": {"[pca]": 1}, "metadata": {"[pca]":{"isBase":false,"CODE":"[PCA]","isMetric":"no","class":"typeset","names":["pica"],"properties":["length"],"values":[{"printable":"12","numeric":12}]}}};}, "[pnt]", { type: "literal", value: "[pnt]", description: "\"[pnt]\"" }, function(u) {return {"value": 1, "units": {"[pnt]": 1}, "metadata": {"[pnt]":{"isBase":false,"CODE":"[PNT]","isMetric":"no","class":"typeset","names":["point"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[lne]", { type: "literal", value: "[lne]", description: "\"[lne]\"" }, function(u) {return {"value": 1, "units": {"[lne]": 1}, "metadata": {"[lne]":{"isBase":false,"CODE":"[LNE]","isMetric":"no","class":"typeset","names":["line"],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[LPF]", { type: "literal", value: "[LPF]", description: "\"[LPF]\"" }, function(u) {return {"value": 1, "units": {"[LPF]": 1}, "metadata": {"[LPF]":{"isBase":false,"CODE":"[LPF]","isMetric":"no","class":"chemical","names":["low power field"],"printSymbols":["LPF"],"properties":["view area in microscope"],"values":[{"printable":"100","numeric":100}]}}};}, "[den]", { type: "literal", value: "[den]", description: "\"[den]\"" }, function(u) {return {"value": 1, "units": {"[den]": 1}, "metadata": {"[den]":{"isBase":false,"CODE":"[DEN]","isMetric":"no","class":"heat","names":["Denier"],"printSymbols":["den"],"properties":["linear mass density (of textile thread)"],"values":[{"printable":"1","numeric":1}]}}};}, "[sct]", { type: "literal", value: "[sct]", description: "\"[sct]\"" }, function(u) {return {"value": 1, "units": {"[sct]": 1}, "metadata": {"[sct]":{"isBase":false,"CODE":"[SCT]","isMetric":"no","class":"us-lengths","names":["section"],"properties":["area"],"values":[{"printable":"1","numeric":1}]}}};}, "[twp]", { type: "literal", value: "[twp]", description: "\"[twp]\"" }, function(u) {return {"value": 1, "units": {"[twp]": 1}, "metadata": {"[twp]":{"isBase":false,"CODE":"[TWP]","isMetric":"no","class":"us-lengths","names":["township"],"properties":["area"],"values":[{"printable":"36","numeric":36}]}}};}, "[Btu]", { type: "literal", value: "[Btu]", description: "\"[Btu]\"" }, function(u) {return {"value": 1, "units": {"[Btu]": 1}, "metadata": {"[Btu]":{"isBase":false,"CODE":"[BTU]","isMetric":"no","class":"heat","names":["British thermal unit"],"printSymbols":["btu"],"properties":["energy"],"values":[{"printable":"1","numeric":1}]}}};}, "[MET]", { type: "literal", value: "[MET]", description: "\"[MET]\"" }, function(u) {return {"value": 1, "units": {"[MET]": 1}, "metadata": {"[MET]":{"isBase":false,"CODE":"[MET]","isMetric":"no","class":"clinical","names":["metabolic equivalent"],"printSymbols":["MET"],"properties":["metabolic cost of physical activity"],"values":[{"printable":"3.5","numeric":3.5}]}}};}, "[HPF]", { type: "literal", value: "[HPF]", description: "\"[HPF]\"" }, function(u) {return {"value": 1, "units": {"[HPF]": 1}, "metadata": {"[HPF]":{"isBase":false,"CODE":"[HPF]","isMetric":"no","class":"chemical","names":["high power field"],"printSymbols":["HPF"],"properties":["view area in microscope"],"values":[{"printable":"1","numeric":1}]}}};}, "[drp]", { type: "literal", value: "[drp]", description: "\"[drp]\"" }, function(u) {return {"value": 1, "units": {"[drp]": 1}, "metadata": {"[drp]":{"isBase":false,"CODE":"[DRP]","isMetric":"no","class":"clinical","names":["drop"],"printSymbols":["drp"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "[AU]", { type: "literal", value: "[AU]", description: "\"[AU]\"" }, function(u) {return {"value": 1, "units": {"[AU]": 1}, "metadata": {"[AU]":{"isBase":false,"CODE":"[AU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["allergen unit"],"printSymbols":["AU"],"properties":["procedure defined amount of an allergen using some reference standard"],"values":[{"printable":"1","numeric":1}]}}};}, "[IU]", { type: "literal", value: "[IU]", description: "\"[IU]\"" }, function(u) {return {"value": 1, "units": {"[IU]": 1}, "metadata": {"[IU]":{"isBase":false,"CODE":"[IU]","isMetric":"yes","isArbitrary":"yes","class":"chemical","names":["international unit"],"printSymbols":["i.U."],"properties":["arbitrary"],"values":[{"printable":"1","numeric":1}]}}};}, "mo_s", { type: "literal", value: "mo_s", description: "\"mo_s\"" }, function(u) {return {"value": 1, "units": {"mo_s": 1}, "metadata": {"mo_s":{"isBase":false,"CODE":"MO_S","isMetric":"no","class":"iso1000","names":["synodal month"],"printSymbols":["mos"],"properties":["time"],"values":[{"printable":"29.53059","numeric":29.53059}]}}};}, "[gr]", { type: "literal", value: "[gr]", description: "\"[gr]\"" }, function(u) {return {"value": 1, "units": {"[gr]": 1}, "metadata": {"[gr]":{"isBase":false,"CODE":"[GR]","isMetric":"no","class":"avoirdupois","names":["grain"],"properties":["mass"],"values":[{"printable":"64.79891","numeric":64.79891}]}}};}, "circ", { type: "literal", value: "circ", description: "\"circ\"" }, function(u) {return {"value": 1, "units": {"circ": 1}, "metadata": {"circ":{"isBase":false,"CODE":"CIRC","isMetric":"no","class":"misc","names":["circle"],"printSymbols":["circ"],"properties":["plane angle"],"values":[{"printable":"2","numeric":2}]}}};}, "[pi]", { type: "literal", value: "[pi]", description: "\"[pi]\"" }, function(u) {return {"value": 1, "units": {"[pi]": 1}, "metadata": {"[pi]":{"isBase":false,"CODE":"[PI]","isMetric":"no","class":"dimless","names":["the number pi"],"printSymbols":["π"],"properties":["number"],"values":[{"printable":"π","numeric":3.141592653589793}]}}};}, "[EU]", { type: "literal", value: "[EU]", description: "\"[EU]\"" }, function(u) {return {"value": 1, "units": {"[EU]": 1}, "metadata": {"[EU]":{"isBase":false,"CODE":"[EU]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Ehrlich unit"],"printSymbols":[""],"properties":["Ehrlich unit"],"values":[{"printable":"1","numeric":1}]}}};}, "[Lf]", { type: "literal", value: "[Lf]", description: "\"[Lf]\"" }, function(u) {return {"value": 1, "units": {"[Lf]": 1}, "metadata": {"[Lf]":{"isBase":false,"CODE":"[LF]","isMetric":"no","isArbitrary":"yes","class":"chemical","names":["Limit of flocculation"],"printSymbols":["Lf"],"properties":["procedure defined amount of an antigen substance"],"values":[{"printable":"1","numeric":1}]}}};}, "mo_j", { type: "literal", value: "mo_j", description: "\"mo_j\"" }, function(u) {return {"value": 1, "units": {"mo_j": 1}, "metadata": {"mo_j":{"isBase":false,"CODE":"MO_J","isMetric":"no","class":"iso1000","names":["mean Julian month"],"printSymbols":["moj"],"properties":["time"],"values":[{"printable":"1","numeric":1}]}}};}, "B[W]", { type: "literal", value: "B[W]", description: "\"B[W]\"" }, function(u) {return {"value": 1, "units": {"B[W]": 1}, "metadata": {"B[W]":{"isBase":false,"CODE":"B[W]","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel watt"],"printSymbols":["B(W)"],"properties":["power level"],"values":[{"printable":"","numeric":null}]}}};}, "B[V]", { type: "literal", value: "B[V]", description: "\"B[V]\"" }, function(u) {return {"value": 1, "units": {"B[V]": 1}, "metadata": {"B[V]":{"isBase":false,"CODE":"B[V]","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel volt"],"printSymbols":["B(V)"],"properties":["electric potential level"],"values":[{"printable":"","numeric":null}]}}};}, "mo_g", { type: "literal", value: "mo_g", description: "\"mo_g\"" }, function(u) {return {"value": 1, "units": {"mo_g": 1}, "metadata": {"mo_g":{"isBase":false,"CODE":"MO_G","isMetric":"no","class":"iso1000","names":["mean Gregorian month"],"printSymbols":["mog"],"properties":["time"],"values":[{"printable":"1","numeric":1}]}}};}, "[iU]", { type: "literal", value: "[iU]", description: "\"[iU]\"" }, function(u) {return {"value": 1, "units": {"[iU]": 1}, "metadata": {"[iU]":{"isBase":false,"CODE":"[IU]","isMetric":"yes","isArbitrary":"yes","class":"chemical","names":["international unit"],"printSymbols":["IU"],"properties":["arbitrary"],"values":[{"printable":"1","numeric":1}]}}};}, "[HP]", { type: "literal", value: "[HP]", description: "\"[HP]\"" }, function(u) {return {"value": 1, "units": {"[HP]": 1}, "metadata": {"[HP]":{"isBase":false,"CODE":"[HP]","isMetric":"no","class":"heat","names":["horsepower"],"properties":["power"],"values":[{"printable":"550","numeric":550}]}}};}, "[Ch]", { type: "literal", value: "[Ch]", description: "\"[Ch]\"" }, function(u) {return {"value": 1, "units": {"[Ch]": 1}, "metadata": {"[Ch]":{"isBase":false,"CODE":"[CH]","isMetric":"no","class":"clinical","names":["Charrière","french"],"printSymbols":["Ch"],"properties":["gauge of catheters"],"values":[{"printable":"1","numeric":1}]}}};}, "[ly]", { type: "literal", value: "[ly]", description: "\"[ly]\"" }, function(u) {return {"value": 1, "units": {"[ly]": 1}, "metadata": {"[ly]":{"isBase":false,"CODE":"[LY]","isMetric":"yes","class":"const","names":["light-year"],"printSymbols":["l.y."],"properties":["length"],"values":[{"printable":"1","numeric":1}]}}};}, "[pH]", { type: "literal", value: "[pH]", description: "\"[pH]\"" }, function(u) {return {"value": 1, "units": {"[pH]": 1}, "metadata": {"[pH]":{"isBase":false,"CODE":"[PH]","isMetric":"no","isSpecial":"yes","class":"chemical","names":["pH"],"printSymbols":["pH"],"properties":["acidity"],"values":[{"printable":"","numeric":null}]}}};}, "a_j", { type: "literal", value: "a_j", description: "\"a_j\"" }, function(u) {return {"value": 1, "units": {"a_j": 1}, "metadata": {"a_j":{"isBase":false,"CODE":"ANN_J","isMetric":"no","class":"iso1000","names":["mean Julian year"],"printSymbols":["aj"],"properties":["time"],"values":[{"printable":"365.25","numeric":365.25}]}}};}, "rad", { type: "literal", value: "rad", description: "\"rad\"" }, function(u) {return {"value": 1, "units": {"rad": 1}, "metadata": {"rad":{"isBase":true,"CODE":"RAD","dim":"A","names":["radian"],"printSymbols":["rad"],"properties":["plane angle"]}}};}, "a_t", { type: "literal", value: "a_t", description: "\"a_t\"" }, function(u) {return {"value": 1, "units": {"a_t": 1}, "metadata": {"a_t":{"isBase":false,"CODE":"ANN_T","isMetric":"no","class":"iso1000","names":["tropical year"],"printSymbols":["at"],"properties":["time"],"values":[{"printable":"365.24219","numeric":365.24219}]}}};}, "Ohm", { type: "literal", value: "Ohm", description: "\"Ohm\"" }, function(u) {return {"value": 1, "units": {"Ohm": 1}, "metadata": {"Ohm":{"isBase":false,"CODE":"OHM","isMetric":"yes","class":"si","names":["Ohm"],"printSymbols":["Ω"],"properties":["electric resistance"],"values":[{"printable":"1","numeric":1}]}}};}, "sph", { type: "literal", value: "sph", description: "\"sph\"" }, function(u) {return {"value": 1, "units": {"sph": 1}, "metadata": {"sph":{"isBase":false,"CODE":"SPH","isMetric":"no","class":"misc","names":["spere"],"printSymbols":["sph"],"properties":["solid angle"],"values":[{"printable":"4","numeric":4}]}}};}, "bit", { type: "literal", value: "bit", description: "\"bit\"" }, function(u) {return {"value": 1, "units": {"bit": 1}, "metadata": {"bit":{"isBase":false,"CODE":"BIT","isMetric":"yes","class":"infotech","names":["bit"],"printSymbols":["bit"],"properties":["amount of information"],"values":[{"printable":"1","numeric":1}]}}};}, "mho", { type: "literal", value: "mho", description: "\"mho\"" }, function(u) {return {"value": 1, "units": {"mho": 1}, "metadata": {"mho":{"isBase":false,"CODE":"MHO","isMetric":"yes","class":"misc","names":["mho"],"printSymbols":["mho"],"properties":["electric conductance"],"values":[{"printable":"1","numeric":1}]}}};}, "min", { type: "literal", value: "min", description: "\"min\"" }, function(u) {return {"value": 1, "units": {"min": 1}, "metadata": {"min":{"isBase":false,"CODE":"MIN","isMetric":"no","class":"iso1000","names":["minute"],"printSymbols":["min"],"properties":["time"],"values":[{"printable":"60","numeric":60}]}}};}, "mol", { type: "literal", value: "mol", description: "\"mol\"" }, function(u) {return {"value": 1, "units": {"mol": 1}, "metadata": {"mol":{"isBase":false,"CODE":"MOL","isMetric":"yes","class":"si","names":["mole"],"printSymbols":["mol"],"properties":["amount of substance"],"values":[{"printable":"6.0221367","numeric":6.0221367}]}}};}, "deg", { type: "literal", value: "deg", description: "\"deg\"" }, function(u) {return {"value": 1, "units": {"deg": 1}, "metadata": {"deg":{"isBase":false,"CODE":"DEG","isMetric":"no","class":"iso1000","names":["degree"],"printSymbols":["°"],"properties":["plane angle"],"values":[{"printable":"2","numeric":2}]}}};}, "gon", { type: "literal", value: "gon", description: "\"gon\"" }, function(u) {return {"value": 1, "units": {"gon": 1}, "metadata": {"gon":{"isBase":false,"CODE":"GON","isMetric":"no","class":"iso1000","names":["gon","grade"],"printSymbols":["□g"],"properties":["plane angle"],"values":[{"printable":"0.9","numeric":0.9}]}}};}, "Cel", { type: "literal", value: "Cel", description: "\"Cel\"" }, function(u) {return {"value": 1, "units": {"Cel": 1}, "metadata": {"Cel":{"isBase":false,"CODE":"CEL","isMetric":"yes","isSpecial":"yes","class":"si","names":["degree Celsius"],"printSymbols":["°C"],"properties":["temperature"],"values":[{"printable":"","numeric":null}]}}};}, "kat", { type: "literal", value: "kat", description: "\"kat\"" }, function(u) {return {"value": 1, "units": {"kat": 1}, "metadata": {"kat":{"isBase":false,"CODE":"KAT","isMetric":"yes","class":"chemical","names":["katal"],"printSymbols":["kat"],"properties":["catalytic activity"],"values":[{"printable":"1","numeric":1}]}}};}, "att", { type: "literal", value: "att", description: "\"att\"" }, function(u) {return {"value": 1, "units": {"att": 1}, "metadata": {"att":{"isBase":false,"CODE":"ATT","isMetric":"no","class":"misc","names":["technical atmosphere"],"printSymbols":["at"],"properties":["pressure"],"values":[{"printable":"1","numeric":1}]}}};}, "osm", { type: "literal", value: "osm", description: "\"osm\"" }, function(u) {return {"value": 1, "units": {"osm": 1}, "metadata": {"osm":{"isBase":false,"CODE":"OSM","isMetric":"yes","class":"chemical","names":["osmole"],"printSymbols":["osm"],"properties":["amount of substance (dissolved particles)"],"values":[{"printable":"1","numeric":1}]}}};}, "tex", { type: "literal", value: "tex", description: "\"tex\"" }, function(u) {return {"value": 1, "units": {"tex": 1}, "metadata": {"tex":{"isBase":false,"CODE":"TEX","isMetric":"yes","class":"heat","names":["tex"],"printSymbols":["tex"],"properties":["linear mass density (of textile thread)"],"values":[{"printable":"1","numeric":1}]}}};}, "cal", { type: "literal", value: "cal", description: "\"cal\"" }, function(u) {return {"value": 1, "units": {"cal": 1}, "metadata": {"cal":{"isBase":false,"CODE":"CAL","isMetric":"yes","class":"heat","names":["calorie"],"printSymbols":["cal"],"properties":["energy"],"values":[{"printable":"1","numeric":1}]}}};}, "REM", { type: "literal", value: "REM", description: "\"REM\"" }, function(u) {return {"value": 1, "units": {"REM": 1}, "metadata": {"REM":{"isBase":false,"CODE":"[REM]","isMetric":"yes","class":"cgs","names":["radiation equivalent man"],"printSymbols":["REM"],"properties":["dose equivalent"],"values":[{"printable":"1","numeric":1}]}}};}, "RAD", { type: "literal", value: "RAD", description: "\"RAD\"" }, function(u) {return {"value": 1, "units": {"RAD": 1}, "metadata": {"RAD":{"isBase":false,"CODE":"[RAD]","isMetric":"yes","class":"cgs","names":["radiation absorbed dose"],"printSymbols":["RAD"],"properties":["energy dose"],"values":[{"printable":"100","numeric":100}]}}};}, "a_g", { type: "literal", value: "a_g", description: "\"a_g\"" }, function(u) {return {"value": 1, "units": {"a_g": 1}, "metadata": {"a_g":{"isBase":false,"CODE":"ANN_G","isMetric":"no","class":"iso1000","names":["mean Gregorian year"],"printSymbols":["ag"],"properties":["time"],"values":[{"printable":"365.2425","numeric":365.2425}]}}};}, "Lmb", { type: "literal", value: "Lmb", description: "\"Lmb\"" }, function(u) {return {"value": 1, "units": {"Lmb": 1}, "metadata": {"Lmb":{"isBase":false,"CODE":"LMB","isMetric":"yes","class":"cgs","names":["Lambert"],"printSymbols":["L"],"properties":["brightness"],"values":[{"printable":"1","numeric":1}]}}};}, "atm", { type: "literal", value: "atm", description: "\"atm\"" }, function(u) {return {"value": 1, "units": {"atm": 1}, "metadata": {"atm":{"isBase":false,"CODE":"ATM","isMetric":"no","class":"const","names":["standard atmosphere"],"printSymbols":["atm"],"properties":["pressure"],"values":[{"printable":"101325","numeric":101325}]}}};}, "erg", { type: "literal", value: "erg", description: "\"erg\"" }, function(u) {return {"value": 1, "units": {"erg": 1}, "metadata": {"erg":{"isBase":false,"CODE":"ERG","isMetric":"yes","class":"cgs","names":["erg"],"printSymbols":["erg"],"properties":["energy"],"values":[{"printable":"1","numeric":1}]}}};}, "dyn", { type: "literal", value: "dyn", description: "\"dyn\"" }, function(u) {return {"value": 1, "units": {"dyn": 1}, "metadata": {"dyn":{"isBase":false,"CODE":"DYN","isMetric":"yes","class":"cgs","names":["dyne"],"printSymbols":["dyn"],"properties":["force"],"values":[{"printable":"1","numeric":1}]}}};}, "Gal", { type: "literal", value: "Gal", description: "\"Gal\"" }, function(u) {return {"value": 1, "units": {"Gal": 1}, "metadata": {"Gal":{"isBase":false,"CODE":"GL","isMetric":"yes","class":"cgs","names":["Gal"],"printSymbols":["Gal"],"properties":["acceleration"],"values":[{"printable":"1","numeric":1}]}}};}, "10^", { type: "literal", value: "10^", description: "\"10^\"" }, function(u) {return {"value": 1, "units": {"10^": 1}, "metadata": {"10^":{"isBase":false,"CODE":"10^","isMetric":"no","class":"dimless","names":["the number ten for arbitrary powers"],"printSymbols":["10"],"properties":["number"],"values":[{"printable":"10","numeric":10}]}}};}, "10*", { type: "literal", value: "10*", description: "\"10*\"" }, function(u) {return {"value": 1, "units": {"10*": 1}, "metadata": {"10*":{"isBase":false,"CODE":"10*","isMetric":"no","class":"dimless","names":["the number ten for arbitrary powers"],"printSymbols":["10"],"properties":["number"],"values":[{"printable":"10","numeric":10}]}}};}, "[S]", { type: "literal", value: "[S]", description: "\"[S]\"" }, function(u) {return {"value": 1, "units": {"[S]": 1}, "metadata": {"[S]":{"isBase":false,"CODE":"[S]","isMetric":"no","class":"chemical","names":["Svedberg unit"],"printSymbols":["S"],"properties":["sedimentation coefficient"],"values":[{"printable":"1","numeric":1}]}}};}, "[g]", { type: "literal", value: "[g]", description: "\"[g]\"" }, function(u) {return {"value": 1, "units": {"[g]": 1}, "metadata": {"[g]":{"isBase":false,"CODE":"[G]","isMetric":"yes","class":"const","names":["standard acceleration of free fall"],"printSymbols":["gn\n "],"properties":["acceleration"],"values":[{"printable":"9.80665","numeric":9.80665}]}}};}, "[G]", { type: "literal", value: "[G]", description: "\"[G]\"" }, function(u) {return {"value": 1, "units": {"[G]": 1}, "metadata": {"[G]":{"isBase":false,"CODE":"[GC]","isMetric":"yes","class":"const","names":["Newtonian constant of gravitation"],"printSymbols":["G"],"properties":["(unclassified)"],"values":[{"printable":"6.67259 × 10-11","numeric":6.67259e-11}]}}};}, "[e]", { type: "literal", value: "[e]", description: "\"[e]\"" }, function(u) {return {"value": 1, "units": {"[e]": 1}, "metadata": {"[e]":{"isBase":false,"CODE":"[E]","isMetric":"yes","class":"const","names":["elementary charge"],"printSymbols":["e"],"properties":["electric charge"],"values":[{"printable":"1.60217733 × 10-19","numeric":1.60217733e-19}]}}};}, "[k]", { type: "literal", value: "[k]", description: "\"[k]\"" }, function(u) {return {"value": 1, "units": {"[k]": 1}, "metadata": {"[k]":{"isBase":false,"CODE":"[K]","isMetric":"yes","class":"const","names":["Boltzmann constant"],"printSymbols":["k"],"properties":["(unclassified)"],"values":[{"printable":"1.380658 × 10-23","numeric":1.380658e-23}]}}};}, "[h]", { type: "literal", value: "[h]", description: "\"[h]\"" }, function(u) {return {"value": 1, "units": {"[h]": 1}, "metadata": {"[h]":{"isBase":false,"CODE":"[H]","isMetric":"yes","class":"const","names":["Planck constant"],"printSymbols":["h"],"properties":["action"],"values":[{"printable":"6.6260755 × 10-24","numeric":6.6260755e-24}]}}};}, "[c]", { type: "literal", value: "[c]", description: "\"[c]\"" }, function(u) {return {"value": 1, "units": {"[c]": 1}, "metadata": {"[c]":{"isBase":false,"CODE":"[C]","isMetric":"yes","class":"const","names":["velocity of light"],"printSymbols":["c"],"properties":["velocity"],"values":[{"printable":"299792458","numeric":299792458}]}}};}, "bar", { type: "literal", value: "bar", description: "\"bar\"" }, function(u) {return {"value": 1, "units": {"bar": 1}, "metadata": {"bar":{"isBase":false,"CODE":"BAR","isMetric":"yes","class":"iso1000","names":["bar"],"printSymbols":["bar"],"properties":["pressure"],"values":[{"printable":"1 × 105","numeric":100000}]}}};}, "lm", { type: "literal", value: "lm", description: "\"lm\"" }, function(u) {return {"value": 1, "units": {"lm": 1}, "metadata": {"lm":{"isBase":false,"CODE":"LM","isMetric":"yes","class":"si","names":["lumen"],"printSymbols":["lm"],"properties":["luminous flux"],"values":[{"printable":"1","numeric":1}]}}};}, "Ci", { type: "literal", value: "Ci", description: "\"Ci\"" }, function(u) {return {"value": 1, "units": {"Ci": 1}, "metadata": {"Ci":{"isBase":false,"CODE":"CI","isMetric":"yes","class":"cgs","names":["Curie"],"printSymbols":["Ci"],"properties":["radioactivity"],"values":[{"printable":"3.7 × 1010","numeric":37000000000}]}}};}, "ph", { type: "literal", value: "ph", description: "\"ph\"" }, function(u) {return {"value": 1, "units": {"ph": 1}, "metadata": {"ph":{"isBase":false,"CODE":"PHT","isMetric":"yes","class":"cgs","names":["phot"],"printSymbols":["ph"],"properties":["illuminance"],"values":[{"printable":"1 × 10-4","numeric":0.0001}]}}};}, "cd", { type: "literal", value: "cd", description: "\"cd\"" }, function(u) {return {"value": 1, "units": {"cd": 1}, "metadata": {"cd":{"isBase":true,"CODE":"CD","dim":"F","names":["candela"],"printSymbols":["cd"],"properties":["luminous intensity"]}}};}, "Ao", { type: "literal", value: "Ao", description: "\"Ao\"" }, function(u) {return {"value": 1, "units": {"Ao": 1}, "metadata": {"Ao":{"isBase":false,"CODE":"AO","isMetric":"no","class":"misc","names":["Ångström"],"printSymbols":["Å"],"properties":["length"],"values":[{"printable":"0.1","numeric":0.1}]}}};}, "Wb", { type: "literal", value: "Wb", description: "\"Wb\"" }, function(u) {return {"value": 1, "units": {"Wb": 1}, "metadata": {"Wb":{"isBase":false,"CODE":"WB","isMetric":"yes","class":"si","names":["Weber"],"printSymbols":["Wb"],"properties":["magentic flux"],"values":[{"printable":"1","numeric":1}]}}};}, "Gb", { type: "literal", value: "Gb", description: "\"Gb\"" }, function(u) {return {"value": 1, "units": {"Gb": 1}, "metadata": {"Gb":{"isBase":false,"CODE":"GB","isMetric":"yes","class":"cgs","names":["Gilbert"],"printSymbols":["Gb"],"properties":["magnetic tension"],"values":[{"printable":"1","numeric":1}]}}};}, "Oe", { type: "literal", value: "Oe", description: "\"Oe\"" }, function(u) {return {"value": 1, "units": {"Oe": 1}, "metadata": {"Oe":{"isBase":false,"CODE":"OE","isMetric":"yes","class":"cgs","names":["Oersted"],"printSymbols":["Oe"],"properties":["magnetic field intensity"],"values":[{"printable":"250","numeric":250}]}}};}, "lx", { type: "literal", value: "lx", description: "\"lx\"" }, function(u) {return {"value": 1, "units": {"lx": 1}, "metadata": {"lx":{"isBase":false,"CODE":"LX","isMetric":"yes","class":"si","names":["lux"],"printSymbols":["lx"],"properties":["illuminance"],"values":[{"printable":"1","numeric":1}]}}};}, "Mx", { type: "literal", value: "Mx", description: "\"Mx\"" }, function(u) {return {"value": 1, "units": {"Mx": 1}, "metadata": {"Mx":{"isBase":false,"CODE":"MX","isMetric":"yes","class":"cgs","names":["Maxwell"],"printSymbols":["Mx"],"properties":["flux of magnetic induction"],"values":[{"printable":"1 × 10-8","numeric":1e-8}]}}};}, "St", { type: "literal", value: "St", description: "\"St\"" }, function(u) {return {"value": 1, "units": {"St": 1}, "metadata": {"St":{"isBase":false,"CODE":"ST","isMetric":"yes","class":"cgs","names":["Stokes"],"printSymbols":["St"],"properties":["kinematic viscosity"],"values":[{"printable":"1","numeric":1}]}}};}, "Bi", { type: "literal", value: "Bi", description: "\"Bi\"" }, function(u) {return {"value": 1, "units": {"Bi": 1}, "metadata": {"Bi":{"isBase":false,"CODE":"BI","isMetric":"yes","class":"cgs","names":["Biot"],"printSymbols":["Bi"],"properties":["electric current"],"values":[{"printable":"10","numeric":10}]}}};}, "Bq", { type: "literal", value: "Bq", description: "\"Bq\"" }, function(u) {return {"value": 1, "units": {"Bq": 1}, "metadata": {"Bq":{"isBase":false,"CODE":"BQ","isMetric":"yes","class":"si","names":["Becquerel"],"printSymbols":["Bq"],"properties":["radioactivity"],"values":[{"printable":"1","numeric":1}]}}};}, "Np", { type: "literal", value: "Np", description: "\"Np\"" }, function(u) {return {"value": 1, "units": {"Np": 1}, "metadata": {"Np":{"isBase":false,"CODE":"NEP","isMetric":"yes","isSpecial":"yes","class":"levels","names":["neper"],"printSymbols":["Np"],"properties":["level"],"values":[{"printable":"","numeric":null}]}}};}, "AU", { type: "literal", value: "AU", description: "\"AU\"" }, function(u) {return {"value": 1, "units": {"AU": 1}, "metadata": {"AU":{"isBase":false,"CODE":"ASU","isMetric":"no","class":"iso1000","names":["astronomic unit"],"printSymbols":["AU"],"properties":["length"],"values":[{"printable":"149597.870691","numeric":149597.870691}]}}};}, "mo", { type: "literal", value: "mo", description: "\"mo\"" }, function(u) {return {"value": 1, "units": {"mo": 1}, "metadata": {"mo":{"isBase":false,"CODE":"MO","isMetric":"no","class":"iso1000","names":["month"],"printSymbols":["mo"],"properties":["time"],"values":[{"printable":"1","numeric":1}]}}};}, "Ky", { type: "literal", value: "Ky", description: "\"Ky\"" }, function(u) {return {"value": 1, "units": {"Ky": 1}, "metadata": {"Ky":{"isBase":false,"CODE":"KY","isMetric":"yes","class":"cgs","names":["Kayser"],"printSymbols":["K"],"properties":["lineic number"],"values":[{"printable":"1","numeric":1}]}}};}, "gf", { type: "literal", value: "gf", description: "\"gf\"" }, function(u) {return {"value": 1, "units": {"gf": 1}, "metadata": {"gf":{"isBase":false,"CODE":"GF","isMetric":"yes","class":"const","names":["gram-force"],"printSymbols":["gf"],"properties":["force"],"values":[{"printable":"1","numeric":1}]}}};}, "wk", { type: "literal", value: "wk", description: "\"wk\"" }, function(u) {return {"value": 1, "units": {"wk": 1}, "metadata": {"wk":{"isBase":false,"CODE":"WK","isMetric":"no","class":"iso1000","names":["week"],"printSymbols":["wk"],"properties":["time"],"values":[{"printable":"7","numeric":7}]}}};}, "Pa", { type: "literal", value: "Pa", description: "\"Pa\"" }, function(u) {return {"value": 1, "units": {"Pa": 1}, "metadata": {"Pa":{"isBase":false,"CODE":"PAL","isMetric":"yes","class":"si","names":["Pascal"],"printSymbols":["Pa"],"properties":["pressure"],"values":[{"printable":"1","numeric":1}]}}};}, "g%", { type: "literal", value: "g%", description: "\"g%\"" }, function(u) {return {"value": 1, "units": {"g%": 1}, "metadata": {"g%":{"isBase":false,"CODE":"G%","isMetric":"yes","class":"chemical","names":["gram percent"],"printSymbols":["g%"],"properties":["mass concentration"],"values":[{"printable":"1","numeric":1}]}}};}, "sr", { type: "literal", value: "sr", description: "\"sr\"" }, function(u) {return {"value": 1, "units": {"sr": 1}, "metadata": {"sr":{"isBase":false,"CODE":"SR","isMetric":"yes","class":"si","names":["steradian"],"printSymbols":["sr"],"properties":["solid angle"],"values":[{"printable":"1","numeric":1}]}}};}, "Bd", { type: "literal", value: "Bd", description: "\"Bd\"" }, function(u) {return {"value": 1, "units": {"Bd": 1}, "metadata": {"Bd":{"isBase":false,"CODE":"BD","isMetric":"yes","class":"infotech","names":["baud"],"printSymbols":["Bd"],"properties":["signal transmission rate"],"values":[{"printable":"1","numeric":1}]}}};}, "eq", { type: "literal", value: "eq", description: "\"eq\"" }, function(u) {return {"value": 1, "units": {"eq": 1}, "metadata": {"eq":{"isBase":false,"CODE":"EQ","isMetric":"yes","class":"chemical","names":["equivalents"],"printSymbols":["eq"],"properties":["amount of substance"],"values":[{"printable":"1","numeric":1}]}}};}, "By", { type: "literal", value: "By", description: "\"By\"" }, function(u) {return {"value": 1, "units": {"By": 1}, "metadata": {"By":{"isBase":false,"CODE":"BY","isMetric":"yes","class":"infotech","names":["byte"],"printSymbols":["B"],"properties":["amount of information"],"values":[{"printable":"8","numeric":8}]}}};}, "Hz", { type: "literal", value: "Hz", description: "\"Hz\"" }, function(u) {return {"value": 1, "units": {"Hz": 1}, "metadata": {"Hz":{"isBase":false,"CODE":"HZ","isMetric":"yes","class":"si","names":["Hertz"],"printSymbols":["Hz"],"properties":["frequency"],"values":[{"printable":"1","numeric":1}]}}};}, "''", { type: "literal", value: "''", description: "\"''\"" }, function(u) {return {"value": 1, "units": {"''": 1}, "metadata": {"''":{"isBase":false,"CODE":"''","isMetric":"no","class":"iso1000","names":["second"],"printSymbols":["''"],"properties":["plane angle"],"values":[{"printable":"1","numeric":1}]}}};}, "pc", { type: "literal", value: "pc", description: "\"pc\"" }, function(u) {return {"value": 1, "units": {"pc": 1}, "metadata": {"pc":{"isBase":false,"CODE":"PRS","isMetric":"yes","class":"iso1000","names":["parsec"],"printSymbols":["pc"],"properties":["length"],"values":[{"printable":"3.085678 × 1016","numeric":30856780000000000}]}}};}, "eV", { type: "literal", value: "eV", description: "\"eV\"" }, function(u) {return {"value": 1, "units": {"eV": 1}, "metadata": {"eV":{"isBase":false,"CODE":"EV","isMetric":"yes","class":"iso1000","names":["electronvolt"],"printSymbols":["eV"],"properties":["energy"],"values":[{"printable":"1","numeric":1}]}}};}, "Gy", { type: "literal", value: "Gy", description: "\"Gy\"" }, function(u) {return {"value": 1, "units": {"Gy": 1}, "metadata": {"Gy":{"isBase":false,"CODE":"GY","isMetric":"yes","class":"si","names":["Gray"],"printSymbols":["Gy"],"properties":["energy dose"],"values":[{"printable":"1","numeric":1}]}}};}, "st", { type: "literal", value: "st", description: "\"st\"" }, function(u) {return {"value": 1, "units": {"st": 1}, "metadata": {"st":{"isBase":false,"CODE":"STR","isMetric":"yes","class":"misc","names":["stere"],"printSymbols":["st"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "Sv", { type: "literal", value: "Sv", description: "\"Sv\"" }, function(u) {return {"value": 1, "units": {"Sv": 1}, "metadata": {"Sv":{"isBase":false,"CODE":"SV","isMetric":"yes","class":"si","names":["Sievert"],"printSymbols":["Sv"],"properties":["dose equivalent"],"values":[{"printable":"1","numeric":1}]}}};}, "ar", { type: "literal", value: "ar", description: "\"ar\"" }, function(u) {return {"value": 1, "units": {"ar": 1}, "metadata": {"ar":{"isBase":false,"CODE":"AR","isMetric":"yes","class":"iso1000","names":["are"],"printSymbols":["a"],"properties":["area"],"values":[{"printable":"100","numeric":100}]}}};}, "sb", { type: "literal", value: "sb", description: "\"sb\"" }, function(u) {return {"value": 1, "units": {"sb": 1}, "metadata": {"sb":{"isBase":false,"CODE":"SB","isMetric":"yes","class":"cgs","names":["stilb"],"printSymbols":["sb"],"properties":["lum. intensity density"],"values":[{"printable":"1","numeric":1}]}}};}, "L", { type: "literal", value: "L", description: "\"L\"" }, function(u) {return {"value": 1, "units": {"L": 1}, "metadata": {"L":{"isBase":false,"isMetric":"yes","class":"iso1000","names":["liter"],"printSymbols":["L"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "t", { type: "literal", value: "t", description: "\"t\"" }, function(u) {return {"value": 1, "units": {"t": 1}, "metadata": {"t":{"isBase":false,"CODE":"TNE","isMetric":"yes","class":"iso1000","names":["tonne"],"printSymbols":["t"],"properties":["mass"],"values":[{"printable":"1 × 103","numeric":1000}]}}};}, "u", { type: "literal", value: "u", description: "\"u\"" }, function(u) {return {"value": 1, "units": {"u": 1}, "metadata": {"u":{"isBase":false,"CODE":"AMU","isMetric":"yes","class":"iso1000","names":["unified atomic mass unit"],"printSymbols":["u"],"properties":["mass"],"values":[{"printable":"1.6605402 × 10-24","numeric":1.6605402e-24}]}}};}, "P", { type: "literal", value: "P", description: "\"P\"" }, function(u) {return {"value": 1, "units": {"P": 1}, "metadata": {"P":{"isBase":false,"CODE":"P","isMetric":"yes","class":"cgs","names":["Poise"],"printSymbols":["P"],"properties":["dynamic viscosity"],"values":[{"printable":"1","numeric":1}]}}};}, "G", { type: "literal", value: "G", description: "\"G\"" }, function(u) {return {"value": 1, "units": {"G": 1}, "metadata": {"G":{"isBase":false,"CODE":"GS","isMetric":"yes","class":"cgs","names":["Gauss"],"printSymbols":["Gs"],"properties":["magnetic flux density"],"values":[{"printable":"1 × 10-4","numeric":0.0001}]}}};}, "R", { type: "literal", value: "R", description: "\"R\"" }, function(u) {return {"value": 1, "units": {"R": 1}, "metadata": {"R":{"isBase":false,"CODE":"ROE","isMetric":"yes","class":"cgs","names":["Roentgen"],"printSymbols":["R"],"properties":["ion dose"],"values":[{"printable":"2.58 × 10-4","numeric":0.000258}]}}};}, "H", { type: "literal", value: "H", description: "\"H\"" }, function(u) {return {"value": 1, "units": {"H": 1}, "metadata": {"H":{"isBase":false,"CODE":"H","isMetric":"yes","class":"si","names":["Henry"],"printSymbols":["H"],"properties":["inductance"],"values":[{"printable":"1","numeric":1}]}}};}, "T", { type: "literal", value: "T", description: "\"T\"" }, function(u) {return {"value": 1, "units": {"T": 1}, "metadata": {"T":{"isBase":false,"CODE":"T","isMetric":"yes","class":"si","names":["Tesla"],"printSymbols":["T"],"properties":["magnetic flux density"],"values":[{"printable":"1","numeric":1}]}}};}, "U", { type: "literal", value: "U", description: "\"U\"" }, function(u) {return {"value": 1, "units": {"U": 1}, "metadata": {"U":{"isBase":false,"CODE":"U","isMetric":"yes","class":"chemical","names":["Unit"],"printSymbols":["U"],"properties":["catalytic activity"],"values":[{"printable":"1","numeric":1}]}}};}, "B", { type: "literal", value: "B", description: "\"B\"" }, function(u) {return {"value": 1, "units": {"B": 1}, "metadata": {"B":{"isBase":false,"CODE":"B","isMetric":"yes","isSpecial":"yes","class":"levels","names":["bel"],"printSymbols":["B"],"properties":["level"],"values":[{"printable":"","numeric":null}]}}};}, "S", { type: "literal", value: "S", description: "\"S\"" }, function(u) {return {"value": 1, "units": {"S": 1}, "metadata": {"S":{"isBase":false,"CODE":"SIE","isMetric":"yes","class":"si","names":["Siemens"],"printSymbols":["S"],"properties":["electric conductance"],"values":[{"printable":"1","numeric":1}]}}};}, "m", { type: "literal", value: "m", description: "\"m\"" }, function(u) {return {"value": 1, "units": {"m": 1}, "metadata": {"m":{"isBase":true,"CODE":"M","dim":"L","names":["meter"],"printSymbols":["m"],"properties":["length"]}}};}, "s", { type: "literal", value: "s", description: "\"s\"" }, function(u) {return {"value": 1, "units": {"s": 1}, "metadata": {"s":{"isBase":true,"CODE":"S","dim":"T","names":["second"],"printSymbols":["s"],"properties":["time"]}}};}, "F", { type: "literal", value: "F", description: "\"F\"" }, function(u) {return {"value": 1, "units": {"F": 1}, "metadata": {"F":{"isBase":false,"CODE":"F","isMetric":"yes","class":"si","names":["Farad"],"printSymbols":["F"],"properties":["electric capacitance"],"values":[{"printable":"1","numeric":1}]}}};}, "l", { type: "literal", value: "l", description: "\"l\"" }, function(u) {return {"value": 1, "units": {"l": 1}, "metadata": {"l":{"isBase":false,"CODE":"L","isMetric":"yes","class":"iso1000","names":["liter"],"printSymbols":["l"],"properties":["volume"],"values":[{"printable":"1","numeric":1}]}}};}, "V", { type: "literal", value: "V", description: "\"V\"" }, function(u) {return {"value": 1, "units": {"V": 1}, "metadata": {"V":{"isBase":false,"CODE":"V","isMetric":"yes","class":"si","names":["Volt"],"printSymbols":["V"],"properties":["electric potential"],"values":[{"printable":"1","numeric":1}]}}};}, "A", { type: "literal", value: "A", description: "\"A\"" }, function(u) {return {"value": 1, "units": {"A": 1}, "metadata": {"A":{"isBase":false,"CODE":"A","isMetric":"yes","class":"si","names":["Ampère"],"printSymbols":["A"],"properties":["electric current"],"values":[{"printable":"1","numeric":1}]}}};}, "W", { type: "literal", value: "W", description: "\"W\"" }, function(u) {return {"value": 1, "units": {"W": 1}, "metadata": {"W":{"isBase":false,"CODE":"W","isMetric":"yes","class":"si","names":["Watt"],"printSymbols":["W"],"properties":["power"],"values":[{"printable":"1","numeric":1}]}}};}, "K", { type: "literal", value: "K", description: "\"K\"" }, function(u) {return {"value": 1, "units": {"K": 1}, "metadata": {"K":{"isBase":true,"CODE":"K","dim":"C","names":["Kelvin"],"printSymbols":["K"],"properties":["temperature"]}}};}, "C", { type: "literal", value: "C", description: "\"C\"" }, function(u) {return {"value": 1, "units": {"C": 1}, "metadata": {"C":{"isBase":true,"CODE":"C","dim":"Q","names":["Coulomb"],"printSymbols":["C"],"properties":["electric charge"]}}};}, "b", { type: "literal", value: "b", description: "\"b\"" }, function(u) {return {"value": 1, "units": {"b": 1}, "metadata": {"b":{"isBase":false,"CODE":"BRN","isMetric":"no","class":"misc","names":["barn"],"printSymbols":["b"],"properties":["action area"],"values":[{"printable":"100","numeric":100}]}}};}, "%", { type: "literal", value: "%", description: "\"%\"" }, function(u) {return {"value": 1, "units": {"%": 1}, "metadata": {"%":{"isBase":false,"CODE":"%","isMetric":"no","class":"dimless","names":["percent"],"printSymbols":["%"],"properties":["fraction"],"values":[{"printable":"1","numeric":1}]}}};}, "J", { type: "literal", value: "J", description: "\"J\"" }, function(u) {return {"value": 1, "units": {"J": 1}, "metadata": {"J":{"isBase":false,"CODE":"J","isMetric":"yes","class":"si","names":["Joule"],"printSymbols":["J"],"properties":["energy"],"values":[{"printable":"1","numeric":1}]}}};}, "'", { type: "literal", value: "'", description: "\"'\"" }, function(u) {return {"value": 1, "units": {"'": 1}, "metadata": {"'":{"isBase":false,"CODE":"'","isMetric":"no","class":"iso1000","names":["minute"],"printSymbols":["'"],"properties":["plane angle"],"values":[{"printable":"1","numeric":1}]}}};}, "h", { type: "literal", value: "h", description: "\"h\"" }, function(u) {return {"value": 1, "units": {"h": 1}, "metadata": {"h":{"isBase":false,"CODE":"HR","isMetric":"no","class":"iso1000","names":["hour"],"printSymbols":["h"],"properties":["time"],"values":[{"printable":"60","numeric":60}]}}};}, "d", { type: "literal", value: "d", description: "\"d\"" }, function(u) {return {"value": 1, "units": {"d": 1}, "metadata": {"d":{"isBase":false,"CODE":"D","isMetric":"no","class":"iso1000","names":["day"],"printSymbols":["d"],"properties":["time"],"values":[{"printable":"24","numeric":24}]}}};}, "N", { type: "literal", value: "N", description: "\"N\"" }, function(u) {return {"value": 1, "units": {"N": 1}, "metadata": {"N":{"isBase":false,"CODE":"N","isMetric":"yes","class":"si","names":["Newton"],"printSymbols":["N"],"properties":["force"],"values":[{"printable":"1","numeric":1}]}}};}, "a", { type: "literal", value: "a", description: "\"a\"" }, function(u) {return {"value": 1, "units": {"a": 1}, "metadata": {"a":{"isBase":false,"CODE":"ANN","isMetric":"no","class":"iso1000","names":["year"],"printSymbols":["a"],"properties":["time"],"values":[{"printable":"1","numeric":1}]}}};}, "g", { type: "literal", value: "g", description: "\"g\"" }, function(u) {return {"value": 1, "units": {"g": 1}, "metadata": {"g":{"isBase":true,"CODE":"G","dim":"M","names":["gram"],"printSymbols":["g"],"properties":["mass"]}}};}, "Y", { type: "literal", value: "Y", description: "\"Y\"" }, "Z", { type: "literal", value: "Z", description: "\"Z\"" }, "E", { type: "literal", value: "E", description: "\"E\"" }, "M", { type: "literal", value: "M", description: "\"M\"" }, "k", { type: "literal", value: "k", description: "\"k\"" }, "da", { type: "literal", value: "da", description: "\"da\"" }, "c", { type: "literal", value: "c", description: "\"c\"" }, "n", { type: "literal", value: "n", description: "\"n\"" }, "p", { type: "literal", value: "p", description: "\"p\"" }, "f", { type: "literal", value: "f", description: "\"f\"" }, "z", { type: "literal", value: "z", description: "\"z\"" }, "y", { type: "literal", value: "y", description: "\"y\"" }, "Ki", { type: "literal", value: "Ki", description: "\"Ki\"" }, "Mi", { type: "literal", value: "Mi", description: "\"Mi\"" }, "Gi", { type: "literal", value: "Gi", description: "\"Gi\"" }, "Ti", { type: "literal", value: "Ti", description: "\"Ti\"" } ], peg$bytecode = [ peg$decode("!7!+' 4!6 !! %"), peg$decode("!.\"\"\"2\"3#+2$7#+(%4\"6$\"! %$\"# !\"# !*# \"7#"), peg$decode("!.%\"\"2%3&+-$7$+#%'\"%$\"# !\"# !*> \"!.\"\"\"2\"3#+-$7$+#%'\"%$\"# !\"# !"), peg$decode("!7$+;$ '7\",#&7\"\"+)%4\"6(\"\"! %$\"# !\"# !"), peg$decode("!7%+c$7&*# \" )+S% '7),#&7)\"+A%56* \"\"!)##\" !\" ++)%4$6,$\"#\"%$$# !$## !$\"# !\"# !*E \"!7(+:$ '7),#&7)\"+(%4\"6-\"!!%$\"# !\"# !"), peg$decode("!7'+' 4!6.!! %*Y \"!./\"\"2/30+B$7#+8%.1\"\"2132+(%4#63#!!%$## !$\"# !\"# !*# \"7)"), peg$decode("!04\"\"1!35*# \" )+3$7(+)%4\"66\"\"! %$\"# !\"# !"), peg$decode("!7+*# \" )+K$7*+A%567 \"! )##\" !\" ++)%4#68#\"\"!%$## !$\"# !\"# !*# \"7*"), peg$decode("! '09\"\"1!3:+,$,)&09\"\"1!3:\"\"\" !+i$.;\"\"2;3<*# \" )+S%7&*# \" )+C%56= #\"! )##\" !\" ++*%4$6>$##\"!%$$# !$## !$\"# !\"# !"), peg$decode("!.?\"\"2?3@+t$ '0A\"\"1!3B+,$,)&0A\"\"1!3B\"\"\" !+O%.C\"\"2C3D+?%56E !!)##\" !\" ++(%4$6F$!\"%$$# !$## !$\"# !\"# !"), peg$decode("!.G\"\"2G3H+' 4!6I!! %*\u1CCD \"!.J\"\"2J3K+' 4!6L!! %*\u1CB5 \"!.M\"\"2M3N+' 4!6O!! %*\u1C9D \"!.P\"\"2P3Q+' 4!6R!! %*\u1C85 \"!.S\"\"2S3T+' 4!6U!! %*\u1C6D \"!.V\"\"2V3W+' 4!6X!! %*\u1C55 \"!.Y\"\"2Y3Z+' 4!6[!! %*\u1C3D \"!.\\\"\"2\\3]+' 4!6^!! %*\u1C25 \"!._\"\"2_3`+' 4!6a!! %*\u1C0D \"!.b\"\"2b3c+' 4!6d!! %*\u1BF5 \"!.e\"\"2e3f+' 4!6g!! %*\u1BDD \"!.h\"\"2h3i+' 4!6j!! %*\u1BC5 \"!.k\"\"2k3l+' 4!6m!! %*\u1BAD \"!.n\"\"2n3o+' 4!6p!! %*\u1B95 \"!.q\"\"2q3r+' 4!6s!! %*\u1B7D \"!.t\"\"2t3u+' 4!6v!! %*\u1B65 \"!.w\"\"2w3x+' 4!6y!! %*\u1B4D \"!.z\"\"2z3{+' 4!6|!! %*\u1B35 \"!.}\"\"2}3~+' 4!6!! %*\u1B1D \"!.\x80\"\"2\x803\x81+' 4!6\x82!! %*\u1B05 \"!.\x83\"\"2\x833\x84+' 4!6\x85!! %*\u1AED \"!.\x86\"\"2\x863\x87+' 4!6\x88!! %*\u1AD5 \"!.\x89\"\"2\x893\x8A+' 4!6\x8B!! %*\u1ABD \"!.\x8C\"\"2\x8C3\x8D+' 4!6\x8E!! %*\u1AA5 \"!.\x8F\"\"2\x8F3\x90+' 4!6\x91!! %*\u1A8D \"!.\x92\"\"2\x923\x93+' 4!6\x94!! %*\u1A75 \"!.\x95\"\"2\x953\x96+' 4!6\x97!! %*\u1A5D \"!.\x98\"\"2\x983\x99+' 4!6\x9A!! %*\u1A45 \"!.\x9B\"\"2\x9B3\x9C+' 4!6\x9D!! %*\u1A2D \"!.\x9E\"\"2\x9E3\x9F+' 4!6\xA0!! %*\u1A15 \"!.\xA1\"\"2\xA13\xA2+' 4!6\xA3!! %*\u19FD \"!.\xA4\"\"2\xA43\xA5+' 4!6\xA6!! %*\u19E5 \"!.\xA7\"\"2\xA73\xA8+' 4!6\xA9!! %*\u19CD \"!.\xAA\"\"2\xAA3\xAB+' 4!6\xAC!! %*\u19B5 \"!.\xAD\"\"2\xAD3\xAE+' 4!6\xAF!! %*\u199D \"!.\xB0\"\"2\xB03\xB1+' 4!6\xB2!! %*\u1985 \"!.\xB3\"\"2\xB33\xB4+' 4!6\xB5!! %*\u196D \"!.\xB6\"\"2\xB63\xB7+' 4!6\xB8!! %*\u1955 \"!.\xB9\"\"2\xB93\xBA+' 4!6\xBB!! %*\u193D \"!.\xBC\"\"2\xBC3\xBD+' 4!6\xBE!! %*\u1925 \"!.\xBF\"\"2\xBF3\xC0+' 4!6\xC1!! %*\u190D \"!.\xC2\"\"2\xC23\xC3+' 4!6\xC4!! %*\u18F5 \"!.\xC5\"\"2\xC53\xC6+' 4!6\xC7!! %*\u18DD \"!.\xC8\"\"2\xC83\xC9+' 4!6\xCA!! %*\u18C5 \"!.\xCB\"\"2\xCB3\xCC+' 4!6\xCD!! %*\u18AD \"!.\xCE\"\"2\xCE3\xCF+' 4!6\xD0!! %*\u1895 \"!.\xD1\"\"2\xD13\xD2+' 4!6\xD3!! %*\u187D \"!.\xD4\"\"2\xD43\xD5+' 4!6\xD6!! %*\u1865 \"!.\xD7\"\"2\xD73\xD8+' 4!6\xD9!! %*\u184D \"!.\xDA\"\"2\xDA3\xDB+' 4!6\xDC!! %*\u1835 \"!.\xDD\"\"2\xDD3\xDE+' 4!6\xDF!! %*\u181D \"!.\xE0\"\"2\xE03\xE1+' 4!6\xE2!! %*\u1805 \"!.\xE3\"\"2\xE33\xE4+' 4!6\xE5!! %*\u17ED \"!.\xE6\"\"2\xE63\xE7+' 4!6\xE8!! %*\u17D5 \"!.\xE9\"\"2\xE93\xEA+' 4!6\xEB!! %*\u17BD \"!.\xEC\"\"2\xEC3\xED+' 4!6\xEE!! %*\u17A5 \"!.\xEF\"\"2\xEF3\xF0+' 4!6\xF1!! %*\u178D \"!.\xF2\"\"2\xF23\xF3+' 4!6\xF4!! %*\u1775 \"!.\xF5\"\"2\xF53\xF6+' 4!6\xF7!! %*\u175D \"!.\xF8\"\"2\xF83\xF9+' 4!6\xFA!! %*\u1745 \"!.\xFB\"\"2\xFB3\xFC+' 4!6\xFD!! %*\u172D \"!.\xFE\"\"2\xFE3\xFF+' 4!6\u0100!! %*\u1715 \"!.\u0101\"\"2\u01013\u0102+' 4!6\u0103!! %*\u16FD \"!.\u0104\"\"2\u01043\u0105+' 4!6\u0106!! %*\u16E5 \"!.\u0107\"\"2\u01073\u0108+' 4!6\u0109!! %*\u16CD \"!.\u010A\"\"2\u010A3\u010B+' 4!6\u010C!! %*\u16B5 \"!.\u010D\"\"2\u010D3\u010E+' 4!6\u010F!! %*\u169D \"!.\u0110\"\"2\u01103\u0111+' 4!6\u0112!! %*\u1685 \"!.\u0113\"\"2\u01133\u0114+' 4!6\u0115!! %*\u166D \"!.\u0116\"\"2\u01163\u0117+' 4!6\u0118!! %*\u1655 \"!.\u0119\"\"2\u01193\u011A+' 4!6\u011B!! %*\u163D \"!.\u011C\"\"2\u011C3\u011D+' 4!6\u011E!! %*\u1625 \"!.\u011F\"\"2\u011F3\u0120+' 4!6\u0121!! %*\u160D \"!.\u0122\"\"2\u01223\u0123+' 4!6\u0124!! %*\u15F5 \"!.\u0125\"\"2\u01253\u0126+' 4!6\u0127!! %*\u15DD \"!.\u0128\"\"2\u01283\u0129+' 4!6\u012A!! %*\u15C5 \"!.\u012B\"\"2\u012B3\u012C+' 4!6\u012D!! %*\u15AD \"!.\u012E\"\"2\u012E3\u012F+' 4!6\u0130!! %*\u1595 \"!.\u0131\"\"2\u01313\u0132+' 4!6\u0133!! %*\u157D \"!.\u0134\"\"2\u01343\u0135+' 4!6\u0136!! %*\u1565 \"!.\u0137\"\"2\u01373\u0138+' 4!6\u0139!! %*\u154D \"!.\u013A\"\"2\u013A3\u013B+' 4!6\u013C!! %*\u1535 \"!.\u013D\"\"2\u013D3\u013E+' 4!6\u013F!! %*\u151D \"!.\u0140\"\"2\u01403\u0141+' 4!6\u0142!! %*\u1505 \"!.\u0143\"\"2\u01433\u0144+' 4!6\u0145!! %*\u14ED \"!.\u0146\"\"2\u01463\u0147+' 4!6\u0148!! %*\u14D5 \"!.\u0149\"\"2\u01493\u014A+' 4!6\u014B!! %*\u14BD \"!.\u014C\"\"2\u014C3\u014D+' 4!6\u014E!! %*\u14A5 \"!.\u014F\"\"2\u014F3\u0150+' 4!6\u0151!! %*\u148D \"!.\u0152\"\"2\u01523\u0153+' 4!6\u0154!! %*\u1475 \"!.\u0155\"\"2\u01553\u0156+' 4!6\u0157!! %*\u145D \"!.\u0158\"\"2\u01583\u0159+' 4!6\u015A!! %*\u1445 \"!.\u015B\"\"2\u015B3\u015C+' 4!6\u015D!! %*\u142D \"!.\u015E\"\"2\u015E3\u015F+' 4!6\u0160!! %*\u1415 \"!.\u0161\"\"2\u01613\u0162+' 4!6\u0163!! %*\u13FD \"!.\u0164\"\"2\u01643\u0165+' 4!6\u0166!! %*\u13E5 \"!.\u0167\"\"2\u01673\u0168+' 4!6\u0169!! %*\u13CD \"!.\u016A\"\"2\u016A3\u016B+' 4!6\u016C!! %*\u13B5 \"!.\u016D\"\"2\u016D3\u016E+' 4!6\u016F!! %*\u139D \"!.\u0170\"\"2\u01703\u0171+' 4!6\u0172!! %*\u1385 \"!.\u0173\"\"2\u01733\u0174+' 4!6\u0175!! %*\u136D \"!.\u0176\"\"2\u01763\u0177+' 4!6\u0178!! %*\u1355 \"!.\u0179\"\"2\u01793\u017A+' 4!6\u017B!! %*\u133D \"!.\u017C\"\"2\u017C3\u017D+' 4!6\u017E!! %*\u1325 \"!.\u017F\"\"2\u017F3\u0180+' 4!6\u0181!! %*\u130D \"!.\u0182\"\"2\u01823\u0183+' 4!6\u0184!! %*\u12F5 \"!.\u0185\"\"2\u01853\u0186+' 4!6\u0187!! %*\u12DD \"!.\u0188\"\"2\u01883\u0189+' 4!6\u018A!! %*\u12C5 \"!.\u018B\"\"2\u018B3\u018C+' 4!6\u018D!! %*\u12AD \"!.\u018E\"\"2\u018E3\u018F+' 4!6\u0190!! %*\u1295 \"!.\u0191\"\"2\u01913\u0192+' 4!6\u0193!! %*\u127D \"!.\u0194\"\"2\u01943\u0195+' 4!6\u0196!! %*\u1265 \"!.\u0197\"\"2\u01973\u0198+' 4!6\u0199!! %*\u124D \"!.\u019A\"\"2\u019A3\u019B+' 4!6\u019C!! %*\u1235 \"!.\u019D\"\"2\u019D3\u019E+' 4!6\u019F!! %*\u121D \"!.\u01A0\"\"2\u01A03\u01A1+' 4!6\u01A2!! %*\u1205 \"!.\u01A3\"\"2\u01A33\u01A4+' 4!6\u01A5!! %*\u11ED \"!.\u01A6\"\"2\u01A63\u01A7+' 4!6\u01A8!! %*\u11D5 \"!.\u01A9\"\"2\u01A93\u01AA+' 4!6\u01AB!! %*\u11BD \"!.\u01AC\"\"2\u01AC3\u01AD+' 4!6\u01AE!! %*\u11A5 \"!.\u01AF\"\"2\u01AF3\u01B0+' 4!6\u01B1!! %*\u118D \"!.\u01B2\"\"2\u01B23\u01B3+' 4!6\u01B4!! %*\u1175 \"!.\u01B5\"\"2\u01B53\u01B6+' 4!6\u01B7!! %*\u115D \"!.\u01B8\"\"2\u01B83\u01B9+' 4!6\u01BA!! %*\u1145 \"!.\u01BB\"\"2\u01BB3\u01BC+' 4!6\u01BD!! %*\u112D \"!.\u01BE\"\"2\u01BE3\u01BF+' 4!6\u01C0!! %*\u1115 \"!.\u01C1\"\"2\u01C13\u01C2+' 4!6\u01C3!! %*\u10FD \"!.\u01C4\"\"2\u01C43\u01C5+' 4!6\u01C6!! %*\u10E5 \"!.\u01C7\"\"2\u01C73\u01C8+' 4!6\u01C9!! %*\u10CD \"!.\u01CA\"\"2\u01CA3\u01CB+' 4!6\u01CC!! %*\u10B5 \"!.\u01CD\"\"2\u01CD3\u01CE+' 4!6\u01CF!! %*\u109D \"!.\u01D0\"\"2\u01D03\u01D1+' 4!6\u01D2!! %*\u1085 \"!.\u01D3\"\"2\u01D33\u01D4+' 4!6\u01D5!! %*\u106D \"!.\u01D6\"\"2\u01D63\u01D7+' 4!6\u01D8!! %*\u1055 \"!.\u01D9\"\"2\u01D93\u01DA+' 4!6\u01DB!! %*\u103D \"!.\u01DC\"\"2\u01DC3\u01DD+' 4!6\u01DE!! %*\u1025 \"!.\u01DF\"\"2\u01DF3\u01E0+' 4!6\u01E1!! %*\u100D \"!.\u01E2\"\"2\u01E23\u01E3+' 4!6\u01E4!! %*\u0FF5 \"!.\u01E5\"\"2\u01E53\u01E6+' 4!6\u01E7!! %*\u0FDD \"!.\u01E8\"\"2\u01E83\u01E9+' 4!6\u01EA!! %*\u0FC5 \"!.\u01EB\"\"2\u01EB3\u01EC+' 4!6\u01ED!! %*\u0FAD \"!.\u01EE\"\"2\u01EE3\u01EF+' 4!6\u01F0!! %*\u0F95 \"!.\u01F1\"\"2\u01F13\u01F2+' 4!6\u01F3!! %*\u0F7D \"!.\u01F4\"\"2\u01F43\u01F5+' 4!6\u01F6!! %*\u0F65 \"!.\u01F7\"\"2\u01F73\u01F8+' 4!6\u01F9!! %*\u0F4D \"!.\u01FA\"\"2\u01FA3\u01FB+' 4!6\u01FC!! %*\u0F35 \"!.\u01FD\"\"2\u01FD3\u01FE+' 4!6\u01FF!! %*\u0F1D \"!.\u0200\"\"2\u02003\u0201+' 4!6\u0202!! %*\u0F05 \"!.\u0203\"\"2\u02033\u0204+' 4!6\u0205!! %*\u0EED \"!.\u0206\"\"2\u02063\u0207+' 4!6\u0208!! %*\u0ED5 \"!.\u0209\"\"2\u02093\u020A+' 4!6\u020B!! %*\u0EBD \"!.\u020C\"\"2\u020C3\u020D+' 4!6\u020E!! %*\u0EA5 \"!.\u020F\"\"2\u020F3\u0210+' 4!6\u0211!! %*\u0E8D \"!.\u0212\"\"2\u02123\u0213+' 4!6\u0214!! %*\u0E75 \"!.\u0215\"\"2\u02153\u0216+' 4!6\u0217!! %*\u0E5D \"!.\u0218\"\"2\u02183\u0219+' 4!6\u021A!! %*\u0E45 \"!.\u021B\"\"2\u021B3\u021C+' 4!6\u021D!! %*\u0E2D \"!.\u021E\"\"2\u021E3\u021F+' 4!6\u0220!! %*\u0E15 \"!.\u0221\"\"2\u02213\u0222+' 4!6\u0223!! %*\u0DFD \"!.\u0224\"\"2\u02243\u0225+' 4!6\u0226!! %*\u0DE5 \"!.\u0227\"\"2\u02273\u0228+' 4!6\u0229!! %*\u0DCD \"!.\u022A\"\"2\u022A3\u022B+' 4!6\u022C!! %*\u0DB5 \"!.\u022D\"\"2\u022D3\u022E+' 4!6\u022F!! %*\u0D9D \"!.\u0230\"\"2\u02303\u0231+' 4!6\u0232!! %*\u0D85 \"!.\u0233\"\"2\u02333\u0234+' 4!6\u0235!! %*\u0D6D \"!.\u0236\"\"2\u02363\u0237+' 4!6\u0238!! %*\u0D55 \"!.\u0239\"\"2\u02393\u023A+' 4!6\u023B!! %*\u0D3D \"!.\u023C\"\"2\u023C3\u023D+' 4!6\u023E!! %*\u0D25 \"!.\u023F\"\"2\u023F3\u0240+' 4!6\u0241!! %*\u0D0D \"!.\u0242\"\"2\u02423\u0243+' 4!6\u0244!! %*\u0CF5 \"!.\u0245\"\"2\u02453\u0246+' 4!6\u0247!! %*\u0CDD \"!.\u0248\"\"2\u02483\u0249+' 4!6\u024A!! %*\u0CC5 \"!.\u024B\"\"2\u024B3\u024C+' 4!6\u024D!! %*\u0CAD \"!.\u024E\"\"2\u024E3\u024F+' 4!6\u0250!! %*\u0C95 \"!.\u0251\"\"2\u02513\u0252+' 4!6\u0253!! %*\u0C7D \"!.\u0254\"\"2\u02543\u0255+' 4!6\u0256!! %*\u0C65 \"!.\u0257\"\"2\u02573\u0258+' 4!6\u0259!! %*\u0C4D \"!.\u025A\"\"2\u025A3\u025B+' 4!6\u025C!! %*\u0C35 \"!.\u025D\"\"2\u025D3\u025E+' 4!6\u025F!! %*\u0C1D \"!.\u0260\"\"2\u02603\u0261+' 4!6\u0262!! %*\u0C05 \"!.\u0263\"\"2\u02633\u0264+' 4!6\u0265!! %*\u0BED \"!.\u0266\"\"2\u02663\u0267+' 4!6\u0268!! %*\u0BD5 \"!.\u0269\"\"2\u02693\u026A+' 4!6\u026B!! %*\u0BBD \"!.\u026C\"\"2\u026C3\u026D+' 4!6\u026E!! %*\u0BA5 \"!.\u026F\"\"2\u026F3\u0270+' 4!6\u0271!! %*\u0B8D \"!.\u0272\"\"2\u02723\u0273+' 4!6\u0274!! %*\u0B75 \"!.\u0275\"\"2\u02753\u0276+' 4!6\u0277!! %*\u0B5D \"!.\u0278\"\"2\u02783\u0279+' 4!6\u027A!! %*\u0B45 \"!.\u027B\"\"2\u027B3\u027C+' 4!6\u027D!! %*\u0B2D \"!.\u027E\"\"2\u027E3\u027F+' 4!6\u0280!! %*\u0B15 \"!.\u0281\"\"2\u02813\u0282+' 4!6\u0283!! %*\u0AFD \"!.\u0284\"\"2\u02843\u0285+' 4!6\u0286!! %*\u0AE5 \"!.\u0287\"\"2\u02873\u0288+' 4!6\u0289!! %*\u0ACD \"!.\u028A\"\"2\u028A3\u028B+' 4!6\u028C!! %*\u0AB5 \"!.\u028D\"\"2\u028D3\u028E+' 4!6\u028F!! %*\u0A9D \"!.\u0290\"\"2\u02903\u0291+' 4!6\u0292!! %*\u0A85 \"!.\u0293\"\"2\u02933\u0294+' 4!6\u0295!! %*\u0A6D \"!.\u0296\"\"2\u02963\u0297+' 4!6\u0298!! %*\u0A55 \"!.\u0299\"\"2\u02993\u029A+' 4!6\u029B!! %*\u0A3D \"!.\u029C\"\"2\u029C3\u029D+' 4!6\u029E!! %*\u0A25 \"!.\u029F\"\"2\u029F3\u02A0+' 4!6\u02A1!! %*\u0A0D \"!.\u02A2\"\"2\u02A23\u02A3+' 4!6\u02A4!! %*\u09F5 \"!.\u02A5\"\"2\u02A53\u02A6+' 4!6\u02A7!! %*\u09DD \"!.\u02A8\"\"2\u02A83\u02A9+' 4!6\u02AA!! %*\u09C5 \"!.\u02AB\"\"2\u02AB3\u02AC+' 4!6\u02AD!! %*\u09AD \"!.\u02AE\"\"2\u02AE3\u02AF+' 4!6\u02B0!! %*\u0995 \"!.\u02B1\"\"2\u02B13\u02B2+' 4!6\u02B3!! %*\u097D \"!.\u02B4\"\"2\u02B43\u02B5+' 4!6\u02B6!! %*\u0965 \"!.\u02B7\"\"2\u02B73\u02B8+' 4!6\u02B9!! %*\u094D \"!.\u02BA\"\"2\u02BA3\u02BB+' 4!6\u02BC!! %*\u0935 \"!.\u02BD\"\"2\u02BD3\u02BE+' 4!6\u02BF!! %*\u091D \"!.\u02C0\"\"2\u02C03\u02C1+' 4!6\u02C2!! %*\u0905 \"!.\u02C3\"\"2\u02C33\u02C4+' 4!6\u02C5!! %*\u08ED \"!.\u02C6\"\"2\u02C63\u02C7+' 4!6\u02C8!! %*\u08D5 \"!.\u02C9\"\"2\u02C93\u02CA+' 4!6\u02CB!! %*\u08BD \"!.\u02CC\"\"2\u02CC3\u02CD+' 4!6\u02CE!! %*\u08A5 \"!.\u02CF\"\"2\u02CF3\u02D0+' 4!6\u02D1!! %*\u088D \"!.\u02D2\"\"2\u02D23\u02D3+' 4!6\u02D4!! %*\u0875 \"!.\u02D5\"\"2\u02D53\u02D6+' 4!6\u02D7!! %*\u085D \"!.\u02D8\"\"2\u02D83\u02D9+' 4!6\u02DA!! %*\u0845 \"!.\u02DB\"\"2\u02DB3\u02DC+' 4!6\u02DD!! %*\u082D \"!.\u02DE\"\"2\u02DE3\u02DF+' 4!6\u02E0!! %*\u0815 \"!.\u02E1\"\"2\u02E13\u02E2+' 4!6\u02E3!! %*\u07FD \"!.\u02E4\"\"2\u02E43\u02E5+' 4!6\u02E6!! %*\u07E5 \"!.\u02E7\"\"2\u02E73\u02E8+' 4!6\u02E9!! %*\u07CD \"!.\u02EA\"\"2\u02EA3\u02EB+' 4!6\u02EC!! %*\u07B5 \"!.\u02ED\"\"2\u02ED3\u02EE+' 4!6\u02EF!! %*\u079D \"!.\u02F0\"\"2\u02F03\u02F1+' 4!6\u02F2!! %*\u0785 \"!.\u02F3\"\"2\u02F33\u02F4+' 4!6\u02F5!! %*\u076D \"!.\u02F6\"\"2\u02F63\u02F7+' 4!6\u02F8!! %*\u0755 \"!.\u02F9\"\"2\u02F93\u02FA+' 4!6\u02FB!! %*\u073D \"!.\u02FC\"\"2\u02FC3\u02FD+' 4!6\u02FE!! %*\u0725 \"!.\u02FF\"\"2\u02FF3\u0300+' 4!6\u0301!! %*\u070D \"!.\u0302\"\"2\u03023\u0303+' 4!6\u0304!! %*\u06F5 \"!.\u0305\"\"2\u03053\u0306+' 4!6\u0307!! %*\u06DD \"!.\u0308\"\"2\u03083\u0309+' 4!6\u030A!! %*\u06C5 \"!.\u030B\"\"2\u030B3\u030C+' 4!6\u030D!! %*\u06AD \"!.\u030E\"\"2\u030E3\u030F+' 4!6\u0310!! %*\u0695 \"!.\u0311\"\"2\u03113\u0312+' 4!6\u0313!! %*\u067D \"!.\u0314\"\"2\u03143\u0315+' 4!6\u0316!! %*\u0665 \"!.\u0317\"\"2\u03173\u0318+' 4!6\u0319!! %*\u064D \"!.\u031A\"\"2\u031A3\u031B+' 4!6\u031C!! %*\u0635 \"!.\u031D\"\"2\u031D3\u031E+' 4!6\u031F!! %*\u061D \"!.\u0320\"\"2\u03203\u0321+' 4!6\u0322!! %*\u0605 \"!.\u0323\"\"2\u03233\u0324+' 4!6\u0325!! %*\u05ED \"!.\u0326\"\"2\u03263\u0327+' 4!6\u0328!! %*\u05D5 \"!.\u0329\"\"2\u03293\u032A+' 4!6\u032B!! %*\u05BD \"!.\u032C\"\"2\u032C3\u032D+' 4!6\u032E!! %*\u05A5 \"!.\u032F\"\"2\u032F3\u0330+' 4!6\u0331!! %*\u058D \"!.\u0332\"\"2\u03323\u0333+' 4!6\u0334!! %*\u0575 \"!.\u0335\"\"2\u03353\u0336+' 4!6\u0337!! %*\u055D \"!.\u0338\"\"2\u03383\u0339+' 4!6\u033A!! %*\u0545 \"!.\u033B\"\"2\u033B3\u033C+' 4!6\u033D!! %*\u052D \"!.\u033E\"\"2\u033E3\u033F+' 4!6\u0340!! %*\u0515 \"!.\u0341\"\"2\u03413\u0342+' 4!6\u0343!! %*\u04FD \"!.\u0344\"\"2\u03443\u0345+' 4!6\u0346!! %*\u04E5 \"!.\u0347\"\"2\u03473\u0348+' 4!6\u0349!! %*\u04CD \"!.\u034A\"\"2\u034A3\u034B+' 4!6\u034C!! %*\u04B5 \"!.\u034D\"\"2\u034D3\u034E+' 4!6\u034F!! %*\u049D \"!.\u0350\"\"2\u03503\u0351+' 4!6\u0352!! %*\u0485 \"!.\u0353\"\"2\u03533\u0354+' 4!6\u0355!! %*\u046D \"!.\u0356\"\"2\u03563\u0357+' 4!6\u0358!! %*\u0455 \"!.\u0359\"\"2\u03593\u035A+' 4!6\u035B!! %*\u043D \"!.\u035C\"\"2\u035C3\u035D+' 4!6\u035E!! %*\u0425 \"!.\u035F\"\"2\u035F3\u0360+' 4!6\u0361!! %*\u040D \"!.\u0362\"\"2\u03623\u0363+' 4!6\u0364!! %*\u03F5 \"!.\u0365\"\"2\u03653\u0366+' 4!6\u0367!! %*\u03DD \"!.\u0368\"\"2\u03683\u0369+' 4!6\u036A!! %*\u03C5 \"!.\u036B\"\"2\u036B3\u036C+' 4!6\u036D!! %*\u03AD \"!.\u036E\"\"2\u036E3\u036F+' 4!6\u0370!! %*\u0395 \"!.\u0371\"\"2\u03713\u0372+' 4!6\u0373!! %*\u037D \"!.\u0374\"\"2\u03743\u0375+' 4!6\u0376!! %*\u0365 \"!.\u0377\"\"2\u03773\u0378+' 4!6\u0379!! %*\u034D \"!.\u037A\"\"2\u037A3\u037B+' 4!6\u037C!! %*\u0335 \"!.\u037D\"\"2\u037D3\u037E+' 4!6\u037F!! %*\u031D \"!.\u0380\"\"2\u03803\u0381+' 4!6\u0382!! %*\u0305 \"!.\u0383\"\"2\u03833\u0384+' 4!6\u0385!! %*\u02ED \"!.\u0386\"\"2\u03863\u0387+' 4!6\u0388!! %*\u02D5 \"!.\u0389\"\"2\u03893\u038A+' 4!6\u038B!! %*\u02BD \"!.\u038C\"\"2\u038C3\u038D+' 4!6\u038E!! %*\u02A5 \"!.\u038F\"\"2\u038F3\u0390+' 4!6\u0391!! %*\u028D \"!.\u0392\"\"2\u03923\u0393+' 4!6\u0394!! %*\u0275 \"!.\u0395\"\"2\u03953\u0396+' 4!6\u0397!! %*\u025D \"!.\u0398\"\"2\u03983\u0399+' 4!6\u039A!! %*\u0245 \"!.\u039B\"\"2\u039B3\u039C+' 4!6\u039D!! %*\u022D \"!.\u039E\"\"2\u039E3\u039F+' 4!6\u03A0!! %*\u0215 \"!.\u03A1\"\"2\u03A13\u03A2+' 4!6\u03A3!! %*\u01FD \"!.\u03A4\"\"2\u03A43\u03A5+' 4!6\u03A6!! %*\u01E5 \"!.\u03A7\"\"2\u03A73\u03A8+' 4!6\u03A9!! %*\u01CD \"!.\u03AA\"\"2\u03AA3\u03AB+' 4!6\u03AC!! %*\u01B5 \"!.\u03AD\"\"2\u03AD3\u03AE+' 4!6\u03AF!! %*\u019D \"!.\u03B0\"\"2\u03B03\u03B1+' 4!6\u03B2!! %*\u0185 \"!.\u03B3\"\"2\u03B33\u03B4+' 4!6\u03B5!! %*\u016D \"!.\u03B6\"\"2\u03B63\u03B7+' 4!6\u03B8!! %*\u0155 \"!.\u03B9\"\"2\u03B93\u03BA+' 4!6\u03BB!! %*\u013D \"!.\u03BC\"\"2\u03BC3\u03BD+' 4!6\u03BE!! %*\u0125 \"!.\u03BF\"\"2\u03BF3\u03C0+' 4!6\u03C1!! %*\u010D \"!.\u03C2\"\"2\u03C23\u03C3+' 4!6\u03C4!! %*\xF5 \"!.\u03C5\"\"2\u03C53\u03C6+' 4!6\u03C7!! %*\xDD \"!.\u03C8\"\"2\u03C83\u03C9+' 4!6\u03CA!! %*\xC5 \"!.\u03CB\"\"2\u03CB3\u03CC+' 4!6\u03CD!! %*\xAD \"!.\u03CE\"\"2\u03CE3\u03CF+' 4!6\u03D0!! %*\x95 \"!.\u03D1\"\"2\u03D13\u03D2+' 4!6\u03D3!! %*} \"!.\u03D4\"\"2\u03D43\u03D5+' 4!6\u03D6!! %*e \"!.\u03D7\"\"2\u03D73\u03D8+' 4!6\u03D9!! %*M \"!.\u03DA\"\"2\u03DA3\u03DB+' 4!6\u03DC!! %*5 \"!.\u03DD\"\"2\u03DD3\u03DE+' 4!6\u03DF!! %"), peg$decode(".\u03E0\"\"2\u03E03\u03E1*\u0131 \".\u03E2\"\"2\u03E23\u03E3*\u0125 \".\u03E4\"\"2\u03E43\u03E5*\u0119 \".\u0392\"\"2\u03923\u0393*\u010D \".\u039E\"\"2\u039E3\u039F*\u0101 \".\u0395\"\"2\u03953\u0396*\xF5 \".\u03E6\"\"2\u03E63\u03E7*\xE9 \".\u03E8\"\"2\u03E83\u03E9*\xDD \".\u03D1\"\"2\u03D13\u03D2*\xD1 \".\u03EA\"\"2\u03EA3\u03EB*\xC5 \".\u03D4\"\"2\u03D43\u03D5*\xB9 \".\u03EC\"\"2\u03EC3\u03ED*\xAD \".\u03AA\"\"2\u03AA3\u03AB*\xA1 \".\u038F\"\"2\u038F3\u0390*\x95 \".\u03EE\"\"2\u03EE3\u03EF*\x89 \".\u03F0\"\"2\u03F03\u03F1*} \".\u03F2\"\"2\u03F23\u03F3*q \".\u03DA\"\"2\u03DA3\u03DB*e \".\u03F4\"\"2\u03F43\u03F5*Y \".\u03F6\"\"2\u03F63\u03F7*M \".\u03F8\"\"2\u03F83\u03F9*A \".\u03FA\"\"2\u03FA3\u03FB*5 \".\u03FC\"\"2\u03FC3\u03FD*) \".\u03FE\"\"2\u03FE3\u03FF") ], peg$currPos = 0, peg$reportedPos = 0, peg$cachedPos = 0, peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleIndices)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleIndex = peg$startRuleIndices[options.startRule]; } function text() { return input.substring(peg$reportedPos, peg$currPos); } function offset() { return peg$reportedPos; } function line() { return peg$computePosDetails(peg$reportedPos).line; } function column() { return peg$computePosDetails(peg$reportedPos).column; } function expected(description) { throw peg$buildException( null, [{ type: "other", description: description }], peg$reportedPos ); } function error(message) { throw peg$buildException(message, null, peg$reportedPos); } function peg$computePosDetails(pos) { function advance(details, startPos, endPos) { var p, ch; for (p = startPos; p < endPos; p++) { ch = input.charAt(p); if (ch === "\n") { if (!details.seenCR) { details.line++; } details.column = 1; details.seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { details.line++; details.column = 1; details.seenCR = true; } else { details.column++; details.seenCR = false; } } } if (peg$cachedPos !== pos) { if (peg$cachedPos > pos) { peg$cachedPos = 0; peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; } advance(peg$cachedPosDetails, peg$cachedPos, pos); peg$cachedPos = pos; } return peg$cachedPosDetails; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildException(message, expected, pos) { function cleanupExpected(expected) { var i = 1; expected.sort(function(a, b) { if (a.description < b.description) { return -1; } else if (a.description > b.description) { return 1; } else { return 0; } }); while (i < expected.length) { if (expected[i - 1] === expected[i]) { expected.splice(i, 1); } else { i++; } } } function buildMessage(expected, found) { function stringEscape(s) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\x08/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); } var expectedDescs = new Array(expected.length), expectedDesc, foundDesc, i; for (i = 0; i < expected.length; i++) { expectedDescs[i] = expected[i].description; } expectedDesc = expected.length > 1 ? expectedDescs.slice(0, -1).join(", ") + " or " + expectedDescs[expected.length - 1] : expectedDescs[0]; foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; return "Expected " + expectedDesc + " but " + foundDesc + " found."; } var posDetails = peg$computePosDetails(pos), found = pos < input.length ? input.charAt(pos) : null; if (expected !== null) { cleanupExpected(expected); } return new SyntaxError( message !== null ? message : buildMessage(expected, found), expected, found, pos, posDetails.line, posDetails.column ); } function peg$decode(s) { var bc = new Array(s.length), i; for (i = 0; i < s.length; i++) { bc[i] = s.charCodeAt(i) - 32; } return bc; } function peg$parseRule(index) { var bc = peg$bytecode[index], ip = 0, ips = [], end = bc.length, ends = [], stack = [], params, i; function protect(object) { return Object.prototype.toString.apply(object) === "[object Array]" ? [] : object; } while (true) { while (ip < end) { switch (bc[ip]) { case 0: stack.push(protect(peg$consts[bc[ip + 1]])); ip += 2; break; case 1: stack.push(peg$currPos); ip++; break; case 2: stack.pop(); ip++; break; case 3: peg$currPos = stack.pop(); ip++; break; case 4: stack.length -= bc[ip + 1]; ip += 2; break; case 5: stack.splice(-2, 1); ip++; break; case 6: stack[stack.length - 2].push(stack.pop()); ip++; break; case 7: stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); ip += 2; break; case 8: stack.pop(); stack.push(input.substring(stack[stack.length - 1], peg$currPos)); ip++; break; case 9: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1]) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 10: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1] === peg$FAILED) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 11: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1] !== peg$FAILED) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 12: if (stack[stack.length - 1] !== peg$FAILED) { ends.push(end); ips.push(ip); end = ip + 2 + bc[ip + 1]; ip += 2; } else { ip += 2 + bc[ip + 1]; } break; case 13: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (input.length > peg$currPos) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 14: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 15: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 16: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 17: stack.push(input.substr(peg$currPos, bc[ip + 1])); peg$currPos += bc[ip + 1]; ip += 2; break; case 18: stack.push(peg$consts[bc[ip + 1]]); peg$currPos += peg$consts[bc[ip + 1]].length; ip += 2; break; case 19: stack.push(peg$FAILED); if (peg$silentFails === 0) { peg$fail(peg$consts[bc[ip + 1]]); } ip += 2; break; case 20: peg$reportedPos = stack[stack.length - 1 - bc[ip + 1]]; ip += 2; break; case 21: peg$reportedPos = peg$currPos; ip++; break; case 22: params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]); for (i = 0; i < bc[ip + 3]; i++) { params[i] = stack[stack.length - 1 - params[i]]; } stack.splice( stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params) ); ip += 4 + bc[ip + 3]; break; case 23: stack.push(peg$parseRule(bc[ip + 1])); ip += 2; break; case 24: peg$silentFails++; ip++; break; case 25: peg$silentFails--; ip++; break; default: throw new Error("Invalid opcode: " + bc[ip] + "."); } } if (ends.length > 0) { end = ends.pop(); ip = ips.pop(); } else { break; } } return stack[0]; } helpers = require('../lib/helpers'); prefixes = require('./prefixes.json'); prefixMetadata = require('./prefixMetadata.json'); unitMetadata = require('./unitMetadata.json'); metrics = require('./metrics.json'); multiply = helpers.multiply; topower = helpers.topower; cleanup = helpers.cleanup; ismetric = helpers.ismetric(metrics); peg$result = peg$parseRule(peg$startRuleIndex); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail({ type: "end", description: "end of input" }); } throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); } } return { SyntaxError: SyntaxError, parse: parse }; })(); },{"../lib/helpers":410,"./metrics.json":405,"./prefixMetadata.json":406,"./prefixes.json":407,"./unitMetadata.json":409}],409:[function(require,module,exports){ module.exports={ "10*": { "isBase": false, "CODE": "10*", "isMetric": "no", "class": "dimless", "names": [ "the number ten for arbitrary powers" ], "printSymbols": [ "10" ], "properties": [ "number" ], "values": [ { "printable": "10", "numeric": 10 } ] }, "10^": { "isBase": false, "CODE": "10^", "isMetric": "no", "class": "dimless", "names": [ "the number ten for arbitrary powers" ], "printSymbols": [ "10" ], "properties": [ "number" ], "values": [ { "printable": "10", "numeric": 10 } ] }, "[pi]": { "isBase": false, "CODE": "[PI]", "isMetric": "no", "class": "dimless", "names": [ "the number pi" ], "printSymbols": [ "π" ], "properties": [ "number" ], "values": [ { "printable": "π", "numeric": 3.141592653589793 } ] }, "%": { "isBase": false, "CODE": "%", "isMetric": "no", "class": "dimless", "names": [ "percent" ], "printSymbols": [ "%" ], "properties": [ "fraction" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[ppth]": { "isBase": false, "CODE": "[PPTH]", "isMetric": "no", "class": "dimless", "names": [ "parts per thousand" ], "printSymbols": [ "ppth" ], "properties": [ "fraction" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[ppm]": { "isBase": false, "CODE": "[PPM]", "isMetric": "no", "class": "dimless", "names": [ "parts per million" ], "printSymbols": [ "ppm" ], "properties": [ "fraction" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[ppb]": { "isBase": false, "CODE": "[PPB]", "isMetric": "no", "class": "dimless", "names": [ "parts per billion" ], "printSymbols": [ "ppb" ], "properties": [ "fraction" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[pptr]": { "isBase": false, "CODE": "[PPTR]", "isMetric": "no", "class": "dimless", "names": [ "parts per trillion" ], "printSymbols": [ "pptr" ], "properties": [ "fraction" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "mol": { "isBase": false, "CODE": "MOL", "isMetric": "yes", "class": "si", "names": [ "mole" ], "printSymbols": [ "mol" ], "properties": [ "amount of substance" ], "values": [ { "printable": "6.0221367", "numeric": 6.0221367 } ] }, "sr": { "isBase": false, "CODE": "SR", "isMetric": "yes", "class": "si", "names": [ "steradian" ], "printSymbols": [ "sr" ], "properties": [ "solid angle" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Hz": { "isBase": false, "CODE": "HZ", "isMetric": "yes", "class": "si", "names": [ "Hertz" ], "printSymbols": [ "Hz" ], "properties": [ "frequency" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "N": { "isBase": false, "CODE": "N", "isMetric": "yes", "class": "si", "names": [ "Newton" ], "printSymbols": [ "N" ], "properties": [ "force" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Pa": { "isBase": false, "CODE": "PAL", "isMetric": "yes", "class": "si", "names": [ "Pascal" ], "printSymbols": [ "Pa" ], "properties": [ "pressure" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "J": { "isBase": false, "CODE": "J", "isMetric": "yes", "class": "si", "names": [ "Joule" ], "printSymbols": [ "J" ], "properties": [ "energy" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "W": { "isBase": false, "CODE": "W", "isMetric": "yes", "class": "si", "names": [ "Watt" ], "printSymbols": [ "W" ], "properties": [ "power" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "A": { "isBase": false, "CODE": "A", "isMetric": "yes", "class": "si", "names": [ "Ampère" ], "printSymbols": [ "A" ], "properties": [ "electric current" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "V": { "isBase": false, "CODE": "V", "isMetric": "yes", "class": "si", "names": [ "Volt" ], "printSymbols": [ "V" ], "properties": [ "electric potential" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "F": { "isBase": false, "CODE": "F", "isMetric": "yes", "class": "si", "names": [ "Farad" ], "printSymbols": [ "F" ], "properties": [ "electric capacitance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Ohm": { "isBase": false, "CODE": "OHM", "isMetric": "yes", "class": "si", "names": [ "Ohm" ], "printSymbols": [ "Ω" ], "properties": [ "electric resistance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "S": { "isBase": false, "CODE": "SIE", "isMetric": "yes", "class": "si", "names": [ "Siemens" ], "printSymbols": [ "S" ], "properties": [ "electric conductance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Wb": { "isBase": false, "CODE": "WB", "isMetric": "yes", "class": "si", "names": [ "Weber" ], "printSymbols": [ "Wb" ], "properties": [ "magentic flux" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Cel": { "isBase": false, "CODE": "CEL", "isMetric": "yes", "isSpecial": "yes", "class": "si", "names": [ "degree Celsius" ], "printSymbols": [ "°C" ], "properties": [ "temperature" ], "values": [ { "printable": "", "numeric": null } ] }, "T": { "isBase": false, "CODE": "T", "isMetric": "yes", "class": "si", "names": [ "Tesla" ], "printSymbols": [ "T" ], "properties": [ "magnetic flux density" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "H": { "isBase": false, "CODE": "H", "isMetric": "yes", "class": "si", "names": [ "Henry" ], "printSymbols": [ "H" ], "properties": [ "inductance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "lm": { "isBase": false, "CODE": "LM", "isMetric": "yes", "class": "si", "names": [ "lumen" ], "printSymbols": [ "lm" ], "properties": [ "luminous flux" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "lx": { "isBase": false, "CODE": "LX", "isMetric": "yes", "class": "si", "names": [ "lux" ], "printSymbols": [ "lx" ], "properties": [ "illuminance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Bq": { "isBase": false, "CODE": "BQ", "isMetric": "yes", "class": "si", "names": [ "Becquerel" ], "printSymbols": [ "Bq" ], "properties": [ "radioactivity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Gy": { "isBase": false, "CODE": "GY", "isMetric": "yes", "class": "si", "names": [ "Gray" ], "printSymbols": [ "Gy" ], "properties": [ "energy dose" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Sv": { "isBase": false, "CODE": "SV", "isMetric": "yes", "class": "si", "names": [ "Sievert" ], "printSymbols": [ "Sv" ], "properties": [ "dose equivalent" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "gon": { "isBase": false, "CODE": "GON", "isMetric": "no", "class": "iso1000", "names": [ "gon", "grade" ], "printSymbols": [ "□g" ], "properties": [ "plane angle" ], "values": [ { "printable": "0.9", "numeric": 0.9 } ] }, "deg": { "isBase": false, "CODE": "DEG", "isMetric": "no", "class": "iso1000", "names": [ "degree" ], "printSymbols": [ "°" ], "properties": [ "plane angle" ], "values": [ { "printable": "2", "numeric": 2 } ] }, "'": { "isBase": false, "CODE": "'", "isMetric": "no", "class": "iso1000", "names": [ "minute" ], "printSymbols": [ "'" ], "properties": [ "plane angle" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "''": { "isBase": false, "CODE": "''", "isMetric": "no", "class": "iso1000", "names": [ "second" ], "printSymbols": [ "''" ], "properties": [ "plane angle" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "l": { "isBase": false, "CODE": "L", "isMetric": "yes", "class": "iso1000", "names": [ "liter" ], "printSymbols": [ "l" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "L": { "isBase": false, "isMetric": "yes", "class": "iso1000", "names": [ "liter" ], "printSymbols": [ "L" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "ar": { "isBase": false, "CODE": "AR", "isMetric": "yes", "class": "iso1000", "names": [ "are" ], "printSymbols": [ "a" ], "properties": [ "area" ], "values": [ { "printable": "100", "numeric": 100 } ] }, "min": { "isBase": false, "CODE": "MIN", "isMetric": "no", "class": "iso1000", "names": [ "minute" ], "printSymbols": [ "min" ], "properties": [ "time" ], "values": [ { "printable": "60", "numeric": 60 } ] }, "h": { "isBase": false, "CODE": "HR", "isMetric": "no", "class": "iso1000", "names": [ "hour" ], "printSymbols": [ "h" ], "properties": [ "time" ], "values": [ { "printable": "60", "numeric": 60 } ] }, "d": { "isBase": false, "CODE": "D", "isMetric": "no", "class": "iso1000", "names": [ "day" ], "printSymbols": [ "d" ], "properties": [ "time" ], "values": [ { "printable": "24", "numeric": 24 } ] }, "a_t": { "isBase": false, "CODE": "ANN_T", "isMetric": "no", "class": "iso1000", "names": [ "tropical year" ], "printSymbols": [ "at" ], "properties": [ "time" ], "values": [ { "printable": "365.24219", "numeric": 365.24219 } ] }, "a_j": { "isBase": false, "CODE": "ANN_J", "isMetric": "no", "class": "iso1000", "names": [ "mean Julian year" ], "printSymbols": [ "aj" ], "properties": [ "time" ], "values": [ { "printable": "365.25", "numeric": 365.25 } ] }, "a_g": { "isBase": false, "CODE": "ANN_G", "isMetric": "no", "class": "iso1000", "names": [ "mean Gregorian year" ], "printSymbols": [ "ag" ], "properties": [ "time" ], "values": [ { "printable": "365.2425", "numeric": 365.2425 } ] }, "a": { "isBase": false, "CODE": "ANN", "isMetric": "no", "class": "iso1000", "names": [ "year" ], "printSymbols": [ "a" ], "properties": [ "time" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "wk": { "isBase": false, "CODE": "WK", "isMetric": "no", "class": "iso1000", "names": [ "week" ], "printSymbols": [ "wk" ], "properties": [ "time" ], "values": [ { "printable": "7", "numeric": 7 } ] }, "mo_s": { "isBase": false, "CODE": "MO_S", "isMetric": "no", "class": "iso1000", "names": [ "synodal month" ], "printSymbols": [ "mos" ], "properties": [ "time" ], "values": [ { "printable": "29.53059", "numeric": 29.53059 } ] }, "mo_j": { "isBase": false, "CODE": "MO_J", "isMetric": "no", "class": "iso1000", "names": [ "mean Julian month" ], "printSymbols": [ "moj" ], "properties": [ "time" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "mo_g": { "isBase": false, "CODE": "MO_G", "isMetric": "no", "class": "iso1000", "names": [ "mean Gregorian month" ], "printSymbols": [ "mog" ], "properties": [ "time" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "mo": { "isBase": false, "CODE": "MO", "isMetric": "no", "class": "iso1000", "names": [ "month" ], "printSymbols": [ "mo" ], "properties": [ "time" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "t": { "isBase": false, "CODE": "TNE", "isMetric": "yes", "class": "iso1000", "names": [ "tonne" ], "printSymbols": [ "t" ], "properties": [ "mass" ], "values": [ { "printable": "1 × 103", "numeric": 1000 } ] }, "bar": { "isBase": false, "CODE": "BAR", "isMetric": "yes", "class": "iso1000", "names": [ "bar" ], "printSymbols": [ "bar" ], "properties": [ "pressure" ], "values": [ { "printable": "1 × 105", "numeric": 100000 } ] }, "u": { "isBase": false, "CODE": "AMU", "isMetric": "yes", "class": "iso1000", "names": [ "unified atomic mass unit" ], "printSymbols": [ "u" ], "properties": [ "mass" ], "values": [ { "printable": "1.6605402 × 10-24", "numeric": 1.6605402e-24 } ] }, "eV": { "isBase": false, "CODE": "EV", "isMetric": "yes", "class": "iso1000", "names": [ "electronvolt" ], "printSymbols": [ "eV" ], "properties": [ "energy" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "AU": { "isBase": false, "CODE": "ASU", "isMetric": "no", "class": "iso1000", "names": [ "astronomic unit" ], "printSymbols": [ "AU" ], "properties": [ "length" ], "values": [ { "printable": "149597.870691", "numeric": 149597.870691 } ] }, "pc": { "isBase": false, "CODE": "PRS", "isMetric": "yes", "class": "iso1000", "names": [ "parsec" ], "printSymbols": [ "pc" ], "properties": [ "length" ], "values": [ { "printable": "3.085678 × 1016", "numeric": 30856780000000000 } ] }, "[c]": { "isBase": false, "CODE": "[C]", "isMetric": "yes", "class": "const", "names": [ "velocity of light" ], "printSymbols": [ "c" ], "properties": [ "velocity" ], "values": [ { "printable": "299792458", "numeric": 299792458 } ] }, "[h]": { "isBase": false, "CODE": "[H]", "isMetric": "yes", "class": "const", "names": [ "Planck constant" ], "printSymbols": [ "h" ], "properties": [ "action" ], "values": [ { "printable": "6.6260755 × 10-24", "numeric": 6.6260755e-24 } ] }, "[k]": { "isBase": false, "CODE": "[K]", "isMetric": "yes", "class": "const", "names": [ "Boltzmann constant" ], "printSymbols": [ "k" ], "properties": [ "(unclassified)" ], "values": [ { "printable": "1.380658 × 10-23", "numeric": 1.380658e-23 } ] }, "[eps_0]": { "isBase": false, "CODE": "[EPS_0]", "isMetric": "yes", "class": "const", "names": [ "permittivity of vacuum" ], "printSymbols": [ "ε\n 0\n \n " ], "properties": [ "electric permittivity" ], "values": [ { "printable": "8.854187817 × 10-12", "numeric": 8.854187817e-12 } ] }, "[mu_0]": { "isBase": false, "CODE": "[MU_0]", "isMetric": "yes", "class": "const", "names": [ "permeability of vacuum" ], "printSymbols": [ "μ\n 0\n \n " ], "properties": [ "magnetic permeability" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[e]": { "isBase": false, "CODE": "[E]", "isMetric": "yes", "class": "const", "names": [ "elementary charge" ], "printSymbols": [ "e" ], "properties": [ "electric charge" ], "values": [ { "printable": "1.60217733 × 10-19", "numeric": 1.60217733e-19 } ] }, "[m_e]": { "isBase": false, "CODE": "[M_E]", "isMetric": "yes", "class": "const", "names": [ "electron mass" ], "printSymbols": [ "m\n e\n \n " ], "properties": [ "mass" ], "values": [ { "printable": "9.1093897 × 10-28", "numeric": 9.1093897e-28 } ] }, "[m_p]": { "isBase": false, "CODE": "[M_P]", "isMetric": "yes", "class": "const", "names": [ "proton mass" ], "printSymbols": [ "m\n p\n \n " ], "properties": [ "mass" ], "values": [ { "printable": "1.6726231 × 10-24", "numeric": 1.6726231e-24 } ] }, "[G]": { "isBase": false, "CODE": "[GC]", "isMetric": "yes", "class": "const", "names": [ "Newtonian constant of gravitation" ], "printSymbols": [ "G" ], "properties": [ "(unclassified)" ], "values": [ { "printable": "6.67259 × 10-11", "numeric": 6.67259e-11 } ] }, "[g]": { "isBase": false, "CODE": "[G]", "isMetric": "yes", "class": "const", "names": [ "standard acceleration of free fall" ], "printSymbols": [ "gn\n " ], "properties": [ "acceleration" ], "values": [ { "printable": "9.80665", "numeric": 9.80665 } ] }, "atm": { "isBase": false, "CODE": "ATM", "isMetric": "no", "class": "const", "names": [ "standard atmosphere" ], "printSymbols": [ "atm" ], "properties": [ "pressure" ], "values": [ { "printable": "101325", "numeric": 101325 } ] }, "[ly]": { "isBase": false, "CODE": "[LY]", "isMetric": "yes", "class": "const", "names": [ "light-year" ], "printSymbols": [ "l.y." ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "gf": { "isBase": false, "CODE": "GF", "isMetric": "yes", "class": "const", "names": [ "gram-force" ], "printSymbols": [ "gf" ], "properties": [ "force" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[lbf_av]": { "isBase": false, "CODE": "[LBF_AV]", "isMetric": "no", "class": "const", "names": [ "pound force" ], "printSymbols": [ "lbf" ], "properties": [ "force" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Ky": { "isBase": false, "CODE": "KY", "isMetric": "yes", "class": "cgs", "names": [ "Kayser" ], "printSymbols": [ "K" ], "properties": [ "lineic number" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Gal": { "isBase": false, "CODE": "GL", "isMetric": "yes", "class": "cgs", "names": [ "Gal" ], "printSymbols": [ "Gal" ], "properties": [ "acceleration" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "dyn": { "isBase": false, "CODE": "DYN", "isMetric": "yes", "class": "cgs", "names": [ "dyne" ], "printSymbols": [ "dyn" ], "properties": [ "force" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "erg": { "isBase": false, "CODE": "ERG", "isMetric": "yes", "class": "cgs", "names": [ "erg" ], "printSymbols": [ "erg" ], "properties": [ "energy" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "P": { "isBase": false, "CODE": "P", "isMetric": "yes", "class": "cgs", "names": [ "Poise" ], "printSymbols": [ "P" ], "properties": [ "dynamic viscosity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Bi": { "isBase": false, "CODE": "BI", "isMetric": "yes", "class": "cgs", "names": [ "Biot" ], "printSymbols": [ "Bi" ], "properties": [ "electric current" ], "values": [ { "printable": "10", "numeric": 10 } ] }, "St": { "isBase": false, "CODE": "ST", "isMetric": "yes", "class": "cgs", "names": [ "Stokes" ], "printSymbols": [ "St" ], "properties": [ "kinematic viscosity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Mx": { "isBase": false, "CODE": "MX", "isMetric": "yes", "class": "cgs", "names": [ "Maxwell" ], "printSymbols": [ "Mx" ], "properties": [ "flux of magnetic induction" ], "values": [ { "printable": "1 × 10-8", "numeric": 1e-8 } ] }, "G": { "isBase": false, "CODE": "GS", "isMetric": "yes", "class": "cgs", "names": [ "Gauss" ], "printSymbols": [ "Gs" ], "properties": [ "magnetic flux density" ], "values": [ { "printable": "1 × 10-4", "numeric": 0.0001 } ] }, "Oe": { "isBase": false, "CODE": "OE", "isMetric": "yes", "class": "cgs", "names": [ "Oersted" ], "printSymbols": [ "Oe" ], "properties": [ "magnetic field intensity" ], "values": [ { "printable": "250", "numeric": 250 } ] }, "Gb": { "isBase": false, "CODE": "GB", "isMetric": "yes", "class": "cgs", "names": [ "Gilbert" ], "printSymbols": [ "Gb" ], "properties": [ "magnetic tension" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "sb": { "isBase": false, "CODE": "SB", "isMetric": "yes", "class": "cgs", "names": [ "stilb" ], "printSymbols": [ "sb" ], "properties": [ "lum. intensity density" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Lmb": { "isBase": false, "CODE": "LMB", "isMetric": "yes", "class": "cgs", "names": [ "Lambert" ], "printSymbols": [ "L" ], "properties": [ "brightness" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "ph": { "isBase": false, "CODE": "PHT", "isMetric": "yes", "class": "cgs", "names": [ "phot" ], "printSymbols": [ "ph" ], "properties": [ "illuminance" ], "values": [ { "printable": "1 × 10-4", "numeric": 0.0001 } ] }, "Ci": { "isBase": false, "CODE": "CI", "isMetric": "yes", "class": "cgs", "names": [ "Curie" ], "printSymbols": [ "Ci" ], "properties": [ "radioactivity" ], "values": [ { "printable": "3.7 × 1010", "numeric": 37000000000 } ] }, "R": { "isBase": false, "CODE": "ROE", "isMetric": "yes", "class": "cgs", "names": [ "Roentgen" ], "printSymbols": [ "R" ], "properties": [ "ion dose" ], "values": [ { "printable": "2.58 × 10-4", "numeric": 0.000258 } ] }, "RAD": { "isBase": false, "CODE": "[RAD]", "isMetric": "yes", "class": "cgs", "names": [ "radiation absorbed dose" ], "printSymbols": [ "RAD" ], "properties": [ "energy dose" ], "values": [ { "printable": "100", "numeric": 100 } ] }, "REM": { "isBase": false, "CODE": "[REM]", "isMetric": "yes", "class": "cgs", "names": [ "radiation equivalent man" ], "printSymbols": [ "REM" ], "properties": [ "dose equivalent" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[in_i]": { "isBase": false, "CODE": "[IN_I]", "isMetric": "no", "class": "intcust", "names": [ "inch" ], "printSymbols": [ "in" ], "properties": [ "length" ], "values": [ { "printable": "2.54", "numeric": 2.54 } ] }, "[ft_i]": { "isBase": false, "CODE": "[FT_I]", "isMetric": "no", "class": "intcust", "names": [ "foot" ], "printSymbols": [ "ft" ], "properties": [ "length" ], "values": [ { "printable": "12", "numeric": 12 } ] }, "[yd_i]": { "isBase": false, "CODE": "[YD_I]", "isMetric": "no", "class": "intcust", "names": [ "yard" ], "printSymbols": [ "yd" ], "properties": [ "length" ], "values": [ { "printable": "3", "numeric": 3 } ] }, "[mi_i]": { "isBase": false, "CODE": "[MI_I]", "isMetric": "no", "class": "intcust", "names": [ "statute mile" ], "printSymbols": [ "mi" ], "properties": [ "length" ], "values": [ { "printable": "5280", "numeric": 5280 } ] }, "[fth_i]": { "isBase": false, "CODE": "[FTH_I]", "isMetric": "no", "class": "intcust", "names": [ "fathom" ], "printSymbols": [ "fth" ], "properties": [ "depth of water" ], "values": [ { "printable": "6", "numeric": 6 } ] }, "[nmi_i]": { "isBase": false, "CODE": "[NMI_I]", "isMetric": "no", "class": "intcust", "names": [ "nautical mile" ], "printSymbols": [ "n.mi" ], "properties": [ "length" ], "values": [ { "printable": "1852", "numeric": 1852 } ] }, "[kn_i]": { "isBase": false, "CODE": "[KN_I]", "isMetric": "no", "class": "intcust", "names": [ "knot" ], "printSymbols": [ "knot" ], "properties": [ "velocity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[sin_i]": { "isBase": false, "CODE": "[SIN_I]", "isMetric": "no", "class": "intcust", "names": [ "square inch" ], "properties": [ "area" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[sft_i]": { "isBase": false, "CODE": "[SFT_I]", "isMetric": "no", "class": "intcust", "names": [ "square foot" ], "properties": [ "area" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[syd_i]": { "isBase": false, "CODE": "[SYD_I]", "isMetric": "no", "class": "intcust", "names": [ "square yard" ], "properties": [ "area" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[cin_i]": { "isBase": false, "CODE": "[CIN_I]", "isMetric": "no", "class": "intcust", "names": [ "cubic inch" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[cft_i]": { "isBase": false, "CODE": "[CFT_I]", "isMetric": "no", "class": "intcust", "names": [ "cubic foot" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[cyd_i]": { "isBase": false, "CODE": "[CYD_I]", "isMetric": "no", "class": "intcust", "names": [ "cubic yard" ], "printSymbols": [ "cu.yd" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[bf_i]": { "isBase": false, "CODE": "[BF_I]", "isMetric": "no", "class": "intcust", "names": [ "board foot" ], "properties": [ "volume" ], "values": [ { "printable": "144", "numeric": 144 } ] }, "[cr_i]": { "isBase": false, "CODE": "[CR_I]", "isMetric": "no", "class": "intcust", "names": [ "cord" ], "properties": [ "volume" ], "values": [ { "printable": "128", "numeric": 128 } ] }, "[mil_i]": { "isBase": false, "CODE": "[MIL_I]", "isMetric": "no", "class": "intcust", "names": [ "mil" ], "printSymbols": [ "mil" ], "properties": [ "length" ], "values": [ { "printable": "1 × 10-3", "numeric": 0.001 } ] }, "[cml_i]": { "isBase": false, "CODE": "[CML_I]", "isMetric": "no", "class": "intcust", "names": [ "circular mil" ], "printSymbols": [ "circ.mil" ], "properties": [ "area" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[hd_i]": { "isBase": false, "CODE": "[HD_I]", "isMetric": "no", "class": "intcust", "names": [ "hand" ], "printSymbols": [ "hd" ], "properties": [ "height of horses" ], "values": [ { "printable": "4", "numeric": 4 } ] }, "[ft_us]": { "isBase": false, "CODE": "[FT_US]", "isMetric": "no", "class": "us-lengths", "names": [ "foot" ], "printSymbols": [ "ftus" ], "properties": [ "length" ], "values": [ { "printable": "1200", "numeric": 1200 } ] }, "[yd_us]": { "isBase": false, "CODE": "[YD_US]", "isMetric": "no", "class": "us-lengths", "names": [ "yard" ], "properties": [ "length" ], "values": [ { "printable": "3", "numeric": 3 } ] }, "[in_us]": { "isBase": false, "CODE": "[IN_US]", "isMetric": "no", "class": "us-lengths", "names": [ "inch" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[rd_us]": { "isBase": false, "CODE": "[RD_US]", "isMetric": "no", "class": "us-lengths", "names": [ "rod" ], "properties": [ "length" ], "values": [ { "printable": "16.5", "numeric": 16.5 } ] }, "[ch_us]": { "isBase": false, "CODE": "[CH_US]", "isMetric": "no", "class": "us-lengths", "names": [ "Gunter's chain", "Surveyor's chain" ], "properties": [ "length" ], "values": [ { "printable": "4", "numeric": 4 } ] }, "[lk_us]": { "isBase": false, "CODE": "[LK_US]", "isMetric": "no", "class": "us-lengths", "names": [ "link for Gunter's chain" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[rch_us]": { "isBase": false, "CODE": "[RCH_US]", "isMetric": "no", "class": "us-lengths", "names": [ "Ramden's chain", "Engineer's chain" ], "properties": [ "length" ], "values": [ { "printable": "100", "numeric": 100 } ] }, "[rlk_us]": { "isBase": false, "CODE": "[RLK_US]", "isMetric": "no", "class": "us-lengths", "names": [ "link for Ramden's chain" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[fth_us]": { "isBase": false, "CODE": "[FTH_US]", "isMetric": "no", "class": "us-lengths", "names": [ "fathom" ], "properties": [ "length" ], "values": [ { "printable": "6", "numeric": 6 } ] }, "[fur_us]": { "isBase": false, "CODE": "[FUR_US]", "isMetric": "no", "class": "us-lengths", "names": [ "furlong" ], "properties": [ "length" ], "values": [ { "printable": "40", "numeric": 40 } ] }, "[mi_us]": { "isBase": false, "CODE": "[MI_US]", "isMetric": "no", "class": "us-lengths", "names": [ "mile" ], "properties": [ "length" ], "values": [ { "printable": "8", "numeric": 8 } ] }, "[acr_us]": { "isBase": false, "CODE": "[ACR_US]", "isMetric": "no", "class": "us-lengths", "names": [ "acre" ], "properties": [ "area" ], "values": [ { "printable": "160", "numeric": 160 } ] }, "[srd_us]": { "isBase": false, "CODE": "[SRD_US]", "isMetric": "no", "class": "us-lengths", "names": [ "square rod" ], "properties": [ "area" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[smi_us]": { "isBase": false, "CODE": "[SMI_US]", "isMetric": "no", "class": "us-lengths", "names": [ "square mile" ], "properties": [ "area" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[sct]": { "isBase": false, "CODE": "[SCT]", "isMetric": "no", "class": "us-lengths", "names": [ "section" ], "properties": [ "area" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[twp]": { "isBase": false, "CODE": "[TWP]", "isMetric": "no", "class": "us-lengths", "names": [ "township" ], "properties": [ "area" ], "values": [ { "printable": "36", "numeric": 36 } ] }, "[mil_us]": { "isBase": false, "CODE": "[MIL_US]", "isMetric": "no", "class": "us-lengths", "names": [ "mil" ], "properties": [ "length" ], "values": [ { "printable": "1 × 10-3", "numeric": 0.001 } ] }, "[in_br]": { "isBase": false, "CODE": "[IN_BR]", "isMetric": "no", "class": "brit-length", "names": [ "inch" ], "properties": [ "length" ], "values": [ { "printable": "2.539998", "numeric": 2.539998 } ] }, "[ft_br]": { "isBase": false, "CODE": "[FT_BR]", "isMetric": "no", "class": "brit-length", "names": [ "foot" ], "properties": [ "length" ], "values": [ { "printable": "12", "numeric": 12 } ] }, "[rd_br]": { "isBase": false, "CODE": "[RD_BR]", "isMetric": "no", "class": "brit-length", "names": [ "rod" ], "properties": [ "length" ], "values": [ { "printable": "16.5", "numeric": 16.5 } ] }, "[ch_br]": { "isBase": false, "CODE": "[CH_BR]", "isMetric": "no", "class": "brit-length", "names": [ "Gunter's chain" ], "properties": [ "length" ], "values": [ { "printable": "4", "numeric": 4 } ] }, "[lk_br]": { "isBase": false, "CODE": "[LK_BR]", "isMetric": "no", "class": "brit-length", "names": [ "link for Gunter's chain" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[fth_br]": { "isBase": false, "CODE": "[FTH_BR]", "isMetric": "no", "class": "brit-length", "names": [ "fathom" ], "properties": [ "length" ], "values": [ { "printable": "6", "numeric": 6 } ] }, "[pc_br]": { "isBase": false, "CODE": "[PC_BR]", "isMetric": "no", "class": "brit-length", "names": [ "pace" ], "properties": [ "length" ], "values": [ { "printable": "2.5", "numeric": 2.5 } ] }, "[yd_br]": { "isBase": false, "CODE": "[YD_BR]", "isMetric": "no", "class": "brit-length", "names": [ "yard" ], "properties": [ "length" ], "values": [ { "printable": "3", "numeric": 3 } ] }, "[mi_br]": { "isBase": false, "CODE": "[MI_BR]", "isMetric": "no", "class": "brit-length", "names": [ "mile" ], "properties": [ "length" ], "values": [ { "printable": "5280", "numeric": 5280 } ] }, "[nmi_br]": { "isBase": false, "CODE": "[NMI_BR]", "isMetric": "no", "class": "brit-length", "names": [ "nautical mile" ], "properties": [ "length" ], "values": [ { "printable": "6080", "numeric": 6080 } ] }, "[kn_br]": { "isBase": false, "CODE": "[KN_BR]", "isMetric": "no", "class": "brit-length", "names": [ "knot" ], "properties": [ "velocity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[acr_br]": { "isBase": false, "CODE": "[ACR_BR]", "isMetric": "no", "class": "brit-length", "names": [ "acre" ], "properties": [ "area" ], "values": [ { "printable": "4840", "numeric": 4840 } ] }, "[gal_us]": { "isBase": false, "CODE": "[GAL_US]", "isMetric": "no", "class": "us-volumes", "names": [ "Queen Anne's wine gallon" ], "properties": [ "fluid volume" ], "values": [ { "printable": "231", "numeric": 231 } ] }, "[bbl_us]": { "isBase": false, "CODE": "[BBL_US]", "isMetric": "no", "class": "us-volumes", "names": [ "barrel" ], "properties": [ "fluid volume" ], "values": [ { "printable": "42", "numeric": 42 } ] }, "[qt_us]": { "isBase": false, "CODE": "[QT_US]", "isMetric": "no", "class": "us-volumes", "names": [ "quart" ], "properties": [ "fluid volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[pt_us]": { "isBase": false, "CODE": "[PT_US]", "isMetric": "no", "class": "us-volumes", "names": [ "pint" ], "properties": [ "fluid volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[gil_us]": { "isBase": false, "CODE": "[GIL_US]", "isMetric": "no", "class": "us-volumes", "names": [ "gill" ], "properties": [ "fluid volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[foz_us]": { "isBase": false, "CODE": "[FOZ_US]", "isMetric": "no", "class": "us-volumes", "names": [ "fluid ounce" ], "printSymbols": [ "oz fl" ], "properties": [ "fluid volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[fdr_us]": { "isBase": false, "CODE": "[FDR_US]", "isMetric": "no", "class": "us-volumes", "names": [ "fluid dram" ], "properties": [ "fluid volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[min_us]": { "isBase": false, "CODE": "[MIN_US]", "isMetric": "no", "class": "us-volumes", "names": [ "minim" ], "properties": [ "fluid volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[crd_us]": { "isBase": false, "CODE": "[CRD_US]", "isMetric": "no", "class": "us-volumes", "names": [ "cord" ], "properties": [ "fluid volume" ], "values": [ { "printable": "128", "numeric": 128 } ] }, "[bu_us]": { "isBase": false, "CODE": "[BU_US]", "isMetric": "no", "class": "us-volumes", "names": [ "bushel" ], "properties": [ "dry volume" ], "values": [ { "printable": "2150.42", "numeric": 2150.42 } ] }, "[gal_wi]": { "isBase": false, "CODE": "[GAL_WI]", "isMetric": "no", "class": "us-volumes", "names": [ "historical winchester gallon" ], "properties": [ "dry volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[pk_us]": { "isBase": false, "CODE": "[PK_US]", "isMetric": "no", "class": "us-volumes", "names": [ "peck" ], "properties": [ "dry volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[dqt_us]": { "isBase": false, "CODE": "[DQT_US]", "isMetric": "no", "class": "us-volumes", "names": [ "dry quart" ], "properties": [ "dry volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[dpt_us]": { "isBase": false, "CODE": "[DPT_US]", "isMetric": "no", "class": "us-volumes", "names": [ "dry pint" ], "properties": [ "dry volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[tbs_us]": { "isBase": false, "CODE": "[TBS_US]", "isMetric": "no", "class": "us-volumes", "names": [ "tablespoon" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[tsp_us]": { "isBase": false, "CODE": "[TSP_US]", "isMetric": "no", "class": "us-volumes", "names": [ "teaspoon" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[cup_us]": { "isBase": false, "CODE": "[CUP_US]", "isMetric": "no", "class": "us-volumes", "names": [ "cup" ], "properties": [ "volume" ], "values": [ { "printable": "16", "numeric": 16 } ] }, "[foz_m]": { "isBase": false, "CODE": "[FOZ_M]", "isMetric": "no", "class": "us-volumes", "names": [ "metric fluid ounce" ], "printSymbols": [ "oz fl" ], "properties": [ "fluid volume" ], "values": [ { "printable": "30", "numeric": 30 } ] }, "[cup_m]": { "isBase": false, "CODE": "[CUP_M]", "isMetric": "no", "class": "us-volumes", "names": [ "metric cup" ], "properties": [ "volume" ], "values": [ { "printable": "240", "numeric": 240 } ] }, "[tsp_m]": { "isBase": false, "CODE": "[TSP_M]", "isMetric": "no", "class": "us-volumes", "names": [ "metric teaspoon" ], "properties": [ "volume" ], "values": [ { "printable": "5", "numeric": 5 } ] }, "[tbs_m]": { "isBase": false, "CODE": "[TBS_M]", "isMetric": "no", "class": "us-volumes", "names": [ "metric tablespoon" ], "properties": [ "volume" ], "values": [ { "printable": "15", "numeric": 15 } ] }, "[gal_br]": { "isBase": false, "CODE": "[GAL_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "gallon" ], "properties": [ "volume" ], "values": [ { "printable": "4.54609", "numeric": 4.54609 } ] }, "[pk_br]": { "isBase": false, "CODE": "[PK_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "peck" ], "properties": [ "volume" ], "values": [ { "printable": "2", "numeric": 2 } ] }, "[bu_br]": { "isBase": false, "CODE": "[BU_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "bushel" ], "properties": [ "volume" ], "values": [ { "printable": "4", "numeric": 4 } ] }, "[qt_br]": { "isBase": false, "CODE": "[QT_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "quart" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[pt_br]": { "isBase": false, "CODE": "[PT_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "pint" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[gil_br]": { "isBase": false, "CODE": "[GIL_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "gill" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[foz_br]": { "isBase": false, "CODE": "[FOZ_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "fluid ounce" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[fdr_br]": { "isBase": false, "CODE": "[FDR_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "fluid dram" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[min_br]": { "isBase": false, "CODE": "[MIN_BR]", "isMetric": "no", "class": "brit-volumes", "names": [ "minim" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[gr]": { "isBase": false, "CODE": "[GR]", "isMetric": "no", "class": "avoirdupois", "names": [ "grain" ], "properties": [ "mass" ], "values": [ { "printable": "64.79891", "numeric": 64.79891 } ] }, "[lb_av]": { "isBase": false, "CODE": "[LB_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "pound" ], "printSymbols": [ "lb" ], "properties": [ "mass" ], "values": [ { "printable": "7000", "numeric": 7000 } ] }, "[oz_av]": { "isBase": false, "CODE": "[OZ_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "ounce" ], "printSymbols": [ "oz" ], "properties": [ "mass" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[dr_av]": { "isBase": false, "CODE": "[DR_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "dram" ], "properties": [ "mass" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[scwt_av]": { "isBase": false, "CODE": "[SCWT_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "short hundredweight", "U.S. hundredweight" ], "properties": [ "mass" ], "values": [ { "printable": "100", "numeric": 100 } ] }, "[lcwt_av]": { "isBase": false, "CODE": "[LCWT_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "long hundredweight", "British hundredweight" ], "properties": [ "mass" ], "values": [ { "printable": "112", "numeric": 112 } ] }, "[ston_av]": { "isBase": false, "CODE": "[STON_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "short ton", "U.S. ton" ], "properties": [ "mass" ], "values": [ { "printable": "20", "numeric": 20 } ] }, "[lton_av]": { "isBase": false, "CODE": "[LTON_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "long ton", "British ton" ], "properties": [ "mass" ], "values": [ { "printable": "20", "numeric": 20 } ] }, "[stone_av]": { "isBase": false, "CODE": "[STONE_AV]", "isMetric": "no", "class": "avoirdupois", "names": [ "stone", "British stone" ], "properties": [ "mass" ], "values": [ { "printable": "14", "numeric": 14 } ] }, "[pwt_tr]": { "isBase": false, "CODE": "[PWT_TR]", "isMetric": "no", "class": "troy", "names": [ "pennyweight" ], "printSymbols": [ "dwt" ], "properties": [ "mass" ], "values": [ { "printable": "24", "numeric": 24 } ] }, "[oz_tr]": { "isBase": false, "CODE": "[OZ_TR]", "isMetric": "no", "class": "troy", "names": [ "troy ounce" ], "printSymbols": [ "oz t" ], "properties": [ "mass" ], "values": [ { "printable": "20", "numeric": 20 } ] }, "[lb_tr]": { "isBase": false, "CODE": "[LB_TR]", "isMetric": "no", "class": "troy", "names": [ "troy pound" ], "printSymbols": [ "lb t" ], "properties": [ "mass" ], "values": [ { "printable": "12", "numeric": 12 } ] }, "[sc_ap]": { "isBase": false, "CODE": "[SC_AP]", "isMetric": "no", "class": "apoth", "names": [ "scruple" ], "printSymbols": [ "℈" ], "properties": [ "mass" ], "values": [ { "printable": "20", "numeric": 20 } ] }, "[dr_ap]": { "isBase": false, "CODE": "[DR_AP]", "isMetric": "no", "class": "apoth", "names": [ "dram", "drachm" ], "printSymbols": [ "ʒ" ], "properties": [ "mass" ], "values": [ { "printable": "3", "numeric": 3 } ] }, "[oz_ap]": { "isBase": false, "CODE": "[OZ_AP]", "isMetric": "no", "class": "apoth", "names": [ "ounce" ], "printSymbols": [ "℥" ], "properties": [ "mass" ], "values": [ { "printable": "8", "numeric": 8 } ] }, "[lb_ap]": { "isBase": false, "CODE": "[LB_AP]", "isMetric": "no", "class": "apoth", "names": [ "pound" ], "printSymbols": [ "lb" ], "properties": [ "mass" ], "values": [ { "printable": "12", "numeric": 12 } ] }, "[oz_m]": { "isBase": false, "CODE": "[OZ_M]", "isMetric": "no", "class": "apoth", "names": [ "metric ounce" ], "properties": [ "mass" ], "values": [ { "printable": "28", "numeric": 28 } ] }, "[lne]": { "isBase": false, "CODE": "[LNE]", "isMetric": "no", "class": "typeset", "names": [ "line" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[pnt]": { "isBase": false, "CODE": "[PNT]", "isMetric": "no", "class": "typeset", "names": [ "point" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[pca]": { "isBase": false, "CODE": "[PCA]", "isMetric": "no", "class": "typeset", "names": [ "pica" ], "properties": [ "length" ], "values": [ { "printable": "12", "numeric": 12 } ] }, "[pnt_pr]": { "isBase": false, "CODE": "[PNT_PR]", "isMetric": "no", "class": "typeset", "names": [ "Printer's point" ], "properties": [ "length" ], "values": [ { "printable": "0.013837", "numeric": 0.013837 } ] }, "[pca_pr]": { "isBase": false, "CODE": "[PCA_PR]", "isMetric": "no", "class": "typeset", "names": [ "Printer's pica" ], "properties": [ "length" ], "values": [ { "printable": "12", "numeric": 12 } ] }, "[pied]": { "isBase": false, "CODE": "[PIED]", "isMetric": "no", "class": "typeset", "names": [ "pied", "French foot" ], "properties": [ "length" ], "values": [ { "printable": "32.48", "numeric": 32.48 } ] }, "[pouce]": { "isBase": false, "CODE": "[POUCE]", "isMetric": "no", "class": "typeset", "names": [ "pouce", "French inch" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[ligne]": { "isBase": false, "CODE": "[LIGNE]", "isMetric": "no", "class": "typeset", "names": [ "ligne", "French line" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[didot]": { "isBase": false, "CODE": "[DIDOT]", "isMetric": "no", "class": "typeset", "names": [ "didot", "Didot's point" ], "properties": [ "length" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[cicero]": { "isBase": false, "CODE": "[CICERO]", "isMetric": "no", "class": "typeset", "names": [ "cicero", "Didot's pica" ], "properties": [ "length" ], "values": [ { "printable": "12", "numeric": 12 } ] }, "[degF]": { "isBase": false, "CODE": "[DEGF]", "isMetric": "no", "isSpecial": "yes", "class": "heat", "names": [ "degree Fahrenheit" ], "printSymbols": [ "°F" ], "properties": [ "temperature" ], "values": [ { "printable": "", "numeric": null } ] }, "[degR]": { "isBase": false, "CODE": "[degR]", "isMetric": "no", "class": "heat", "names": [ "degree Rankine" ], "printSymbols": [ "°R" ], "properties": [ "temperature" ], "values": [ { "printable": "5", "numeric": 5 } ] }, "cal_[15]": { "isBase": false, "CODE": "CAL_[15]", "isMetric": "yes", "class": "heat", "names": [ "calorie at 15 °C" ], "printSymbols": [ "cal15°C" ], "properties": [ "energy" ], "values": [ { "printable": "4.18580", "numeric": 4.1858 } ] }, "cal_[20]": { "isBase": false, "CODE": "CAL_[20]", "isMetric": "yes", "class": "heat", "names": [ "calorie at 20 °C" ], "printSymbols": [ "cal20°C" ], "properties": [ "energy" ], "values": [ { "printable": "4.18190", "numeric": 4.1819 } ] }, "cal_m": { "isBase": false, "CODE": "CAL_M", "isMetric": "yes", "class": "heat", "names": [ "mean calorie" ], "printSymbols": [ "calm" ], "properties": [ "energy" ], "values": [ { "printable": "4.19002", "numeric": 4.19002 } ] }, "cal_IT": { "isBase": false, "CODE": "CAL_IT", "isMetric": "yes", "class": "heat", "names": [ "international table calorie" ], "printSymbols": [ "calIT" ], "properties": [ "energy" ], "values": [ { "printable": "4.1868", "numeric": 4.1868 } ] }, "cal_th": { "isBase": false, "CODE": "CAL_TH", "isMetric": "yes", "class": "heat", "names": [ "thermochemical calorie" ], "printSymbols": [ "calth" ], "properties": [ "energy" ], "values": [ { "printable": "4.184", "numeric": 4.184 } ] }, "cal": { "isBase": false, "CODE": "CAL", "isMetric": "yes", "class": "heat", "names": [ "calorie" ], "printSymbols": [ "cal" ], "properties": [ "energy" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[Cal]": { "isBase": false, "CODE": "[CAL]", "isMetric": "no", "class": "heat", "names": [ "nutrition label Calories" ], "printSymbols": [ "Cal" ], "properties": [ "energy" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[Btu_39]": { "isBase": false, "CODE": "[BTU_39]", "isMetric": "no", "class": "heat", "names": [ "British thermal unit at 39 °F" ], "printSymbols": [ "Btu39°F" ], "properties": [ "energy" ], "values": [ { "printable": "1.05967", "numeric": 1.05967 } ] }, "[Btu_59]": { "isBase": false, "CODE": "[BTU_59]", "isMetric": "no", "class": "heat", "names": [ "British thermal unit at 59 °F" ], "printSymbols": [ "Btu59°F" ], "properties": [ "energy" ], "values": [ { "printable": "1.05480", "numeric": 1.0548 } ] }, "[Btu_60]": { "isBase": false, "CODE": "[BTU_60]", "isMetric": "no", "class": "heat", "names": [ "British thermal unit at 60 °F" ], "printSymbols": [ "Btu60°F" ], "properties": [ "energy" ], "values": [ { "printable": "1.05468", "numeric": 1.05468 } ] }, "[Btu_m]": { "isBase": false, "CODE": "[BTU_M]", "isMetric": "no", "class": "heat", "names": [ "mean British thermal unit" ], "printSymbols": [ "Btum" ], "properties": [ "energy" ], "values": [ { "printable": "1.05587", "numeric": 1.05587 } ] }, "[Btu_IT]": { "isBase": false, "CODE": "[BTU_IT]", "isMetric": "no", "class": "heat", "names": [ "international table British thermal unit" ], "printSymbols": [ "BtuIT" ], "properties": [ "energy" ], "values": [ { "printable": "1.05505585262", "numeric": 1.05505585262 } ] }, "[Btu_th]": { "isBase": false, "CODE": "[BTU_TH]", "isMetric": "no", "class": "heat", "names": [ "thermochemical British thermal unit" ], "printSymbols": [ "Btuth" ], "properties": [ "energy" ], "values": [ { "printable": "1.054350", "numeric": 1.05435 } ] }, "[Btu]": { "isBase": false, "CODE": "[BTU]", "isMetric": "no", "class": "heat", "names": [ "British thermal unit" ], "printSymbols": [ "btu" ], "properties": [ "energy" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[HP]": { "isBase": false, "CODE": "[HP]", "isMetric": "no", "class": "heat", "names": [ "horsepower" ], "properties": [ "power" ], "values": [ { "printable": "550", "numeric": 550 } ] }, "tex": { "isBase": false, "CODE": "TEX", "isMetric": "yes", "class": "heat", "names": [ "tex" ], "printSymbols": [ "tex" ], "properties": [ "linear mass density (of textile thread)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[den]": { "isBase": false, "CODE": "[DEN]", "isMetric": "no", "class": "heat", "names": [ "Denier" ], "printSymbols": [ "den" ], "properties": [ "linear mass density (of textile thread)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "m[H2O]": { "isBase": false, "CODE": "M[H2O]", "isMetric": "yes", "class": "clinical", "names": [ "meter of water column" ], "printSymbols": [ "m H\n 2\n O" ], "properties": [ "pressure" ], "values": [ { "printable": "9.80665", "numeric": 9.80665 } ] }, "m[Hg]": { "isBase": false, "CODE": "M[HG]", "isMetric": "yes", "class": "clinical", "names": [ "meter of mercury column" ], "printSymbols": [ "m Hg" ], "properties": [ "pressure" ], "values": [ { "printable": "133.3220", "numeric": 133.322 } ] }, "[in_i'H2O]": { "isBase": false, "CODE": "[IN_I'H2O]", "isMetric": "no", "class": "clinical", "names": [ "inch of water column" ], "printSymbols": [ "in H\n 2\n O" ], "properties": [ "pressure" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[in_i'Hg]": { "isBase": false, "CODE": "[IN_I'HG]", "isMetric": "no", "class": "clinical", "names": [ "inch of mercury column" ], "printSymbols": [ "in Hg" ], "properties": [ "pressure" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[PRU]": { "isBase": false, "CODE": "[PRU]", "isMetric": "no", "class": "clinical", "names": [ "peripheral vascular resistance unit" ], "printSymbols": [ "P.R.U." ], "properties": [ "fluid resistance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[wood'U]": { "isBase": false, "CODE": "[WOOD'U]", "isMetric": "no", "class": "clinical", "names": [ "Wood unit" ], "printSymbols": [ "Wood U." ], "properties": [ "fluid resistance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[diop]": { "isBase": false, "CODE": "[DIOP]", "isMetric": "no", "class": "clinical", "names": [ "diopter" ], "printSymbols": [ "dpt" ], "properties": [ "refraction of a lens" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[p'diop]": { "isBase": false, "CODE": "[P'DIOP]", "isMetric": "no", "isSpecial": "yes", "class": "clinical", "names": [ "prism diopter" ], "printSymbols": [ "PD" ], "properties": [ "refraction of a prism" ], "values": [ { "printable": "", "numeric": null } ] }, "%[slope]": { "isBase": false, "CODE": "%[SLOPE]", "isMetric": "no", "isSpecial": "yes", "class": "clinical", "names": [ "percent of slope" ], "printSymbols": [ "%" ], "properties": [ "slope" ], "values": [ { "printable": "", "numeric": null } ] }, "[mesh_i]": { "isBase": false, "CODE": "[MESH_I]", "isMetric": "no", "class": "clinical", "names": [ "mesh" ], "properties": [ "lineic number" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[Ch]": { "isBase": false, "CODE": "[CH]", "isMetric": "no", "class": "clinical", "names": [ "Charrière", "french" ], "printSymbols": [ "Ch" ], "properties": [ "gauge of catheters" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[drp]": { "isBase": false, "CODE": "[DRP]", "isMetric": "no", "class": "clinical", "names": [ "drop" ], "printSymbols": [ "drp" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[hnsf'U]": { "isBase": false, "CODE": "[HNSF'U]", "isMetric": "no", "class": "clinical", "names": [ "Hounsfield unit" ], "printSymbols": [ "HF" ], "properties": [ "x-ray attenuation" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[MET]": { "isBase": false, "CODE": "[MET]", "isMetric": "no", "class": "clinical", "names": [ "metabolic equivalent" ], "printSymbols": [ "MET" ], "properties": [ "metabolic cost of physical activity" ], "values": [ { "printable": "3.5", "numeric": 3.5 } ] }, "[hp'_X]": { "isBase": false, "CODE": "[HP'_X]", "isMetric": "no", "isSpecial": "yes", "class": "clinical", "names": [ "homeopathic potency of decimal series (retired)" ], "printSymbols": [ "X" ], "properties": [ "homeopathic potency (retired)" ], "values": [ { "printable": "", "numeric": null } ] }, "[hp'_C]": { "isBase": false, "CODE": "[HP'_C]", "isMetric": "no", "isSpecial": "yes", "class": "clinical", "names": [ "homeopathic potency of centesimal series (retired)" ], "printSymbols": [ "C" ], "properties": [ "homeopathic potency (retired)" ], "values": [ { "printable": "", "numeric": null } ] }, "[hp'_M]": { "isBase": false, "CODE": "[HP'_M]", "isMetric": "no", "isSpecial": "yes", "class": "clinical", "names": [ "homeopathic potency of millesimal series (retired)" ], "printSymbols": [ "M" ], "properties": [ "homeopathic potency (retired)" ], "values": [ { "printable": "", "numeric": null } ] }, "[hp'_Q]": { "isBase": false, "CODE": "[HP'_Q]", "isMetric": "no", "isSpecial": "yes", "class": "clinical", "names": [ "homeopathic potency of quintamillesimal series (retired)" ], "printSymbols": [ "Q" ], "properties": [ "homeopathic potency (retired)" ], "values": [ { "printable": "", "numeric": null } ] }, "[hp_X]": { "isBase": false, "CODE": "[HP_X]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of decimal hahnemannian series" ], "printSymbols": [ "X" ], "properties": [ "homeopathic potency (Hahnemann)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[hp_C]": { "isBase": false, "CODE": "[HP_C]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of centesimal hahnemannian series" ], "printSymbols": [ "C" ], "properties": [ "homeopathic potency (Hahnemann)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[hp_M]": { "isBase": false, "CODE": "[HP_M]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of millesimal hahnemannian series" ], "printSymbols": [ "M" ], "properties": [ "homeopathic potency (Hahnemann)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[hp_Q]": { "isBase": false, "CODE": "[HP_Q]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of quintamillesimal hahnemannian series" ], "printSymbols": [ "Q" ], "properties": [ "homeopathic potency (Hahnemann)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[kp_X]": { "isBase": false, "CODE": "[KP_X]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of decimal korsakovian series" ], "printSymbols": [ "X" ], "properties": [ "homeopathic potency (Korsakov)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[kp_C]": { "isBase": false, "CODE": "[KP_C]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of centesimal korsakovian series" ], "printSymbols": [ "C" ], "properties": [ "homeopathic potency (Korsakov)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[kp_M]": { "isBase": false, "CODE": "[KP_M]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of millesimal korsakovian series" ], "printSymbols": [ "M" ], "properties": [ "homeopathic potency (Korsakov)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[kp_Q]": { "isBase": false, "CODE": "[KP_Q]", "isMetric": "no", "isArbitrary": "yes", "class": "clinical", "names": [ "homeopathic potency of quintamillesimal korsakovian series" ], "printSymbols": [ "Q" ], "properties": [ "homeopathic potency (Korsakov)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "eq": { "isBase": false, "CODE": "EQ", "isMetric": "yes", "class": "chemical", "names": [ "equivalents" ], "printSymbols": [ "eq" ], "properties": [ "amount of substance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "osm": { "isBase": false, "CODE": "OSM", "isMetric": "yes", "class": "chemical", "names": [ "osmole" ], "printSymbols": [ "osm" ], "properties": [ "amount of substance (dissolved particles)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[pH]": { "isBase": false, "CODE": "[PH]", "isMetric": "no", "isSpecial": "yes", "class": "chemical", "names": [ "pH" ], "printSymbols": [ "pH" ], "properties": [ "acidity" ], "values": [ { "printable": "", "numeric": null } ] }, "g%": { "isBase": false, "CODE": "G%", "isMetric": "yes", "class": "chemical", "names": [ "gram percent" ], "printSymbols": [ "g%" ], "properties": [ "mass concentration" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[S]": { "isBase": false, "CODE": "[S]", "isMetric": "no", "class": "chemical", "names": [ "Svedberg unit" ], "printSymbols": [ "S" ], "properties": [ "sedimentation coefficient" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[HPF]": { "isBase": false, "CODE": "[HPF]", "isMetric": "no", "class": "chemical", "names": [ "high power field" ], "printSymbols": [ "HPF" ], "properties": [ "view area in microscope" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[LPF]": { "isBase": false, "CODE": "[LPF]", "isMetric": "no", "class": "chemical", "names": [ "low power field" ], "printSymbols": [ "LPF" ], "properties": [ "view area in microscope" ], "values": [ { "printable": "100", "numeric": 100 } ] }, "kat": { "isBase": false, "CODE": "KAT", "isMetric": "yes", "class": "chemical", "names": [ "katal" ], "printSymbols": [ "kat" ], "properties": [ "catalytic activity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "U": { "isBase": false, "CODE": "U", "isMetric": "yes", "class": "chemical", "names": [ "Unit" ], "printSymbols": [ "U" ], "properties": [ "catalytic activity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[iU]": { "isBase": false, "CODE": "[IU]", "isMetric": "yes", "isArbitrary": "yes", "class": "chemical", "names": [ "international unit" ], "printSymbols": [ "IU" ], "properties": [ "arbitrary" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[IU]": { "isBase": false, "CODE": "[IU]", "isMetric": "yes", "isArbitrary": "yes", "class": "chemical", "names": [ "international unit" ], "printSymbols": [ "i.U." ], "properties": [ "arbitrary" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[arb'U]": { "isBase": false, "CODE": "[ARB'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "arbitary unit" ], "printSymbols": [ "arb. U" ], "properties": [ "arbitrary" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[USP'U]": { "isBase": false, "CODE": "[USP'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "United States Pharmacopeia unit" ], "printSymbols": [ "U.S.P." ], "properties": [ "arbitrary" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[GPL'U]": { "isBase": false, "CODE": "[GPL'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "GPL unit" ], "properties": [ "biologic activity of anticardiolipin IgG" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[MPL'U]": { "isBase": false, "CODE": "[MPL'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "MPL unit" ], "properties": [ "biologic activity of anticardiolipin IgM" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[APL'U]": { "isBase": false, "CODE": "[APL'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "APL unit" ], "properties": [ "biologic activity of anticardiolipin IgA" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[beth'U]": { "isBase": false, "CODE": "[BETH'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Bethesda unit" ], "properties": [ "biologic activity of factor VIII inhibitor" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[anti'Xa'U]": { "isBase": false, "CODE": "[ANTI'XA'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "anti factor Xa unit" ], "properties": [ "biologic activity of factor Xa inhibitor (heparin)" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[todd'U]": { "isBase": false, "CODE": "[TODD'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Todd unit" ], "properties": [ "biologic activity antistreptolysin O" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[dye'U]": { "isBase": false, "CODE": "[DYE'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Dye unit" ], "properties": [ "biologic activity of amylase" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[smgy'U]": { "isBase": false, "CODE": "[SMGY'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Somogyi unit" ], "properties": [ "biologic activity of amylase" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[bdsk'U]": { "isBase": false, "CODE": "[BDSK'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Bodansky unit" ], "properties": [ "biologic activity of phosphatase" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[ka'U]": { "isBase": false, "CODE": "[KA'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "King-Armstrong unit" ], "properties": [ "biologic activity of phosphatase" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[knk'U]": { "isBase": false, "CODE": "[KNK'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Kunkel unit" ], "properties": [ "arbitrary biologic activity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[mclg'U]": { "isBase": false, "CODE": "[MCLG'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Mac Lagan unit" ], "properties": [ "arbitrary biologic activity" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[tb'U]": { "isBase": false, "CODE": "[TB'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "tuberculin unit" ], "properties": [ "biologic activity of tuberculin" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[CCID_50]": { "isBase": false, "CODE": "[CCID_50]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "50% cell culture infectious dose" ], "printSymbols": [ "CCID50" ], "properties": [ "biologic activity (infectivity) of an infectious agent preparation" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[TCID_50]": { "isBase": false, "CODE": "[TCID_50]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "50% tissue culture infectious dose" ], "printSymbols": [ "TCID50" ], "properties": [ "biologic activity (infectivity) of an infectious agent preparation" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[EID_50]": { "isBase": false, "CODE": "[EID_50]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "50% embryo infectious dose" ], "printSymbols": [ "EID50" ], "properties": [ "biologic activity (infectivity) of an infectious agent preparation" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[PFU]": { "isBase": false, "CODE": "[PFU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "plaque forming units" ], "printSymbols": [ "PFU" ], "properties": [ "amount of an infectious agent" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[FFU]": { "isBase": false, "CODE": "[FFU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "focus forming units" ], "printSymbols": [ "FFU" ], "properties": [ "amount of an infectious agent" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[CFU]": { "isBase": false, "CODE": "[CFU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "colony forming units" ], "printSymbols": [ "CFU" ], "properties": [ "amount of a proliferating organism" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[BAU]": { "isBase": false, "CODE": "[BAU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "bioequivalent allergen unit" ], "printSymbols": [ "BAU" ], "properties": [ "amount of an allergen callibrated through in-vivo testing based on the ID50EAL method of (intradermal dilution for 50mm sum of erythema diameters" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[AU]": { "isBase": false, "CODE": "[AU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "allergen unit" ], "printSymbols": [ "AU" ], "properties": [ "procedure defined amount of an allergen using some reference standard" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[Amb'a'1'U]": { "isBase": false, "CODE": "[AMB'A'1'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "allergen unit for Ambrosia artemisiifolia" ], "printSymbols": [ "Amb a 1 U" ], "properties": [ "procedure defined amount of the major allergen of ragweed." ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[PNU]": { "isBase": false, "CODE": "[PNU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "protein nitrogen unit" ], "printSymbols": [ "PNU" ], "properties": [ "procedure defined amount of a protein substance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[Lf]": { "isBase": false, "CODE": "[LF]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Limit of flocculation" ], "printSymbols": [ "Lf" ], "properties": [ "procedure defined amount of an antigen substance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[D'ag'U]": { "isBase": false, "CODE": "[D'AG'U]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "D-antigen unit" ], "printSymbols": [ "" ], "properties": [ "procedure defined amount of a poliomyelitis d-antigen substance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[FEU]": { "isBase": false, "CODE": "[FEU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "fibrinogen equivalent unit" ], "printSymbols": [ "" ], "properties": [ "amount of fibrinogen broken down into the measured d-dimers" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[ELU]": { "isBase": false, "CODE": "[ELU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "ELISA unit" ], "printSymbols": [ "" ], "properties": [ "arbitrary ELISA unit" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[EU]": { "isBase": false, "CODE": "[EU]", "isMetric": "no", "isArbitrary": "yes", "class": "chemical", "names": [ "Ehrlich unit" ], "printSymbols": [ "" ], "properties": [ "Ehrlich unit" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Np": { "isBase": false, "CODE": "NEP", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "neper" ], "printSymbols": [ "Np" ], "properties": [ "level" ], "values": [ { "printable": "", "numeric": null } ] }, "B": { "isBase": false, "CODE": "B", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel" ], "printSymbols": [ "B" ], "properties": [ "level" ], "values": [ { "printable": "", "numeric": null } ] }, "B[SPL]": { "isBase": false, "CODE": "B[SPL]", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel sound pressure" ], "printSymbols": [ "B(SPL)" ], "properties": [ "pressure level" ], "values": [ { "printable": "", "numeric": null } ] }, "B[V]": { "isBase": false, "CODE": "B[V]", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel volt" ], "printSymbols": [ "B(V)" ], "properties": [ "electric potential level" ], "values": [ { "printable": "", "numeric": null } ] }, "B[mV]": { "isBase": false, "CODE": "B[MV]", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel millivolt" ], "printSymbols": [ "B(mV)" ], "properties": [ "electric potential level" ], "values": [ { "printable": "", "numeric": null } ] }, "B[uV]": { "isBase": false, "CODE": "B[UV]", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel microvolt" ], "printSymbols": [ "B(μV)" ], "properties": [ "electric potential level" ], "values": [ { "printable": "", "numeric": null } ] }, "B[10.nV]": { "isBase": false, "CODE": "B[10.NV]", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel 10 nanovolt" ], "printSymbols": [ "B(10 nV)" ], "properties": [ "electric potential level" ], "values": [ { "printable": "", "numeric": null } ] }, "B[W]": { "isBase": false, "CODE": "B[W]", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel watt" ], "printSymbols": [ "B(W)" ], "properties": [ "power level" ], "values": [ { "printable": "", "numeric": null } ] }, "B[kW]": { "isBase": false, "CODE": "B[KW]", "isMetric": "yes", "isSpecial": "yes", "class": "levels", "names": [ "bel kilowatt" ], "printSymbols": [ "B(kW)" ], "properties": [ "power level" ], "values": [ { "printable": "", "numeric": null } ] }, "st": { "isBase": false, "CODE": "STR", "isMetric": "yes", "class": "misc", "names": [ "stere" ], "printSymbols": [ "st" ], "properties": [ "volume" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "Ao": { "isBase": false, "CODE": "AO", "isMetric": "no", "class": "misc", "names": [ "Ångström" ], "printSymbols": [ "Å" ], "properties": [ "length" ], "values": [ { "printable": "0.1", "numeric": 0.1 } ] }, "b": { "isBase": false, "CODE": "BRN", "isMetric": "no", "class": "misc", "names": [ "barn" ], "printSymbols": [ "b" ], "properties": [ "action area" ], "values": [ { "printable": "100", "numeric": 100 } ] }, "att": { "isBase": false, "CODE": "ATT", "isMetric": "no", "class": "misc", "names": [ "technical atmosphere" ], "printSymbols": [ "at" ], "properties": [ "pressure" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "mho": { "isBase": false, "CODE": "MHO", "isMetric": "yes", "class": "misc", "names": [ "mho" ], "printSymbols": [ "mho" ], "properties": [ "electric conductance" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[psi]": { "isBase": false, "CODE": "[PSI]", "isMetric": "no", "class": "misc", "names": [ "pound per sqare inch" ], "printSymbols": [ "psi" ], "properties": [ "pressure" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "circ": { "isBase": false, "CODE": "CIRC", "isMetric": "no", "class": "misc", "names": [ "circle" ], "printSymbols": [ "circ" ], "properties": [ "plane angle" ], "values": [ { "printable": "2", "numeric": 2 } ] }, "sph": { "isBase": false, "CODE": "SPH", "isMetric": "no", "class": "misc", "names": [ "spere" ], "printSymbols": [ "sph" ], "properties": [ "solid angle" ], "values": [ { "printable": "4", "numeric": 4 } ] }, "[car_m]": { "isBase": false, "CODE": "[CAR_M]", "isMetric": "no", "class": "misc", "names": [ "metric carat" ], "printSymbols": [ "ctm" ], "properties": [ "mass" ], "values": [ { "printable": "0.2", "numeric": 0.2 } ] }, "[car_Au]": { "isBase": false, "CODE": "[CAR_AU]", "isMetric": "no", "class": "misc", "names": [ "carat of gold alloys" ], "printSymbols": [ "ct\n Au\n " ], "properties": [ "mass fraction" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "[smoot]": { "isBase": false, "CODE": "[SMOOT]", "isMetric": "no", "class": "misc", "names": [ "Smoot" ], "printSymbols": [ "" ], "properties": [ "length" ], "values": [ { "printable": "67", "numeric": 67 } ] }, "bit_s": { "isBase": false, "CODE": "BIT_S", "isMetric": "no", "isSpecial": "yes", "class": "infotech", "names": [ "bit" ], "printSymbols": [ "bits" ], "properties": [ "amount of information" ], "values": [ { "printable": "", "numeric": null } ] }, "bit": { "isBase": false, "CODE": "BIT", "isMetric": "yes", "class": "infotech", "names": [ "bit" ], "printSymbols": [ "bit" ], "properties": [ "amount of information" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "By": { "isBase": false, "CODE": "BY", "isMetric": "yes", "class": "infotech", "names": [ "byte" ], "printSymbols": [ "B" ], "properties": [ "amount of information" ], "values": [ { "printable": "8", "numeric": 8 } ] }, "Bd": { "isBase": false, "CODE": "BD", "isMetric": "yes", "class": "infotech", "names": [ "baud" ], "printSymbols": [ "Bd" ], "properties": [ "signal transmission rate" ], "values": [ { "printable": "1", "numeric": 1 } ] }, "m": { "isBase": true, "CODE": "M", "dim": "L", "names": [ "meter" ], "printSymbols": [ "m" ], "properties": [ "length" ] }, "s": { "isBase": true, "CODE": "S", "dim": "T", "names": [ "second" ], "printSymbols": [ "s" ], "properties": [ "time" ] }, "g": { "isBase": true, "CODE": "G", "dim": "M", "names": [ "gram" ], "printSymbols": [ "g" ], "properties": [ "mass" ] }, "rad": { "isBase": true, "CODE": "RAD", "dim": "A", "names": [ "radian" ], "printSymbols": [ "rad" ], "properties": [ "plane angle" ] }, "K": { "isBase": true, "CODE": "K", "dim": "C", "names": [ "Kelvin" ], "printSymbols": [ "K" ], "properties": [ "temperature" ] }, "C": { "isBase": true, "CODE": "C", "dim": "Q", "names": [ "Coulomb" ], "printSymbols": [ "C" ], "properties": [ "electric charge" ] }, "cd": { "isBase": true, "CODE": "CD", "dim": "F", "names": [ "candela" ], "printSymbols": [ "cd" ], "properties": [ "luminous intensity" ] } } },{}],410:[function(require,module,exports){ module.exports = { multiply: function multiply(t, ms) { //console.log("Multiply: ", JSON.stringify(t), JSON.stringify(ms)); if (ms.length == 0) return t; var ret = t; ms.forEach(function(mterm){ var sign = (mterm[0] == "." ? 1 : -1); var b = mterm[1]; ret.value *= Math.pow(b.value, sign); //console.log("b = ", JSON.stringify(b)); //console.log("ret = ", JSON.stringify(ret)); Object.keys(b.units).forEach(function(u){ ret.units[u] = ret.units[u] || 0; ret.units[u] = ret.units[u] + sign*b.units[u]; if(!ret.metadata && b.metadata){ ret.metadata = {}; ret.metadata[u] = b.metadata[u]; } else if(ret.metadata && b.metadata){ ret.metadata[u] = b.metadata[u]; } if (ret.units[u] == 0){ delete ret.units[u]; if(ret.metadata) { delete ret.metadata[u]; } } }); }); //console.log("Multiply ret: ", ret); return ret; }, topower: function topower(e, exp){ if (!exp) {exp = 1;} var ret = e; ret.value = Math.pow(ret.value, exp); Object.keys(e.units).forEach(function(u){ ret.units[u] = e.units[u] * exp; }); return ret; }, cleanup: function cleanup(e) { ["10^", "10*"].forEach(function(k){ if (e.units[k]) { e.value *= Math.pow(10, e.units[k]); delete e.units[k]; } }); return e; }, ismetric: function(metrics) { return function(u) { return metrics[Object.keys(u.units)[0]] !== undefined; }; } } },{}],411:[function(require,module,exports){ parser = require('./generated/ucum-parser.js'); equivalents = require('./generated/equivalents.json'); helpers = require('./lib/helpers.js'); unitMetadata = require('./generated/unitMetadata.json'); module.exports = { parse: parse, canonicalize: canonicalize, convert: convert, format: format, unitQuery: unitQuery }; function parse(value, units){ if (arguments.length === 1 || units === undefined){ units = value; value = 1 } if (units.match(/^\//)){ units = '1'+units; } if (units === '') units = '1'; var ret = parser.parse(units); ret.value *= value; return ret; } function nonBaseUnit(u){ return equivalents[u] !== undefined; } function remainingNonBaseUnits(value) { return Object.keys(value.units).filter(nonBaseUnit) } function canonicalize(value, units){ value = parse(value, units); var remaining = remainingNonBaseUnits(value); while (remaining.length) { if (remaining.length === 0) { return false; } remaining.forEach(function(u){ var sub = parse(equivalents[u].ucum); sub.value *= equivalents[u].value; sub = helpers.topower(sub, value.units[u]); value = helpers.multiply(value, [['.', sub]]); delete value.units[u]; }); remaining = remainingNonBaseUnits(value); } // we should remove any prefix metadata that exists at this point // because it represents residual artifacts of the above process if(value.metadata){ Object.keys(value.metadata).forEach(function(u){ if(value.metadata[u]){ if(value.metadata[u].prefix) { delete value.metadata[u].prefix; } // if it's not in the final array of units we should delete this metadata as well if(Object.keys(value.units).indexOf(u) == -1){ delete value.metadata[u]; } } }); } return value; } function conformant(a, b){ var ret = true; Object.keys(a.units) .concat(Object.keys(b.units)) .forEach(function(k){ if (a.units[k] !== b.units[k]) { ret = false; } }); return ret; } function convert(fromValue, fromUnits, toUnits){ fromc = canonicalize(fromValue, fromUnits); toc = canonicalize(toUnits); if (!conformant(fromc, toc)){ throw "Non-conformant units; can't convert from " + fromUnits + " to " + toUnits ; } return fromc.value / toc.value; } // format returns a printable representation of the value // the resulting units are a single-line html rendering of the resultant units // can be invoked in the following supported ways, by example: // 1. ucum.format('[in_i]') -> 'in' // 2. ucum.format('[in_i]', true) -> '1 in' // 3. ucum.format(3, '[in_i]', true) -> '3 in' // 4. var x = ucum.parse(3, '[in_i]'); ucum.format(x) -> 'in' // 5. var x = ucum.parse(3, '[in_i]'); ucum.format(x, true) -> '3 in' function format(value, units, includeValue){ var obj; if(typeof value === 'string'){ includeValue = units; units = value; value = 1; } if(typeof value === 'object'){ // treat it like a UCUM parse output obj = value; includeValue = units; // you would never provide units in this case, but you might provide includeValue } else{ // parse it first obj = parse(value, units); } var units = Object.keys(obj.units); var metadata = obj.metadata; var numUnits = units.length; var numeratorUnits = []; var denominatorUnits = []; var printableUnits = ""; units.forEach(function(unit, index){ var exponent = obj.units[unit]; var absExponent = Math.abs(exponent); var printable = metadata[unit].printSymbols ? metadata[unit].printSymbols[0] : metadata[unit].names[0]; var prefix = metadata[unit].prefix ? metadata[unit].prefix.printSymbols[0] : ""; pUnit = prefix + printable; if(absExponent !== 1){ pUnit += ""; pUnit += Math.abs(exponent); pUnit += ""; } if(exponent > 0){ numeratorUnits.push(pUnit); } else{ denominatorUnits.push(pUnit); } }); if(numeratorUnits.length == 0){ printableUnits = "1"; } else if(numeratorUnits.length > 0){ printableUnits = numeratorUnits.join("*"); } if(denominatorUnits.length > 0){ printableUnits += "/"; } printableUnits += denominatorUnits.join("/"); if(includeValue){ printableUnits = obj.value + " " + printableUnits; } return printableUnits; } // searches the unit metadata for all unit metadata // criteria is an object like // { properties: 'area', isMetric: 'yes' } // where the key/value pairs form a logical intersection, i.e. all criteria must be met // resultFields is an array to pre-reduce the result set fields function unitQuery(criteria, resultFields){ return Object.keys(unitMetadata).filter((unit) => { var keys = Object.keys(criteria); for(var ii = 0; ii < keys.length; ii++){ var key = keys[ii]; var val = unitMetadata[unit][key]; var value = criteria[key]; if(val && (typeof val === 'object')){ // it's a list of values, it's a match if the target value occurs in the list if(val.indexOf(value) === -1){ return false; } } else{ // it's a non-object, make a direct comparison if(unitMetadata[unit][key] !== value){ return false; } } } return true; }).map((key) => { var obj = {}; if(resultFields){ if(resultFields.length) { obj[key] = {}; resultFields.forEach((field) => { if (unitMetadata[key][field] !== undefined) { obj[key][field] = JSON.parse(JSON.stringify(unitMetadata[key][field])); } }); } else{ // just return the keys if an empty array gets passed for resultSet obj = key; } } else{ obj[key] = JSON.parse(JSON.stringify(unitMetadata[key])); } return obj; }); } },{"./generated/equivalents.json":404,"./generated/ucum-parser.js":408,"./generated/unitMetadata.json":409,"./lib/helpers.js":410}],412:[function(require,module,exports){ arguments[4][90][0].apply(exports,arguments) },{"dup":90}],413:[function(require,module,exports){ arguments[4][91][0].apply(exports,arguments) },{"dup":91}],414:[function(require,module,exports){ arguments[4][92][0].apply(exports,arguments) },{"./support/isBuffer":413,"_process":399,"dup":92,"inherits":412}]},{},[75]);