(function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o ['STRAT', 'IPP', 'DENOM', 'DENEX', 'NUMER', 'NUMEX', 'DENEXCEP', 'MSRPOPL', 'OBSERV', 'MSRPOPLEX']); MeasureSchema.virtual('cqlSkipStatements').get(() => ['SDE Ethnicity', 'SDE Payer', 'SDE Race', 'SDE Sex']); module.exports.MeasureSchema = MeasureSchema; module.exports.Measure = mongoose.model('measure', MeasureSchema); },{"./basetypes/Code":68,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],34:[function(require,module,exports){ const mongoose = require('mongoose'); const [mBuffer, ObjectId] = [ mongoose.Schema.Types.Buffer, mongoose.Schema.Types.ObjectId, ]; const MeasurePackageSchema = mongoose.Schema( { file: mBuffer, measure: { type: ObjectId, ref: 'Measure' }, }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, } ); module.exports.MeasurePackageSchema = MeasurePackageSchema; module.exports.MeasurePackage = mongoose.model('measure_package', MeasurePackageSchema); },{"mongoose":401}],35:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const MedicationActiveSchema = DataElementSchema({ relevantPeriod: Interval, dosage: Quantity, supply: Quantity, frequency: Code, route: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.44' }, category: { type: String, default: 'medication' }, qdmStatus: { type: String, default: 'active' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'MedicationActive' }, }); module.exports.MedicationActiveSchema = MedicationActiveSchema; module.exports.MedicationActive = mongoose.model('MedicationActive', MedicationActiveSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],36:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const MedicationAdministeredSchema = DataElementSchema({ authorDatetime: DateTime, relevantPeriod: Interval, dosage: Quantity, supply: Quantity, frequency: Code, route: Code, reason: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.45' }, category: { type: String, default: 'medication' }, qdmStatus: { type: String, default: 'administered' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'MedicationAdministered' }, }); module.exports.MedicationAdministeredSchema = MedicationAdministeredSchema; module.exports.MedicationAdministered = mongoose.model('MedicationAdministered', MedicationAdministeredSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],37:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const MedicationDischargeSchema = DataElementSchema({ authorDatetime: DateTime, refills: Number, dosage: Quantity, supply: Quantity, frequency: Code, route: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.48' }, category: { type: String, default: 'medication' }, qdmStatus: { type: String, default: 'discharge' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'MedicationDischarge' }, }); module.exports.MedicationDischargeSchema = MedicationDischargeSchema; module.exports.MedicationDischarge = mongoose.model('MedicationDischarge', MedicationDischargeSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],38:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const MedicationDispensedSchema = DataElementSchema({ authorDatetime: DateTime, relevantPeriod: Interval, refills: Number, dosage: Quantity, supply: Quantity, frequency: Code, route: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.49' }, category: { type: String, default: 'medication' }, qdmStatus: { type: String, default: 'dispensed' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'MedicationDispensed' }, }); module.exports.MedicationDispensedSchema = MedicationDispensedSchema; module.exports.MedicationDispensed = mongoose.model('MedicationDispensed', MedicationDispensedSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],39:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const MedicationOrderSchema = DataElementSchema({ activeDatetime: DateTime, relevantPeriod: Interval, authorDatetime: DateTime, refills: Number, dosage: Quantity, supply: Quantity, frequency: Code, route: Code, method: Code, reason: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.51' }, category: { type: String, default: 'medication' }, qdmStatus: { type: String, default: 'order' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'MedicationOrder' }, }); module.exports.MedicationOrderSchema = MedicationOrderSchema; module.exports.MedicationOrder = mongoose.model('MedicationOrder', MedicationOrderSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],40:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ParticipationSchema = DataElementSchema({ participationPeriod: Interval, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.4.130' }, category: { type: String, default: 'participation' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'Participation' }, }); module.exports.ParticipationSchema = ParticipationSchema; module.exports.Participation = mongoose.model('Participation', ParticipationSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],41:[function(require,module,exports){ const mongoose = require('mongoose'); const Code = require('./basetypes/Code'); const Interval = require('./basetypes/Interval'); const Quantity = require('./basetypes/Quantity'); const DateTime = require('./basetypes/DateTime'); const AllDataElements = require('./AllDataElements'); const [Schema, Number, String] = [ mongoose.Schema, mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientSchema = new Schema({ birthDatetime: DateTime, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'Patient' }, givenNames: [String], familyName: String, bundleId: String, // These are the "data criteria", or QDM datatype elements that exist on a // patient. dataElements: [], // This field is for application specific information only. If both Bonnie // Cypress use a common field, it should be made a field on this model, // and not put into extendedData. extendedData: {}, }, { id: false }); // After initialization of a Patient model, initialize every individual data element // to its respective Mongoose Model PatientSchema.methods.initializeDataElements = function initializeDataElements() { let typeStripped; const dataElementsInit = []; this.dataElements.forEach((element) => { typeStripped = element._type.replace(/QDM::/, ''); if (typeStripped in AllDataElements) { dataElementsInit.push(AllDataElements[typeStripped](element)); } else { dataElementsInit.push(element); } }); this.set({ dataElements: dataElementsInit }); }; PatientSchema.queue('initializeDataElements'); PatientSchema.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. PatientSchema.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. PatientSchema.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 category, which returns all elements of that QDM category. // Example: patient.getDataElements(category = 'encounters') will return // all Encounter QDM data types active on the patient. PatientSchema.methods.getDataElements = function getDataElements(params) { if (params.category && params.qdmStatus) { return this.dataElements.filter(element => (element.category === params.category) && (element.qdmStatus === params.qdmStatus)); } else if (params.category) { return this.dataElements.filter(element => element.category === params.category); } return this.dataElements; }; // Returns an array of dataElements that exist on the patient, queried by // QDM profile PatientSchema.methods.getByProfile = function getByProfile(profile, isNegated = null) { if (isNegated === true) { return this.dataElements.filter(element => element._type === `QDM::${profile}` && (typeof element.negationRationale !== 'undefined' && element.negationRationale != null)); } else if (isNegated === false) { return this.dataElements.filter(element => element._type === `QDM::${profile}` && (typeof element.negationRationale === 'undefined' || element.negationRationale == null)); } return this.dataElements.filter(element => element._type === `QDM::${profile}`); }; // 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's patient builder). // @param {String} profile - the data criteria requested by the execution engine // @returns {Object} PatientSchema.methods.findRecords = function findRecords(profile) { let profileStripped; if (profile === 'Patient') { // Requested generic patient info return { birthDatetime: this.birthDatetime }; } else if (/PatientCharacteristic/.test(profile)) { // Requested a patient characteristic profileStripped = profile.replace(/ *\{[^)]*\} */g, ''); return this.getByProfile(profileStripped); } 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 don't 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. return this.getByProfile(profileStripped, false); } else if (/Negative/.test(profileStripped)) { profileStripped = profileStripped.replace(/Negative/, ''); // Since the data criteria is 'Negative', it is negated. return this.getByProfile(profileStripped, true); } // No negation status, proceed normally return this.getByProfile(profileStripped); } return []; }; PatientSchema.methods.adverse_events = function adverse_events() { return this.getDataElements({ category: 'adverse_event' }); }; PatientSchema.methods.allergies = function allergies() { return this.getDataElements({ category: 'allergy' }); }; PatientSchema.methods.assessments = function assessments() { return this.getDataElements({ category: 'assessment' }); }; PatientSchema.methods.care_experiences = function care_experiences() { return this.getDataElements({ category: 'care_experience' }); }; PatientSchema.methods.care_goals = function care_goals() { return this.getDataElements({ category: 'care_goal' }); }; PatientSchema.methods.communications = function communications() { return this.getDataElements({ category: 'communication' }); }; PatientSchema.methods.conditions = function conditions() { return this.getDataElements({ category: 'condition' }); }; PatientSchema.methods.devices = function devices() { return this.getDataElements({ category: 'device' }); }; PatientSchema.methods.diagnostic_studies = function diagnostic_studies() { return this.getDataElements({ category: 'diagnostic_study' }); }; PatientSchema.methods.encounters = function encounters() { return this.getDataElements({ category: 'encounter' }); }; PatientSchema.methods.family_history = function family_history() { return this.getDataElements({ category: 'family_history' }); }; PatientSchema.methods.functional_statuses = function functional_statuses() { return this.getDataElements({ category: 'functional_status' }); }; PatientSchema.methods.immunizations = function immunizations() { return this.getDataElements({ category: 'immunization' }); }; PatientSchema.methods.interventions = function interventions() { return this.getDataElements({ category: 'intervention' }); }; PatientSchema.methods.laboratory_tests = function laboratory_tests() { return this.getDataElements({ category: 'laboratory_test' }); }; PatientSchema.methods.medical_equipment = function medical_equipment() { return this.getDataElements({ category: 'medical_equipment' }); }; PatientSchema.methods.medications = function medications() { return this.getDataElements({ category: 'medication' }); }; PatientSchema.methods.physical_exams = function physical_exams() { return this.getDataElements({ category: 'physical_exam' }); }; PatientSchema.methods.preferences = function preferences() { return this.getDataElements({ category: 'preference' }); }; PatientSchema.methods.provider_characteristics = function provider_characteristics() { return this.getDataElements({ category: 'provider_characteristic' }); }; PatientSchema.methods.procedures = function procedures() { return this.getDataElements({ category: 'procedure' }); }; PatientSchema.methods.results = function results() { return this.getDataElements({ category: 'result' }); }; PatientSchema.methods.risk_category_assessments = function risk_category_assessments() { return this.getDataElements({ category: 'risk_category_assessment' }); }; PatientSchema.methods.social_history = function social_history() { return this.getDataElements({ category: 'social_history' }); }; PatientSchema.methods.substances = function substances() { return this.getDataElements({ category: 'substance' }); }; PatientSchema.methods.symptoms = function symptoms() { return this.getDataElements({ category: 'symptom' }); }; PatientSchema.methods.system_characteristics = function system_characteristics() { return this.getDataElements({ category: 'system_characteristic' }); }; PatientSchema.methods.transfers = function transfers() { return this.getDataElements({ category: 'transfer' }); }; PatientSchema.methods.vital_signs = function vital_signs() { return this.getDataElements({ category: 'vital_sign' }); }; module.exports.PatientSchema = PatientSchema; module.exports.Patient = mongoose.model('Patient', PatientSchema); },{"./AllDataElements":2,"./basetypes/Code":68,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],42:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCareExperienceSchema = DataElementSchema({ authorDatetime: DateTime, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.52' }, category: { type: String, default: 'care_experience' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCareExperience' }, }); module.exports.PatientCareExperienceSchema = PatientCareExperienceSchema; module.exports.PatientCareExperience = mongoose.model('PatientCareExperience', PatientCareExperienceSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],43:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicSchema = DataElementSchema({ authorDatetime: DateTime, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.53' }, category: { type: String, default: 'patient_characteristic' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristic' }, }); module.exports.PatientCharacteristicSchema = PatientCharacteristicSchema; module.exports.PatientCharacteristic = mongoose.model('PatientCharacteristic', PatientCharacteristicSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],44:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicBirthdateSchema = DataElementSchema({ birthDatetime: DateTime, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.54' }, category: { type: String, default: 'patient_characteristic' }, qdmStatus: { type: String, default: 'birthdate' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristicBirthdate' }, }); module.exports.PatientCharacteristicBirthdateSchema = PatientCharacteristicBirthdateSchema; module.exports.PatientCharacteristicBirthdate = mongoose.model('PatientCharacteristicBirthdate', PatientCharacteristicBirthdateSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],45:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicClinicalTrialParticipantSchema = DataElementSchema({ reason: Code, relevantPeriod: Interval, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.6' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.51' }, category: { type: String, default: 'patient_characteristic' }, qdmStatus: { type: String, default: 'clinical_trial_participant' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristicClinicalTrialParticipant' }, }); module.exports.PatientCharacteristicClinicalTrialParticipantSchema = PatientCharacteristicClinicalTrialParticipantSchema; module.exports.PatientCharacteristicClinicalTrialParticipant = mongoose.model('PatientCharacteristicClinicalTrialParticipant', PatientCharacteristicClinicalTrialParticipantSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],46:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicEthnicitySchema = DataElementSchema({ hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.56' }, category: { type: String, default: 'patient_characteristic' }, qdmStatus: { type: String, default: 'ethnicity' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristicEthnicity' }, }); module.exports.PatientCharacteristicEthnicitySchema = PatientCharacteristicEthnicitySchema; module.exports.PatientCharacteristicEthnicity = mongoose.model('PatientCharacteristicEthnicity', PatientCharacteristicEthnicitySchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],47:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicExpiredSchema = DataElementSchema({ expiredDatetime: DateTime, cause: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.57' }, category: { type: String, default: 'patient_characteristic' }, qdmStatus: { type: String, default: 'expired' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristicExpired' }, }); module.exports.PatientCharacteristicExpiredSchema = PatientCharacteristicExpiredSchema; module.exports.PatientCharacteristicExpired = mongoose.model('PatientCharacteristicExpired', PatientCharacteristicExpiredSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],48:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicPayerSchema = DataElementSchema({ relevantPeriod: Interval, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.58' }, category: { type: String, default: 'patient_characteristic' }, qdmStatus: { type: String, default: 'payer' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristicPayer' }, }); module.exports.PatientCharacteristicPayerSchema = PatientCharacteristicPayerSchema; module.exports.PatientCharacteristicPayer = mongoose.model('PatientCharacteristicPayer', PatientCharacteristicPayerSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],49:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicRaceSchema = DataElementSchema({ hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.59' }, category: { type: String, default: 'patient_characteristic' }, qdmStatus: { type: String, default: 'race' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristicRace' }, }); module.exports.PatientCharacteristicRaceSchema = PatientCharacteristicRaceSchema; module.exports.PatientCharacteristicRace = mongoose.model('PatientCharacteristicRace', PatientCharacteristicRaceSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],50:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PatientCharacteristicSexSchema = DataElementSchema({ hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.55' }, category: { type: String, default: 'patient_characteristic' }, qdmStatus: { type: String, default: 'gender' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PatientCharacteristicSex' }, }); module.exports.PatientCharacteristicSexSchema = PatientCharacteristicSexSchema; module.exports.PatientCharacteristicSex = mongoose.model('PatientCharacteristicSex', PatientCharacteristicSexSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],51:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PhysicalExamOrderSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, method: Code, anatomicalLocationSite: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.61' }, category: { type: String, default: 'physical_exam' }, qdmStatus: { type: String, default: 'order' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PhysicalExamOrder' }, }); module.exports.PhysicalExamOrderSchema = PhysicalExamOrderSchema; module.exports.PhysicalExamOrder = mongoose.model('PhysicalExamOrder', PhysicalExamOrderSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],52:[function(require,module,exports){ const mongoose = require('mongoose'); 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 { ComponentSchema } = require('./Component'); const Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PhysicalExamPerformedSchema = DataElementSchema({ authorDatetime: DateTime, relevantPeriod: Interval, reason: Code, method: Code, result: Any, anatomicalLocationSite: Code, negationRationale: Code, components: [ComponentSchema], hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.62' }, category: { type: String, default: 'physical_exam' }, qdmStatus: { type: String, default: 'performed' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PhysicalExamPerformed' }, }); module.exports.PhysicalExamPerformedSchema = PhysicalExamPerformedSchema; module.exports.PhysicalExamPerformed = mongoose.model('PhysicalExamPerformed', PhysicalExamPerformedSchema); },{"./Component":10,"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],53:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const PhysicalExamRecommendedSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, method: Code, anatomicalLocationSite: Code, negationRationale: Code, hqmfOid: { type: String, default: '22.16.840.1.113883.10.20.28.3.63' }, category: { type: String, default: 'physical_exam' }, qdmStatus: { type: String, default: 'recommended' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'PhysicalExamRecommended' }, }); module.exports.PhysicalExamRecommendedSchema = PhysicalExamRecommendedSchema; module.exports.PhysicalExamRecommended = mongoose.model('PhysicalExamRecommended', PhysicalExamRecommendedSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],54:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ProcedureOrderSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, method: Code, anatomicalApproachSite: Code, anatomicalLocationSite: Code, ordinality: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.66' }, category: { type: String, default: 'procedure' }, qdmStatus: { type: String, default: 'order' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'ProcedureOrder' }, }); module.exports.ProcedureOrderSchema = ProcedureOrderSchema; module.exports.ProcedureOrder = mongoose.model('ProcedureOrder', ProcedureOrderSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],55:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const { ComponentSchema } = require('./Component'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ProcedurePerformedSchema = DataElementSchema({ authorDatetime: DateTime, relevantPeriod: Interval, reason: Code, method: Code, result: Any, status: Code, anatomicalApproachSite: Code, anatomicalLocationSite: Code, ordinality: Code, incisionDatetime: DateTime, negationRationale: Code, components: [ComponentSchema], hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.67' }, category: { type: String, default: 'procedure' }, qdmStatus: { type: String, default: 'performed' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'ProcedurePerformed' }, }); module.exports.ProcedurePerformedSchema = ProcedurePerformedSchema; module.exports.ProcedurePerformed = mongoose.model('ProcedurePerformed', ProcedurePerformedSchema); },{"./Component":10,"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],56:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ProcedureRecommendedSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, method: Code, anatomicalApproachSite: Code, anatomicalLocationSite: Code, ordinality: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.68' }, category: { type: String, default: 'procedure' }, qdmStatus: { type: String, default: 'recommended' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'ProcedureRecommended' }, }); module.exports.ProcedureRecommendedSchema = ProcedureRecommendedSchema; module.exports.ProcedureRecommended = mongoose.model('ProcedureRecommended', ProcedureRecommendedSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],57:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ProviderCareExperienceSchema = DataElementSchema({ authorDatetime: DateTime, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.70' }, category: { type: String, default: 'care_experience' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'ProviderCareExperience' }, }); module.exports.ProviderCareExperienceSchema = ProviderCareExperienceSchema; module.exports.ProviderCareExperience = mongoose.model('ProviderCareExperience', ProviderCareExperienceSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],58:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ProviderCharacteristicSchema = DataElementSchema({ authorDatetime: DateTime, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.71' }, category: { type: String, default: 'provider_characteristic' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'ProviderCharacteristic' }, }); module.exports.ProviderCharacteristicSchema = ProviderCharacteristicSchema; module.exports.ProviderCharacteristic = mongoose.model('ProviderCharacteristic', ProviderCharacteristicSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],59:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const RatioSchema = DataElementSchema({ numerator: Quantity, denominator: Quantity, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'Ratio' }, }); module.exports.RatioSchema = RatioSchema; module.exports.Ratio = mongoose.model('Ratio', RatioSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],60:[function(require,module,exports){ const mongoose = require('mongoose'); 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; module.exports.Result = mongoose.model('Result', PlaceholderResultSchema); },{"mongoose":401}],61:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const ResultComponentSchema = DataElementSchema({ referenceRange: Interval, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'ResultComponent' }, }); module.exports.ResultComponentSchema = ResultComponentSchema; module.exports.ResultComponent = mongoose.model('ResultComponent', ResultComponentSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],62:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceAdministeredSchema = DataElementSchema({ authorDatetime: DateTime, relevantPeriod: Interval, dosage: Quantity, supply: Quantity, frequency: Code, route: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.73' }, category: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'administered' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'SubstanceAdministered' }, }); module.exports.SubstanceAdministeredSchema = SubstanceAdministeredSchema; module.exports.SubstanceAdministered = mongoose.model('SubstanceAdministered', SubstanceAdministeredSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],63:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceOrderSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, dosage: Quantity, supply: Quantity, frequency: Code, method: Code, refills: Number, route: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.77' }, category: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'order' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'SubstanceOrder' }, }); module.exports.SubstanceOrderSchema = SubstanceOrderSchema; module.exports.SubstanceOrder = mongoose.model('SubstanceOrder', SubstanceOrderSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],64:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SubstanceRecommendedSchema = DataElementSchema({ authorDatetime: DateTime, reason: Code, dosage: Quantity, supply: Quantity, frequency: Code, method: Code, refills: Number, route: Code, negationRationale: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.78' }, category: { type: String, default: 'substance' }, qdmStatus: { type: String, default: 'recommended' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'SubstanceRecommended' }, }); module.exports.SubstanceRecommendedSchema = SubstanceRecommendedSchema; module.exports.SubstanceRecommended = mongoose.model('SubstanceRecommended', SubstanceRecommendedSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],65:[function(require,module,exports){ const mongoose = require('mongoose'); 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 Any = require('./basetypes/Any'); const [Number, String] = [ mongoose.Schema.Types.Number, mongoose.Schema.Types.String, ]; const SymptomSchema = DataElementSchema({ prevalencePeriod: Interval, severity: Code, hqmfOid: { type: String, default: '2.16.840.1.113883.10.20.28.3.116' }, qrdaOid: { type: String, default: '2.16.840.1.113883.10.20.24.3.136' }, category: { type: String, default: 'symptom' }, qdmVersion: { type: String, default: '5.3' }, _type: { type: String, default: 'Symptom' }, }); module.exports.SymptomSchema = SymptomSchema; module.exports.Symptom = mongoose.model('Symptom', SymptomSchema); },{"./basetypes/Any":67,"./basetypes/Code":68,"./basetypes/DataElement":69,"./basetypes/DateTime":70,"./basetypes/Interval":71,"./basetypes/Quantity":72,"mongoose":401}],66:[function(require,module,exports){ const mongoose = require('mongoose'); const Concept = require('./Concept.js'); const [mString, Mixed, ObjectId] = [ mongoose.Schema.Types.String, mongoose.Schema.Types.Mixed, mongoose.Schema.Types.ObjectId, ]; const ValueSetSchema = mongoose.Schema( { oid: mString, display_name: mString, version: mString, categories: Mixed, concepts: [Concept.ConceptSchema], user: { type: ObjectId, ref: 'User', index: true }, // Bonnie-specific bundle: { type: ObjectId, ref: 'Bundle' }, // Cypress-specific measures: [{ type: ObjectId, ref: 'Measure' }], }, // Options { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }, } ); module.exports.ValueSetSchema = ValueSetSchema; module.exports.ValueSet = mongoose.model('value_set', ValueSetSchema); },{"./Concept.js":11,"mongoose":401}],67:[function(require,module,exports){ const mongoose = require('mongoose'); 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); } 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); if (casted.high && casted.high.unit && casted.high.value) { casted.high = new cql.Quantity(casted.high); } return casted; } // Cast to DateTime if it is a string representing a DateTime if (casted.low && Date.parse(casted.low)) { casted.low = cql.DateTime.fromDate(new Date(casted.low), 0); } if (casted.high && Date.parse(casted.high)) { casted.high = cql.DateTime.fromDate(new Date(casted.high), 0); } return casted; } if (Array.isArray(any)) { const casted = []; any.forEach((val) => { casted.push(RecursiveCast(val)); }); return casted; } if (Number.isInteger(any)) { return any; } if (Date.parse(any)) { return cql.DateTime.fromDate(new Date(any), 0); } return any; } Any.prototype.cast = any => RecursiveCast(any); mongoose.Schema.Types.Any = Any; module.exports = Any; },{"cql-execution":150,"mongoose":401}],68:[function(require,module,exports){ const mongoose = require('mongoose'); function Code(key, options) { mongoose.SchemaType.call(this, key, options, 'Code'); } Code.prototype = Object.create(mongoose.SchemaType.prototype); Code.prototype.cast = (code) => { if (typeof code.code === 'undefined') { throw new Error(`Code: ${code} does not have a code`); } else if (typeof code.codeSystem === 'undefined') { throw new Error(`Code: ${code} does not have a codeSystem`); } const val = { code: code.code, codeSystem: code.codeSystem }; val.descriptor = (typeof code.descriptor !== 'undefined') ? code.descriptor : null; val.codeSystemOid = (typeof code.codeSystemOid !== 'undefined') ? code.codeSystemOid : null; val.version = (typeof code.version !== 'undefined') ? code.version : null; return val; }; mongoose.Schema.Types.Code = Code; module.exports = Code; },{"mongoose":401}],69:[function(require,module,exports){ const mongoose = require('mongoose'); const Code = require('./Code.js'); const [Schema] = [mongoose.Schema]; function DataElementSchema(add, options) { const extended = new Schema({ dataElementCodes: { type: [Code] }, description: { type: String }, }, 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() { return this.dataElementCodes.map((code) => { const result = {}; result.code = code.code; result.system = code.code_system; return result; }); }; // Returns all of the codes on this data element // in their normal form. extended.methods.codes = function getCodes() { return this.dataElementCodes; }; return extended; } module.exports.DataElementSchema = DataElementSchema; },{"./Code.js":68,"mongoose":401}],70:[function(require,module,exports){ const mongoose = require('mongoose'); 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 (!Date.parse(dateTime)) { throw new Error(`DateTime: ${dateTime} is not a valid DateTime`); } return cql.DateTime.fromDate(new Date(dateTime), 0); }; mongoose.Schema.Types.DateTime = DateTime; module.exports = DateTime; },{"cql-execution":150,"mongoose":401}],71:[function(require,module,exports){ const mongoose = require('mongoose'); const cql = require('cql-execution'); function Interval(key, options) { mongoose.SchemaType.call(this, key, options, 'Interval'); } Interval.prototype = Object.create(mongoose.SchemaType.prototype); Interval.prototype.cast = (interval) => { if (typeof interval.low === 'undefined' || interval.low === null) { throw new Error(`Interval: ${interval} does not have a low value`); } 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); if (casted.high && casted.high.unit && casted.high.value) { casted.high = new cql.Quantity(casted.high); } return casted; } // Cast to DateTime if it is a string representing a DateTime if (casted.low && Date.parse(casted.low)) { casted.low = cql.DateTime.fromDate(new Date(casted.low), 0); } if (casted.high && Date.parse(casted.high)) { casted.high = cql.DateTime.fromDate(new Date(casted.high), 0); } return casted; }; mongoose.Schema.Types.Interval = Interval; module.exports = Interval; },{"cql-execution":150,"mongoose":401}],72:[function(require,module,exports){ const mongoose = require('mongoose'); 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); }; mongoose.Schema.Types.Quantity = Quantity; module.exports = Quantity; },{"cql-execution":150,"mongoose":401}],73:[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('./Measure.js').Measure; module.exports.MeasureSchema = require('./Measure.js').MeasureSchema; module.exports.MeasurePackage = require('./MeasurePackage.js').MeasurePackage; module.exports.MeasurePackageSchema = require('./MeasurePackage.js').MeasurePackageSchema; module.exports.ValueSet = require('./ValueSet.js').ValueSet; module.exports.ValueSetSchema = require('./ValueSet.js').ValueSetSchema; module.exports.Concept = require('./Concept.js').Concept; module.exports.ConceptSchema = require('./Concept.js').ConceptSchema; },{"./AllDataElements.js":2,"./Concept.js":11,"./Measure.js":33,"./MeasurePackage.js":34,"./Result.js":60,"./ValueSet.js":66,"cql-execution":150}],74:[function(require,module,exports){ var asn1 = exports; asn1.bignum = require('bn.js'); asn1.define = require('./asn1/api').define; asn1.base = require('./asn1/base'); asn1.constants = require('./asn1/constants'); asn1.decoders = require('./asn1/decoders'); asn1.encoders = require('./asn1/encoders'); },{"./asn1/api":75,"./asn1/base":77,"./asn1/constants":81,"./asn1/decoders":83,"./asn1/encoders":86,"bn.js":91}],75:[function(require,module,exports){ var asn1 = require('../asn1'); var inherits = require('inherits'); var api = exports; api.define = function define(name, body) { return new Entity(name, body); }; function Entity(name, body) { this.name = name; this.body = body; this.decoders = {}; this.encoders = {}; }; Entity.prototype._createNamed = function createNamed(base) { var named; try { named = require('vm').runInThisContext( '(function ' + this.name + '(entity) {\n' + ' this._initNamed(entity);\n' + '})' ); } catch (e) { named = function (entity) { this._initNamed(entity); }; } inherits(named, base); named.prototype._initNamed = function initnamed(entity) { base.call(this, entity); }; return new named(this); }; Entity.prototype._getDecoder = function _getDecoder(enc) { enc = enc || 'der'; // Lazily create decoder if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(asn1.decoders[enc]); return this.decoders[enc]; }; Entity.prototype.decode = function decode(data, enc, options) { return this._getDecoder(enc).decode(data, options); }; Entity.prototype._getEncoder = function _getEncoder(enc) { enc = enc || 'der'; // Lazily create encoder if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(asn1.encoders[enc]); return this.encoders[enc]; }; Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; },{"../asn1":74,"inherits":334,"vm":564}],76:[function(require,module,exports){ var inherits = require('inherits'); var Reporter = require('../base').Reporter; var Buffer = require('buffer').Buffer; function DecoderBuffer(base, options) { Reporter.call(this, options); if (!Buffer.isBuffer(base)) { this.error('Input not Buffer'); return; } this.base = base; this.offset = 0; this.length = base.length; } inherits(DecoderBuffer, Reporter); exports.DecoderBuffer = DecoderBuffer; DecoderBuffer.prototype.save = function save() { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; DecoderBuffer.prototype.restore = function restore(save) { // Return skipped data var res = new DecoderBuffer(this.base); res.offset = save.offset; res.length = this.offset; this.offset = save.offset; Reporter.prototype.restore.call(this, save.reporter); return res; }; DecoderBuffer.prototype.isEmpty = function isEmpty() { return this.offset === this.length; }; DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true); else return this.error(fail || 'DecoderBuffer overrun'); } DecoderBuffer.prototype.skip = function skip(bytes, fail) { if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); var res = new DecoderBuffer(this.base); // Share reporter state res._reporterState = this._reporterState; res.offset = this.offset; res.length = this.offset + bytes; this.offset += bytes; return res; } DecoderBuffer.prototype.raw = function raw(save) { return this.base.slice(save ? save.offset : this.offset, this.length); } function EncoderBuffer(value, reporter) { if (Array.isArray(value)) { this.length = 0; this.value = value.map(function(item) { if (!(item instanceof EncoderBuffer)) item = new EncoderBuffer(item, reporter); this.length += item.length; return item; }, this); } else if (typeof value === 'number') { if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value'); this.value = value; this.length = 1; } else if (typeof value === 'string') { this.value = value; this.length = Buffer.byteLength(value); } else if (Buffer.isBuffer(value)) { this.value = value; this.length = value.length; } else { return reporter.error('Unsupported type: ' + typeof value); } } exports.EncoderBuffer = EncoderBuffer; EncoderBuffer.prototype.join = function join(out, offset) { if (!out) out = new Buffer(this.length); if (!offset) offset = 0; if (this.length === 0) return out; if (Array.isArray(this.value)) { this.value.forEach(function(item) { item.join(out, offset); offset += item.length; }); } else { if (typeof this.value === 'number') out[offset] = this.value; else if (typeof this.value === 'string') out.write(this.value, offset); else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset); offset += this.length; } return out; }; },{"../base":77,"buffer":144,"inherits":334}],77:[function(require,module,exports){ var base = exports; base.Reporter = require('./reporter').Reporter; base.DecoderBuffer = require('./buffer').DecoderBuffer; base.EncoderBuffer = require('./buffer').EncoderBuffer; base.Node = require('./node'); },{"./buffer":76,"./node":78,"./reporter":79}],78:[function(require,module,exports){ var Reporter = require('../base').Reporter; var EncoderBuffer = require('../base').EncoderBuffer; var DecoderBuffer = require('../base').DecoderBuffer; var assert = require('minimalistic-assert'); // Supported tags var tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ]; // Public methods list var methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags); // Overrided methods list var overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ]; function Node(enc, parent) { var state = {}; this._baseState = state; state.enc = enc; state.parent = parent || null; state.children = null; // State state.tag = null; state.args = null; state.reverseArgs = null; state.choice = null; state.optional = false; state.any = false; state.obj = false; state.use = null; state.useDecoder = null; state.key = null; state['default'] = null; state.explicit = null; state.implicit = null; state.contains = null; // Should create new instance on each method if (!state.parent) { state.children = []; this._wrap(); } } module.exports = Node; var stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ]; Node.prototype.clone = function clone() { var state = this._baseState; var cstate = {}; stateProps.forEach(function(prop) { cstate[prop] = state[prop]; }); var res = new this.constructor(cstate.parent); res._baseState = cstate; return res; }; Node.prototype._wrap = function wrap() { var state = this._baseState; methods.forEach(function(method) { this[method] = function _wrappedMethod() { var clone = new this.constructor(this); state.children.push(clone); return clone[method].apply(clone, arguments); }; }, this); }; Node.prototype._init = function init(body) { var state = this._baseState; assert(state.parent === null); body.call(this); // Filter children state.children = state.children.filter(function(child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; Node.prototype._useArgs = function useArgs(args) { var state = this._baseState; // Filter children and args var children = args.filter(function(arg) { return arg instanceof this.constructor; }, this); args = args.filter(function(arg) { return !(arg instanceof this.constructor); }, this); if (children.length !== 0) { assert(state.children === null); state.children = children; // Replace parent to maintain backward link children.forEach(function(child) { child._baseState.parent = this; }, this); } if (args.length !== 0) { assert(state.args === null); state.args = args; state.reverseArgs = args.map(function(arg) { if (typeof arg !== 'object' || arg.constructor !== Object) return arg; var res = {}; Object.keys(arg).forEach(function(key) { if (key == (key | 0)) key |= 0; var value = arg[key]; res[value] = key; }); return res; }); } }; // // Overrided methods // overrided.forEach(function(method) { Node.prototype[method] = function _overrided() { var state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); // // Public methods // tags.forEach(function(tag) { Node.prototype[tag] = function _tagMethod() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); assert(state.tag === null); state.tag = tag; this._useArgs(args); return this; }; }); Node.prototype.use = function use(item) { assert(item); var state = this._baseState; assert(state.use === null); state.use = item; return this; }; Node.prototype.optional = function optional() { var state = this._baseState; state.optional = true; return this; }; Node.prototype.def = function def(val) { var state = this._baseState; assert(state['default'] === null); state['default'] = val; state.optional = true; return this; }; Node.prototype.explicit = function explicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.explicit = num; return this; }; Node.prototype.implicit = function implicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.implicit = num; return this; }; Node.prototype.obj = function obj() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); state.obj = true; if (args.length !== 0) this._useArgs(args); return this; }; Node.prototype.key = function key(newKey) { var state = this._baseState; assert(state.key === null); state.key = newKey; return this; }; Node.prototype.any = function any() { var state = this._baseState; state.any = true; return this; }; Node.prototype.choice = function choice(obj) { var state = this._baseState; assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function(key) { return obj[key]; })); return this; }; Node.prototype.contains = function contains(item) { var state = this._baseState; assert(state.use === null); state.contains = item; return this; }; // // Decoding // Node.prototype._decode = function decode(input, options) { var state = this._baseState; // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); var result = state['default']; var present = true; var prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there if (state.optional) { var tag = null; if (state.explicit !== null) tag = state.explicit; else if (state.implicit !== null) tag = state.implicit; else if (state.tag !== null) tag = state.tag; if (tag === null && !state.any) { // Trial and Error var save = input.save(); try { if (state.choice === null) this._decodeGeneric(state.tag, input, options); else this._decodeChoice(input, options); present = true; } catch (e) { present = false; } input.restore(save); } else { present = this._peekTag(input, tag, state.any); if (input.isError(present)) return present; } } // Push object on stack var prevObj; if (state.obj && present) prevObj = input.enterObject(); if (present) { // Unwrap explicit values if (state.explicit !== null) { var explicit = this._decodeTag(input, state.explicit); if (input.isError(explicit)) return explicit; input = explicit; } var start = input.offset; // Unwrap implicit and normal values if (state.use === null && state.choice === null) { if (state.any) var save = input.save(); var body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ); if (input.isError(body)) return body; if (state.any) result = input.raw(save); else input = body; } if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag if (state.any) result = result; else if (state.choice === null) result = this._decodeGeneric(state.tag, input, options); else result = this._decodeChoice(input, options); if (input.isError(result)) return result; // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options); }); } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { var data = new DecoderBuffer(result); result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options); } } // Pop object if (state.obj && present) result = input.leaveObject(prevObj); // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result); else if (prevKey !== null) input.exitKey(prevKey); return result; }; Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { var state = this._baseState; if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options); else if (/str$/.test(tag)) return this._decodeStr(input, tag, options); else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options); else if (tag === 'objid') return this._decodeObjid(input, null, null, options); else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options); else if (tag === 'null_') return this._decodeNull(input, options); else if (tag === 'bool') return this._decodeBool(input, options); else if (tag === 'objDesc') return this._decodeStr(input, tag, options); else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options); } else { return input.error('unknown tag: ' + tag); } }; Node.prototype._getUse = function _getUse(entity, obj) { var state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); assert(state.useDecoder._baseState.parent === null); state.useDecoder = state.useDecoder._baseState.children[0]; if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone(); state.useDecoder._baseState.implicit = state.implicit; } return state.useDecoder; }; Node.prototype._decodeChoice = function decodeChoice(input, options) { var state = this._baseState; var result = null; var match = false; Object.keys(state.choice).some(function(key) { var save = input.save(); var node = state.choice[key]; try { var value = node._decode(input, options); if (input.isError(value)) return false; result = { type: key, value: value }; match = true; } catch (e) { input.restore(save); return false; } return true; }, this); if (!match) return input.error('Choice not matched'); return result; }; // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; Node.prototype._encode = function encode(data, reporter, parent) { var state = this._baseState; if (state['default'] !== null && state['default'] === data) return; var result = this._encodeValue(data, reporter, parent); if (result === undefined) return; if (this._skipDefault(result, reporter, parent)) return; return result; }; Node.prototype._encodeValue = function encode(data, reporter, parent) { var state = this._baseState; // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); var result = null; // Set reporter to share it with a child class this.reporter = reporter; // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) data = state['default'] else return; } // Encode children first var content = null; var primitive = false; if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data); } else if (state.choice) { result = this._encodeChoice(data, reporter); } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter); primitive = true; } else if (state.children) { content = state.children.map(function(child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); if (child._baseState.key === null) return reporter.error('Child should have a key'); var prevKey = reporter.enterKey(child._baseState.key); if (typeof data !== 'object') return reporter.error('Child expected, but input is not object'); var res = child._encode(data[child._baseState.key], reporter, data); reporter.leaveKey(prevKey); return res; }, this).filter(function(child) { return child; }); content = this._createEncoderBuffer(content); } else { if (state.tag === 'seqof' || state.tag === 'setof') { // TODO(indutny): this should be thrown on DSL level if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); var child = this.clone(); child._baseState.implicit = null; content = this._createEncoderBuffer(data.map(function(item) { var state = this._baseState; return this._getUse(state.args[0], data)._encode(item, reporter); }, child)); } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter); } else { content = this._encodePrimitive(state.tag, data); primitive = true; } } // Encode data itself var result; if (!state.any && state.choice === null) { var tag = state.implicit !== null ? state.implicit : state.tag; var cls = state.implicit === null ? 'universal' : 'context'; if (tag === null) { if (state.use === null) reporter.error('Tag could be omitted only for .use()'); } else { if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content); } } // Wrap in explicit if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); return result; }; Node.prototype._encodeChoice = function encodeChoice(data, reporter) { var state = this._baseState; var node = state.choice[data.type]; if (!node) { assert( false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice))); } return node._encode(data.value, reporter); }; Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { var state = this._baseState; if (/str$/.test(tag)) return this._encodeStr(data, tag); else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); else if (tag === 'objid') return this._encodeObjid(data, null, null); else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag); else if (tag === 'null_') return this._encodeNull(); else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]); else if (tag === 'bool') return this._encodeBool(data); else if (tag === 'objDesc') return this._encodeStr(data, tag); else throw new Error('Unsupported tag: ' + tag); }; Node.prototype._isNumstr = function isNumstr(str) { return /^[0-9 ]*$/.test(str); }; Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); }; },{"../base":77,"minimalistic-assert":342}],79:[function(require,module,exports){ var inherits = require('inherits'); function Reporter(options) { this._reporterState = { obj: null, path: [], options: options || {}, errors: [] }; } exports.Reporter = Reporter; Reporter.prototype.isError = function isError(obj) { return obj instanceof ReporterError; }; Reporter.prototype.save = function save() { var state = this._reporterState; return { obj: state.obj, pathLen: state.path.length }; }; Reporter.prototype.restore = function restore(data) { var state = this._reporterState; state.obj = data.obj; state.path = state.path.slice(0, data.pathLen); }; Reporter.prototype.enterKey = function enterKey(key) { return this._reporterState.path.push(key); }; Reporter.prototype.exitKey = function exitKey(index) { var state = this._reporterState; state.path = state.path.slice(0, index - 1); }; Reporter.prototype.leaveKey = function leaveKey(index, key, value) { var state = this._reporterState; this.exitKey(index); if (state.obj !== null) state.obj[key] = value; }; Reporter.prototype.path = function path() { return this._reporterState.path.join('/'); }; Reporter.prototype.enterObject = function enterObject() { var state = this._reporterState; var prev = state.obj; state.obj = {}; return prev; }; Reporter.prototype.leaveObject = function leaveObject(prev) { var state = this._reporterState; var now = state.obj; state.obj = prev; return now; }; Reporter.prototype.error = function error(msg) { var err; var state = this._reporterState; var inherited = msg instanceof ReporterError; if (inherited) { err = msg; } else { err = new ReporterError(state.path.map(function(elem) { return '[' + JSON.stringify(elem) + ']'; }).join(''), msg.message || msg, msg.stack); } if (!state.options.partial) throw err; if (!inherited) state.errors.push(err); return err; }; Reporter.prototype.wrapResult = function wrapResult(result) { var state = this._reporterState; if (!state.options.partial) return result; return { result: this.isError(result) ? null : result, errors: state.errors }; }; function ReporterError(path, msg) { this.path = path; this.rethrow(msg); }; inherits(ReporterError, Error); ReporterError.prototype.rethrow = function rethrow(msg) { this.message = msg + ' at: ' + (this.path || '(shallow)'); if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError); if (!this.stack) { try { // IE only adds stack when thrown throw new Error(this.message); } catch (e) { this.stack = e.stack; } } return this; }; },{"inherits":334}],80:[function(require,module,exports){ var constants = require('../constants'); exports.tagClass = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private' }; exports.tagClassByName = constants._reverse(exports.tagClass); exports.tag = { 0x00: 'end', 0x01: 'bool', 0x02: 'int', 0x03: 'bitstr', 0x04: 'octstr', 0x05: 'null_', 0x06: 'objid', 0x07: 'objDesc', 0x08: 'external', 0x09: 'real', 0x0a: 'enum', 0x0b: 'embed', 0x0c: 'utf8str', 0x0d: 'relativeOid', 0x10: 'seq', 0x11: 'set', 0x12: 'numstr', 0x13: 'printstr', 0x14: 't61str', 0x15: 'videostr', 0x16: 'ia5str', 0x17: 'utctime', 0x18: 'gentime', 0x19: 'graphstr', 0x1a: 'iso646str', 0x1b: 'genstr', 0x1c: 'unistr', 0x1d: 'charstr', 0x1e: 'bmpstr' }; exports.tagByName = constants._reverse(exports.tag); },{"../constants":81}],81:[function(require,module,exports){ var constants = exports; // Helper constants._reverse = function reverse(map) { var res = {}; Object.keys(map).forEach(function(key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; var value = map[key]; res[value] = key; }); return res; }; constants.der = require('./der'); },{"./der":80}],82:[function(require,module,exports){ var inherits = require('inherits'); var asn1 = require('../../asn1'); var base = asn1.base; var bignum = asn1.bignum; // Import DER constants var der = asn1.constants.der; function DERDecoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); }; module.exports = DERDecoder; DERDecoder.prototype.decode = function decode(data, options) { if (!(data instanceof base.DecoderBuffer)) data = new base.DecoderBuffer(data, options); return this.tree._decode(data, options); }; // Tree methods function DERNode(parent) { base.Node.call(this, 'der', parent); } inherits(DERNode, base.Node); DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { if (buffer.isEmpty()) return false; var state = buffer.save(); var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; buffer.restore(state); return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any; }; DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { var decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; var len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); // Failure if (buffer.isError(len)) return len; if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error('Failed to match tag: "' + tag + '"'); } if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); // Indefinite length... find END tag var state = buffer.save(); var res = this._skipUntilEnd( buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); if (buffer.isError(res)) return res; len = buffer.offset - state.offset; buffer.restore(state); return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); }; DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { while (true) { var tag = derDecodeTag(buffer, fail); if (buffer.isError(tag)) return tag; var len = derDecodeLen(buffer, tag.primitive, fail); if (buffer.isError(len)) return len; var res; if (tag.primitive || len !== null) res = buffer.skip(len) else res = this._skipUntilEnd(buffer, fail); // Failure if (buffer.isError(res)) return res; if (tag.tagStr === 'end') break; } }; DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) { var result = []; while (!buffer.isEmpty()) { var possibleEnd = this._peekTag(buffer, 'end'); if (buffer.isError(possibleEnd)) return possibleEnd; var res = decoder.decode(buffer, 'der', options); if (buffer.isError(res) && possibleEnd) break; result.push(res); } return result; }; DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { if (tag === 'bitstr') { var unused = buffer.readUInt8(); if (buffer.isError(unused)) return unused; return { unused: unused, data: buffer.raw() }; } else if (tag === 'bmpstr') { var raw = buffer.raw(); if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch'); var str = ''; for (var i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)); } return str; } else if (tag === 'numstr') { var numstr = buffer.raw().toString('ascii'); if (!this._isNumstr(numstr)) { return buffer.error('Decoding of string type: ' + 'numstr unsupported characters'); } return numstr; } else if (tag === 'octstr') { return buffer.raw(); } else if (tag === 'objDesc') { return buffer.raw(); } else if (tag === 'printstr') { var printstr = buffer.raw().toString('ascii'); if (!this._isPrintstr(printstr)) { return buffer.error('Decoding of string type: ' + 'printstr unsupported characters'); } return printstr; } else if (/str$/.test(tag)) { return buffer.raw().toString(); } else { return buffer.error('Decoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { var result; var identifiers = []; var ident = 0; while (!buffer.isEmpty()) { var subident = buffer.readUInt8(); ident <<= 7; ident |= subident & 0x7f; if ((subident & 0x80) === 0) { identifiers.push(ident); ident = 0; } } if (subident & 0x80) identifiers.push(ident); var first = (identifiers[0] / 40) | 0; var second = identifiers[0] % 40; if (relative) result = identifiers; else result = [first, second].concat(identifiers.slice(1)); if (values) { var tmp = values[result.join(' ')]; if (tmp === undefined) tmp = values[result.join('.')]; if (tmp !== undefined) result = tmp; } return result; }; DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { var str = buffer.raw().toString(); if (tag === 'gentime') { var year = str.slice(0, 4) | 0; var mon = str.slice(4, 6) | 0; var day = str.slice(6, 8) | 0; var hour = str.slice(8, 10) | 0; var min = str.slice(10, 12) | 0; var sec = str.slice(12, 14) | 0; } else if (tag === 'utctime') { var year = str.slice(0, 2) | 0; var mon = str.slice(2, 4) | 0; var day = str.slice(4, 6) | 0; var hour = str.slice(6, 8) | 0; var min = str.slice(8, 10) | 0; var sec = str.slice(10, 12) | 0; if (year < 70) year = 2000 + year; else year = 1900 + year; } else { return buffer.error('Decoding ' + tag + ' time is not supported yet'); } return Date.UTC(year, mon - 1, day, hour, min, sec, 0); }; DERNode.prototype._decodeNull = function decodeNull(buffer) { return null; }; DERNode.prototype._decodeBool = function decodeBool(buffer) { var res = buffer.readUInt8(); if (buffer.isError(res)) return res; else return res !== 0; }; DERNode.prototype._decodeInt = function decodeInt(buffer, values) { // Bigint, return as it is (assume big endian) var raw = buffer.raw(); var res = new bignum(raw); if (values) res = values[res.toString(10)] || res; return res; }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getDecoder('der').tree; }; // Utility methods function derDecodeTag(buf, fail) { var tag = buf.readUInt8(fail); if (buf.isError(tag)) return tag; var cls = der.tagClass[tag >> 6]; var primitive = (tag & 0x20) === 0; // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { var oct = tag; tag = 0; while ((oct & 0x80) === 0x80) { oct = buf.readUInt8(fail); if (buf.isError(oct)) return oct; tag <<= 7; tag |= oct & 0x7f; } } else { tag &= 0x1f; } var tagStr = der.tag[tag]; return { cls: cls, primitive: primitive, tag: tag, tagStr: tagStr }; } function derDecodeLen(buf, primitive, fail) { var len = buf.readUInt8(fail); if (buf.isError(len)) return len; // Indefinite form if (!primitive && len === 0x80) return null; // Definite form if ((len & 0x80) === 0) { // Short form return len; } // Long form var num = len & 0x7f; if (num > 4) return buf.error('length octect is too long'); len = 0; for (var i = 0; i < num; i++) { len <<= 8; var j = buf.readUInt8(fail); if (buf.isError(j)) return j; len |= j; } return len; } },{"../../asn1":74,"inherits":334}],83:[function(require,module,exports){ var decoders = exports; decoders.der = require('./der'); decoders.pem = require('./pem'); },{"./der":82,"./pem":84}],84:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; var DERDecoder = require('./der'); function PEMDecoder(entity) { DERDecoder.call(this, entity); this.enc = 'pem'; }; inherits(PEMDecoder, DERDecoder); module.exports = PEMDecoder; PEMDecoder.prototype.decode = function decode(data, options) { var lines = data.toString().split(/[\r\n]+/g); var label = options.label.toUpperCase(); var re = /^-----(BEGIN|END) ([^-]+)-----$/; var start = -1; var end = -1; for (var i = 0; i < lines.length; i++) { var match = lines[i].match(re); if (match === null) continue; if (match[2] !== label) continue; if (start === -1) { if (match[1] !== 'BEGIN') break; start = i; } else { if (match[1] !== 'END') break; end = i; break; } } if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label); var base64 = lines.slice(start + 1, end).join(''); // Remove excessive symbols base64.replace(/[^a-z0-9\+\/=]+/gi, ''); var input = new Buffer(base64, 'base64'); return DERDecoder.prototype.decode.call(this, input, options); }; },{"./der":82,"buffer":144,"inherits":334}],85:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; var asn1 = require('../../asn1'); var base = asn1.base; // Import DER constants var der = asn1.constants.der; function DEREncoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); }; module.exports = DEREncoder; DEREncoder.prototype.encode = function encode(data, reporter) { return this.tree._encode(data, reporter).join(); }; // Tree methods function DERNode(parent) { base.Node.call(this, 'der', parent); } inherits(DERNode, base.Node); DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { var encodedTag = encodeTag(tag, primitive, cls, this.reporter); // Short form if (content.length < 0x80) { var header = new Buffer(2); header[0] = encodedTag; header[1] = content.length; return this._createEncoderBuffer([ header, content ]); } // Long form // Count octets required to store length var lenOctets = 1; for (var i = content.length; i >= 0x100; i >>= 8) lenOctets++; var header = new Buffer(1 + 1 + lenOctets); header[0] = encodedTag; header[1] = 0x80 | lenOctets; for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 0xff; return this._createEncoderBuffer([ header, content ]); }; DERNode.prototype._encodeStr = function encodeStr(str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([ str.unused | 0, str.data ]); } else if (tag === 'bmpstr') { var buf = new Buffer(str.length * 2); for (var i = 0; i < str.length; i++) { buf.writeUInt16BE(str.charCodeAt(i), i * 2); } return this._createEncoderBuffer(buf); } else if (tag === 'numstr') { if (!this._isNumstr(str)) { return this.reporter.error('Encoding of string type: numstr supports ' + 'only digits and space'); } return this._createEncoderBuffer(str); } else if (tag === 'printstr') { if (!this._isPrintstr(str)) { return this.reporter.error('Encoding of string type: printstr supports ' + 'only latin upper and lower case letters, ' + 'digits, space, apostrophe, left and rigth ' + 'parenthesis, plus sign, comma, hyphen, ' + 'dot, slash, colon, equal sign, ' + 'question mark'); } return this._createEncoderBuffer(str); } else if (/str$/.test(tag)) { return this._createEncoderBuffer(str); } else if (tag === 'objDesc') { return this._createEncoderBuffer(str); } else { return this.reporter.error('Encoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { if (typeof id === 'string') { if (!values) return this.reporter.error('string objid given, but no values map found'); if (!values.hasOwnProperty(id)) return this.reporter.error('objid not found in values map'); id = values[id].split(/[\s\.]+/g); for (var i = 0; i < id.length; i++) id[i] |= 0; } else if (Array.isArray(id)) { id = id.slice(); for (var i = 0; i < id.length; i++) id[i] |= 0; } if (!Array.isArray(id)) { return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id)); } if (!relative) { if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB'); id.splice(0, 2, id[0] * 40 + id[1]); } // Count number of octets var size = 0; for (var i = 0; i < id.length; i++) { var ident = id[i]; for (size++; ident >= 0x80; ident >>= 7) size++; } var objid = new Buffer(size); var offset = objid.length - 1; for (var i = id.length - 1; i >= 0; i--) { var ident = id[i]; objid[offset--] = ident & 0x7f; while ((ident >>= 7) > 0) objid[offset--] = 0x80 | (ident & 0x7f); } return this._createEncoderBuffer(objid); }; function two(num) { if (num < 10) return '0' + num; else return num; } DERNode.prototype._encodeTime = function encodeTime(time, tag) { var str; var date = new Date(time); if (tag === 'gentime') { str = [ two(date.getFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else if (tag === 'utctime') { str = [ two(date.getFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else { this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } return this._encodeStr(str, 'octstr'); }; DERNode.prototype._encodeNull = function encodeNull() { return this._createEncoderBuffer(''); }; DERNode.prototype._encodeInt = function encodeInt(num, values) { if (typeof num === 'string') { if (!values) return this.reporter.error('String int or enum given, but no values map'); if (!values.hasOwnProperty(num)) { return this.reporter.error('Values map doesn\'t contain: ' + JSON.stringify(num)); } num = values[num]; } // Bignum, assume big endian if (typeof num !== 'number' && !Buffer.isBuffer(num)) { var numArray = num.toArray(); if (!num.sign && numArray[0] & 0x80) { numArray.unshift(0); } num = new Buffer(numArray); } if (Buffer.isBuffer(num)) { var size = num.length; if (num.length === 0) size++; var out = new Buffer(size); num.copy(out); if (num.length === 0) out[0] = 0 return this._createEncoderBuffer(out); } if (num < 0x80) return this._createEncoderBuffer(num); if (num < 0x100) return this._createEncoderBuffer([0, num]); var size = 1; for (var i = num; i >= 0x100; i >>= 8) size++; var out = new Array(size); for (var i = out.length - 1; i >= 0; i--) { out[i] = num & 0xff; num >>= 8; } if(out[0] & 0x80) { out.unshift(0); } return this._createEncoderBuffer(new Buffer(out)); }; DERNode.prototype._encodeBool = function encodeBool(value) { return this._createEncoderBuffer(value ? 0xff : 0); }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getEncoder('der').tree; }; DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { var state = this._baseState; var i; if (state['default'] === null) return false; var data = dataBuffer.join(); if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); if (data.length !== state.defaultBuffer.length) return false; for (i=0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return false; return true; }; // Utility methods function encodeTag(tag, primitive, cls, reporter) { var res; if (tag === 'seqof') tag = 'seq'; else if (tag === 'setof') tag = 'set'; if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag]; else if (typeof tag === 'number' && (tag | 0) === tag) res = tag; else return reporter.error('Unknown tag: ' + tag); if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported'); if (!primitive) res |= 0x20; res |= (der.tagClassByName[cls || 'universal'] << 6); return res; } },{"../../asn1":74,"buffer":144,"inherits":334}],86:[function(require,module,exports){ var encoders = exports; encoders.der = require('./der'); encoders.pem = require('./pem'); },{"./der":85,"./pem":87}],87:[function(require,module,exports){ var inherits = require('inherits'); var DEREncoder = require('./der'); function PEMEncoder(entity) { DEREncoder.call(this, entity); this.enc = 'pem'; }; inherits(PEMEncoder, DEREncoder); module.exports = PEMEncoder; PEMEncoder.prototype.encode = function encode(data, options) { var buf = DEREncoder.prototype.encode.call(this, data); var p = buf.toString('base64'); var out = [ '-----BEGIN ' + options.label + '-----' ]; for (var i = 0; i < p.length; i += 64) out.push(p.slice(i, i + 64)); out.push('-----END ' + options.label + '-----'); return out.join('\n'); }; },{"./der":85,"inherits":334}],88:[function(require,module,exports){ (function (global){ 'use strict'; // 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: // 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; }; 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 : {}) },{"util/":563}],89:[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 placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0; i < l; 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[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = 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 output = '' 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] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],90:[function(require,module,exports){ (function (process,global){ /* @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.0 * 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(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; 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.0"; _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 !== 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 : {}) },{"_process":507}],91:[function(require,module,exports){ (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // Could use `inherits` module, but don't want to move from single file // architecture yet. function inherits (ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } // BN function BN (number, base, endian) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { Buffer = require('buffer').Buffer; } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } if (typeof number === 'object') { return this._initArray(number, base, endian); } if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; } if (base === 16) { this._parseHex(number, start); } else { this._parseBase(number, base, start); } if (number[0] === '-') { this.negative = 1; } this.strip(); if (endian !== 'le') return; this._initArray(this.toArray(), base, endian); }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } else if (endian === 'le') { for (i = 0, j = 0; i < number.length; i += 3) { w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; off += 24; if (off >= 26) { off -= 26; j++; } } } return this.strip(); }; function parseHex (str, start, end) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r <<= 4; // 'a' - 'f' if (c >= 49 && c <= 54) { r |= c - 49 + 0xa; // 'A' - 'F' } else if (c >= 17 && c <= 22) { r |= c - 17 + 0xa; // '0' - '9' } else { r |= c & 0xf; } } return r; } BN.prototype._parseHex = function _parseHex (number, start) { // Create possibly bigger array to ensure that it fits the number this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i = 0; i < this.length; i++) { this.words[i] = 0; } var j, w; // Scan 24-bit chunks and add them to the number var off = 0; for (i = number.length - 6, j = 0; i >= start; i -= 6) { w = parseHex(number, i, i + 6); this.words[j] |= (w << off) & 0x3ffffff; // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; off += 24; if (off >= 26) { off -= 26; j++; } } if (i + 6 !== start) { w = parseHex(number, start, i + 6); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } }; BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { dest.words[i] = this.words[i]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // Remove leading `0` from `this` BN.prototype.strip = function strip () { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN.prototype.inspect = function inspect () { return (this.red ? ''; }; /* var zeros = []; var groupSizes = []; var groupBases = []; var s = ''; var i = -1; while (++i < BN.wordSize) { zeros[i] = s; s += '0'; } groupSizes[0] = 0; groupSizes[1] = 0; groupBases[0] = 0; groupBases[1] = 0; var base = 2 - 1; while (++base < 36 + 1) { var groupSize = 0; var groupBase = 1; while (groupBase < (1 << BN.wordSize) / base) { groupBase *= base; groupSize += 1; } groupSizes[base] = groupSize; groupBases[base] = groupBase; } */ var zeros = [ '', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000', '0000000000', '00000000000', '000000000000', '0000000000000', '00000000000000', '000000000000000', '0000000000000000', '00000000000000000', '000000000000000000', '0000000000000000000', '00000000000000000000', '000000000000000000000', '0000000000000000000000', '00000000000000000000000', '000000000000000000000000', '0000000000000000000000000' ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN.prototype.toString = function toString (base, padding) { base = base || 10; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; var carry = 0; for (var i = 0; i < this.length; i++) { var w = this.words[i]; var word = (((w << off) | carry) & 0xffffff).toString(16); carry = (w >>> (24 - off)) & 0xffffff; if (carry !== 0 || i !== this.length - 1) { out = zeros[6 - word.length] + word + out; } else { out = word + out; } off += 2; if (off >= 26) { off -= 26; i--; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } if (base === (base | 0) && base >= 2 && base <= 36) { // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); var groupSize = groupSizes[base]; // var groupBase = Math.pow(base, groupSize); var groupBase = groupBases[base]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; // Copy the rest of the words } else if (a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } return this; }; // Add `num` to `this` BN.prototype.add = function add (num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // Copy rest of the words if (carry === 0 && i < a.length && a !== this) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = Math.max(this.length, i); if (a !== this) { this.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = carry >>> 26; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.length + num.length; var carry = 0; var hncarry = 0; for (var k = 0; k < out.length - 1; k++) { // Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff var ncarry = hncarry; hncarry = 0; var rword = carry & 0x3ffffff; var maxJ = Math.min(k, num.length - 1); for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.words[i] | 0; var b = num.words[j] | 0; var r = a * b; var lo = r & 0x3ffffff; ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; lo = (lo + rword) | 0; rword = lo & 0x3ffffff; ncarry = (ncarry + (lo >>> 26)) | 0; hncarry += ncarry >>> 26; ncarry &= 0x3ffffff; } out.words[k] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // Multiply `this` by `num` BN.prototype.mul = function mul (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // Extended mode, copy masked part if (maskedWords) { for (var i = 0; i < s; i++) { maskedWords.words[i] = this.words[i]; } maskedWords.length = s; } if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { this.length -= s; for (i = 0; i < this.length; i++) { this.words[i] = this.words[i + s]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; this.words[i] = (carry << (26 - r)) | (word >>> r); carry = word & mask; } // Push carried bits as a mask if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(bits); }; // Test if n bit is set BN.prototype.testn = function testn (bit) { assert(typeof bit === 'number' && bit >= 0); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) return false; // Check bit and return var w = this.words[s]; return !!(w & q); }; // Return only lowers bits of number (in-place) BN.prototype.imaskn = function imaskn (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; assert(this.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } if (r !== 0) { s++; } this.length = Math.min(s, this.length); if (r !== 0) { var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); this.words[this.length - 1] &= mask; } return this.strip(); }; // Return only lowers bits of number BN.prototype.maskn = function maskn (bits) { return this.clone().imaskn(bits); }; // Add plain number `num` to `this` BN.prototype.iaddn = function iaddn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { this.words[0] += num; // Carry for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { this.words[i] -= 0x4000000; if (i === this.length - 1) { this.words[i + 1] = 1; } else { this.words[i + 1]++; } } this.length = Math.max(this.length, i + 1); return this; }; // Subtract plain number `num` from `this` BN.prototype.isubn = function isubn (num) { assert(typeof num === 'number'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // Carry for (var i = 0; i < this.length && this.words[i] < 0; i++) { this.words[i] += 0x4000000; this.words[i + 1] -= 1; } } return this.strip(); }; BN.prototype.addn = function addn (num) { return this.clone().iaddn(num); }; BN.prototype.subn = function subn (num) { return this.clone().isubn(num); }; BN.prototype.iabs = function iabs () { this.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // Both numbers are positive at this point // Strip both numbers to approximate shift value if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN(0), mod: this }; } // Very short reduction if (num.length === 1) { if (mode === 'div') { return { div: this.divn(num.words[0]), mod: null }; } if (mode === 'mod') { return { div: null, mod: new BN(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; // Find `this` / `num` BN.prototype.div = function div (num) { return this.divmod(num, 'div', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r2 = num.andln(1); var cmp = mod.cmp(half); // Round down if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; // Round up return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN.prototype.modn = function modn (num) { assert(num <= 0x3ffffff); var p = (1 << 26) % num; var acc = 0; for (var i = this.length - 1; i >= 0; i--) { acc = (p * acc + (this.words[i] | 0)) % num; } return acc; }; // In-place division by number BN.prototype.idivn = function idivn (num) { assert(num <= 0x3ffffff); var carry = 0; for (var i = this.length - 1; i >= 0; i--) { var w = (this.words[i] | 0) + carry * 0x4000000; this.words[i] = (w / num) | 0; carry = w % num; } return this.strip(); }; BN.prototype.divn = function divn (num) { return this.clone().idivn(num); }; BN.prototype.egcd = function egcd (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { return (this.words[0] & 1) === 1; }; // And first word and num BN.prototype.andln = function andln (num) { return this.words[0] & num; }; // Increment at the bit position in-line BN.prototype.bincn = function bincn (bit) { assert(typeof bit === 'number'); var r = bit % 26; var s = (bit - r) / 26; var q = 1 << r; // Fast case: bit is much higher than all existing words if (this.length <= s) { this._expand(s + 1); this.words[s] |= q; return this; } // Add bit and propagate, if needed var carry = q; for (var i = s; carry !== 0 && i < this.length; i++) { var w = this.words[i] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` BN.prototype.cmp = function cmp (num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; // Unsigned comparison BN.prototype.ucmp = function ucmp (num) { // At this point both numbers have the same sign if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // A reduce context, could be using montgomery or something better, depending // on the `m` itself. // BN.red = function red (num) { return new Red(num); }; BN.prototype.toRed = function toRed (ctx) { assert(!this.red, 'Already a number in reduction context'); assert(this.negative === 0, 'red works only with positives'); return ctx.convertTo(this)._forceRed(ctx); }; BN.prototype.fromRed = function fromRed () { assert(this.red, 'fromRed works only with numbers in reduction context'); return this.red.convertFrom(this); }; BN.prototype._forceRed = function _forceRed (ctx) { this.red = ctx; return this; }; BN.prototype.forceRed = function forceRed (ctx) { assert(!this.red, 'Already a number in reduction context'); return this._forceRed(ctx); }; BN.prototype.redAdd = function redAdd (num) { assert(this.red, 'redAdd works only with red numbers'); return this.red.add(this, num); }; BN.prototype.redIAdd = function redIAdd (num) { assert(this.red, 'redIAdd works only with red numbers'); return this.red.iadd(this, num); }; BN.prototype.redSub = function redSub (num) { assert(this.red, 'redSub works only with red numbers'); return this.red.sub(this, num); }; BN.prototype.redISub = function redISub (num) { assert(this.red, 'redISub works only with red numbers'); return this.red.isub(this, num); }; BN.prototype.redShl = function redShl (num) { assert(this.red, 'redShl works only with red numbers'); return this.red.shl(this, num); }; BN.prototype.redMul = function redMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.mul(this, num); }; BN.prototype.redIMul = function redIMul (num) { assert(this.red, 'redMul works only with red numbers'); this.red._verify2(this, num); return this.red.imul(this, num); }; BN.prototype.redSqr = function redSqr () { assert(this.red, 'redSqr works only with red numbers'); this.red._verify1(this); return this.red.sqr(this); }; BN.prototype.redISqr = function redISqr () { assert(this.red, 'redISqr works only with red numbers'); this.red._verify1(this); return this.red.isqr(this); }; // Square root over p BN.prototype.redSqrt = function redSqrt () { assert(this.red, 'redSqrt works only with red numbers'); this.red._verify1(this); return this.red.sqrt(this); }; BN.prototype.redInvm = function redInvm () { assert(this.red, 'redInvm works only with red numbers'); this.red._verify1(this); return this.red.invm(this); }; // Return negative clone of `this` % `red modulo` BN.prototype.redNeg = function redNeg () { assert(this.red, 'redNeg works only with red numbers'); this.red._verify1(this); return this.red.neg(this); }; BN.prototype.redPow = function redPow (num) { assert(this.red && !num.red, 'redPow(normalNum)'); this.red._verify1(this); return this.red.pow(this, num); }; // Prime numbers with efficient reduction var primes = { k256: null, p224: null, p192: null, p25519: null }; // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K this.name = name; this.p = new BN(p, 16); this.n = this.p.bitLength(); this.k = new BN(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp () { var tmp = new BN(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce (num) { // Assumes that `num` is less than `P^2` // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) var r = num; var rlen; do { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(this.p); if (cmp === 0) { r.words[0] = 0; r.length = 1; } else if (cmp > 0) { r.isub(this.p); } else { r.strip(); } return r; }; MPrime.prototype.split = function split (input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK (num) { return num.imul(this.k); }; function K256 () { MPrime.call( this, 'k256', 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); } inherits(K256, MPrime); K256.prototype.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224 () { MPrime.call( this, 'p224', 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); function P192 () { MPrime.call( this, 'p192', 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); function P25519 () { // 2 ^ 255 - 19 MPrime.call( this, '25519', '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; for (var i = 0; i < num.length; i++) { var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; num.words[i] = lo; carry = hi; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; // Exported mostly for testing purposes, use plain name instead BN._prime = function prime (name) { // Cached version of prime if (primes[name]) return primes[name]; var prime; if (name === 'k256') { prime = new K256(); } else if (name === 'p224') { prime = new P224(); } else if (name === 'p192') { prime = new P192(); } else if (name === 'p25519') { prime = new P25519(); } else { throw new Error('Unknown prime ' + name); } primes[name] = prime; return prime; }; // // Base reduction engine // function Red (m) { if (typeof m === 'string') { var prime = BN._prime(m); this.m = prime.p; this.prime = prime; } else { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, 'red works only with positives'); assert(a.red && a.red === b.red, 'red works only with red numbers'); }; Red.prototype.imod = function imod (a) { if (this.prime) return this.prime.ireduce(a)._forceRed(this); return a.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._forceRed(this); }; Red.prototype.add = function add (a, b) { this._verify2(a, b); var res = a.add(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd (a, b) { this._verify2(a, b); var res = a.iadd(b); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub (a, b) { this._verify2(a, b); var res = a.sub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub (a, b) { this._verify2(a, b); var res = a.isub(b); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl (a, num) { this._verify1(a); return this.imod(a.ushln(num)); }; Red.prototype.imul = function imul (a, b) { this._verify2(a, b); return this.imod(a.imul(b)); }; Red.prototype.mul = function mul (a, b) { this._verify2(a, b); return this.imod(a.mul(b)); }; Red.prototype.isqr = function isqr (a) { return this.imul(a, a.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) return a.clone(); var mod3 = this.m.andln(3); assert(mod3 % 2 === 1); // Fast case if (mod3 === 3) { var pow = this.m.add(new BN(1)).iushrn(2); return this.pow(a, pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) var q = this.m.subn(1); var s = 0; while (!q.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); var one = new BN(1).toRed(this); var nOne = one.redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. var lpow = this.m.subn(1).iushrn(1); var z = this.m.bitLength(); z = new BN(2 * z * z).toRed(this); while (this.pow(z, lpow).cmp(nOne) !== 0) { z.redIAdd(nOne); } var c = this.pow(z, q); var r = this.pow(a, q.addn(1).iushrn(1)); var t = this.pow(a, q); var m = s; while (t.cmp(one) !== 0) { var tmp = t; for (var i = 0; tmp.cmp(one) !== 0; i++) { tmp = tmp.redSqr(); } assert(i < m); var b = this.pow(c, new BN(1).iushln(m - i - 1)); r = r.redMul(b); c = b.redSqr(); t = t.redMul(c); m = i; } return r; }; Red.prototype.invm = function invm (a) { var inv = a._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; Red.prototype.convertFrom = function convertFrom (num) { var res = num.clone(); res.red = null; return res; }; // // Montgomery method engine // BN.mont = function mont (num) { return new Mont(num); }; function Mont (m) { Red.call(this, m); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - (this.shift % 26); } this.r = new BN(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom (num) { var r = this.imod(num.mul(this.rinv)); r.red = null; return r; }; Mont.prototype.imul = function imul (a, b) { if (a.isZero() || b.isZero()) { a.words[0] = 0; a.length = 1; return a; } var t = a.imul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul (a, b) { if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); var t = a.mul(b); var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u = t.isub(c).iushrn(this.shift); var res = u; if (u.cmp(this.m) >= 0) { res = u.isub(this.m); } else if (u.cmpn(0) < 0) { res = u.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm (a) { // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R var res = this.imod(a._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === 'undefined' || module, this); },{"buffer":93}],92:[function(require,module,exports){ var r; module.exports = function rand(len) { if (!r) r = new Rand(null); return r.generate(len); }; function Rand(rand) { this.rand = rand; } module.exports.Rand = Rand; Rand.prototype.generate = function generate(len) { return this._rand(len); }; // Emulate crypto API using randy Rand.prototype._rand = function _rand(n) { if (this.rand.getBytes) return this.rand.getBytes(n); var res = new Uint8Array(n); for (var i = 0; i < res.length; i++) res[i] = this.rand.getByte(); return res; }; if (typeof self === 'object') { if (self.crypto && self.crypto.getRandomValues) { // Modern browsers Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.crypto.getRandomValues(arr); return arr; }; } else if (self.msCrypto && self.msCrypto.getRandomValues) { // IE Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.msCrypto.getRandomValues(arr); return arr; }; // Safari's WebWorkers do not have `crypto` } else if (typeof window === 'object') { // Old junk Rand.prototype._rand = function() { throw new Error('Not implemented yet'); }; } } else { // Node.js or Web worker with no crypto support try { var crypto = require('crypto'); if (typeof crypto.randomBytes !== 'function') throw new Error('Not supported'); Rand.prototype._rand = function _rand(n) { return crypto.randomBytes(n); }; } catch (e) { } } },{"crypto":93}],93:[function(require,module,exports){ },{}],94:[function(require,module,exports){ // based on the aes implimentation in triple sec // https://github.com/keybase/triplesec // which is in turn based on the one from crypto-js // https://code.google.com/p/crypto-js/ var Buffer = require('safe-buffer').Buffer function asUInt32Array (buf) { if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) var len = (buf.length / 4) | 0 var out = new Array(len) for (var i = 0; i < len; i++) { out[i] = buf.readUInt32BE(i * 4) } return out } function scrubVec (v) { for (var i = 0; i < v.length; v++) { v[i] = 0 } } function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { var SUB_MIX0 = SUB_MIX[0] var SUB_MIX1 = SUB_MIX[1] var SUB_MIX2 = SUB_MIX[2] var SUB_MIX3 = SUB_MIX[3] var s0 = M[0] ^ keySchedule[0] var s1 = M[1] ^ keySchedule[1] var s2 = M[2] ^ keySchedule[2] var s3 = M[3] ^ keySchedule[3] var t0, t1, t2, t3 var ksRow = 4 for (var round = 1; round < nRounds; round++) { t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] s0 = t0 s1 = t1 s2 = t2 s3 = t3 } t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] t0 = t0 >>> 0 t1 = t1 >>> 0 t2 = t2 >>> 0 t3 = t3 >>> 0 return [t0, t1, t2, t3] } // AES constants var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] var G = (function () { // Compute double table var d = new Array(256) for (var j = 0; j < 256; j++) { if (j < 128) { d[j] = j << 1 } else { d[j] = (j << 1) ^ 0x11b } } var SBOX = [] var INV_SBOX = [] var SUB_MIX = [[], [], [], []] var INV_SUB_MIX = [[], [], [], []] // Walk GF(2^8) var x = 0 var xi = 0 for (var i = 0; i < 256; ++i) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 SBOX[x] = sx INV_SBOX[sx] = x // Compute multiplication var x2 = d[x] var x4 = d[x2] var x8 = d[x4] // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100) SUB_MIX[0][x] = (t << 24) | (t >>> 8) SUB_MIX[1][x] = (t << 16) | (t >>> 16) SUB_MIX[2][x] = (t << 8) | (t >>> 24) SUB_MIX[3][x] = t // Compute inv sub bytes, inv mix columns tables t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) INV_SUB_MIX[3][sx] = t if (x === 0) { x = xi = 1 } else { x = x2 ^ d[d[d[x8 ^ x2]]] xi ^= d[d[xi]] } } return { SBOX: SBOX, INV_SBOX: INV_SBOX, SUB_MIX: SUB_MIX, INV_SUB_MIX: INV_SUB_MIX } })() function AES (key) { this._key = asUInt32Array(key) this._reset() } AES.blockSize = 4 * 4 AES.keySize = 256 / 8 AES.prototype.blockSize = AES.blockSize AES.prototype.keySize = AES.keySize AES.prototype._reset = function () { var keyWords = this._key var keySize = keyWords.length var nRounds = keySize + 6 var ksRows = (nRounds + 1) * 4 var keySchedule = [] for (var k = 0; k < keySize; k++) { keySchedule[k] = keyWords[k] } for (k = keySize; k < ksRows; k++) { var t = keySchedule[k - 1] if (k % keySize === 0) { t = (t << 8) | (t >>> 24) t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | (G.SBOX[t & 0xff]) t ^= RCON[(k / keySize) | 0] << 24 } else if (keySize > 6 && k % keySize === 4) { t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | (G.SBOX[t & 0xff]) } keySchedule[k] = keySchedule[k - keySize] ^ t } var invKeySchedule = [] for (var ik = 0; ik < ksRows; ik++) { var ksR = ksRows - ik var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] if (ik < 4 || ksR <= 4) { invKeySchedule[ik] = tt } else { invKeySchedule[ik] = G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] } } this._nRounds = nRounds this._keySchedule = keySchedule this._invKeySchedule = invKeySchedule } AES.prototype.encryptBlockRaw = function (M) { M = asUInt32Array(M) return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) } AES.prototype.encryptBlock = function (M) { var out = this.encryptBlockRaw(M) var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0], 0) buf.writeUInt32BE(out[1], 4) buf.writeUInt32BE(out[2], 8) buf.writeUInt32BE(out[3], 12) return buf } AES.prototype.decryptBlock = function (M) { M = asUInt32Array(M) // swap var m1 = M[1] M[1] = M[3] M[3] = m1 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0], 0) buf.writeUInt32BE(out[3], 4) buf.writeUInt32BE(out[2], 8) buf.writeUInt32BE(out[1], 12) return buf } AES.prototype.scrub = function () { scrubVec(this._keySchedule) scrubVec(this._invKeySchedule) scrubVec(this._key) } module.exports.AES = AES },{"safe-buffer":537}],95:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') var inherits = require('inherits') var GHASH = require('./ghash') var xor = require('buffer-xor') var incr32 = require('./incr32') function xorTest (a, b) { var out = 0 if (a.length !== b.length) out++ var len = Math.min(a.length, b.length) for (var i = 0; i < len; ++i) { out += (a[i] ^ b[i]) } return out } function calcIv (self, iv, ck) { if (iv.length === 12) { self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) } var ghash = new GHASH(ck) var len = iv.length var toPad = len % 16 ghash.update(iv) if (toPad) { toPad = 16 - toPad ghash.update(Buffer.alloc(toPad, 0)) } ghash.update(Buffer.alloc(8, 0)) var ivBits = len * 8 var tail = Buffer.alloc(8) tail.writeUIntBE(ivBits, 0, 8) ghash.update(tail) self._finID = ghash.state var out = Buffer.from(self._finID) incr32(out) return out } function StreamCipher (mode, key, iv, decrypt) { Transform.call(this) var h = Buffer.alloc(4, 0) this._cipher = new aes.AES(key) var ck = this._cipher.encryptBlock(h) this._ghash = new GHASH(ck) iv = calcIv(this, iv, ck) this._prev = Buffer.from(iv) this._cache = Buffer.allocUnsafe(0) this._secCache = Buffer.allocUnsafe(0) this._decrypt = decrypt this._alen = 0 this._len = 0 this._mode = mode this._authTag = null this._called = false } inherits(StreamCipher, Transform) StreamCipher.prototype._update = function (chunk) { if (!this._called && this._alen) { var rump = 16 - (this._alen % 16) if (rump < 16) { rump = Buffer.alloc(rump, 0) this._ghash.update(rump) } } this._called = true var out = this._mode.encrypt(this, chunk) if (this._decrypt) { this._ghash.update(chunk) } else { this._ghash.update(out) } this._len += chunk.length return out } StreamCipher.prototype._final = function () { if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') this._authTag = tag this._cipher.scrub() } StreamCipher.prototype.getAuthTag = function getAuthTag () { if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') return this._authTag } StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') this._authTag = tag } StreamCipher.prototype.setAAD = function setAAD (buf) { if (this._called) throw new Error('Attempting to set AAD in unsupported state') this._ghash.update(buf) this._alen += buf.length } module.exports = StreamCipher },{"./aes":94,"./ghash":99,"./incr32":100,"buffer-xor":143,"cipher-base":145,"inherits":334,"safe-buffer":537}],96:[function(require,module,exports){ var ciphers = require('./encrypter') var deciphers = require('./decrypter') var modes = require('./modes/list.json') function getCiphers () { return Object.keys(modes) } exports.createCipher = exports.Cipher = ciphers.createCipher exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv exports.createDecipher = exports.Decipher = deciphers.createDecipher exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv exports.listCiphers = exports.getCiphers = getCiphers },{"./decrypter":97,"./encrypter":98,"./modes/list.json":108}],97:[function(require,module,exports){ var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer var MODES = require('./modes') var StreamCipher = require('./streamCipher') var Transform = require('cipher-base') var aes = require('./aes') var ebtk = require('evp_bytestokey') var inherits = require('inherits') function Decipher (mode, key, iv) { Transform.call(this) this._cache = new Splitter() this._last = void 0 this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._mode = mode this._autopadding = true } inherits(Decipher, Transform) Decipher.prototype._update = function (data) { this._cache.add(data) var chunk var thing var out = [] while ((chunk = this._cache.get(this._autopadding))) { thing = this._mode.decrypt(this, chunk) out.push(thing) } return Buffer.concat(out) } Decipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { return unpad(this._mode.decrypt(this, chunk)) } else if (chunk) { throw new Error('data not multiple of block length') } } Decipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } function Splitter () { this.cache = Buffer.allocUnsafe(0) } Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } Splitter.prototype.get = function (autoPadding) { var out if (autoPadding) { if (this.cache.length > 16) { out = this.cache.slice(0, 16) this.cache = this.cache.slice(16) return out } } else { if (this.cache.length >= 16) { out = this.cache.slice(0, 16) this.cache = this.cache.slice(16) return out } } return null } Splitter.prototype.flush = function () { if (this.cache.length) return this.cache } function unpad (last) { var padded = last[15] var i = -1 while (++i < padded) { if (last[(i + (16 - padded))] !== padded) { throw new Error('unable to decrypt data') } } if (padded === 16) return return last.slice(0, 16 - padded) } function createDecipheriv (suite, password, iv) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') if (typeof iv === 'string') iv = Buffer.from(iv) if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) if (typeof password === 'string') password = Buffer.from(password) if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) if (config.type === 'stream') { return new StreamCipher(config.module, password, iv, true) } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv, true) } return new Decipher(config.module, password, iv) } function createDecipher (suite, password) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') var keys = ebtk(password, false, config.key, config.iv) return createDecipheriv(suite, keys.key, keys.iv) } exports.createDecipher = createDecipher exports.createDecipheriv = createDecipheriv },{"./aes":94,"./authCipher":95,"./modes":107,"./streamCipher":110,"cipher-base":145,"evp_bytestokey":317,"inherits":334,"safe-buffer":537}],98:[function(require,module,exports){ var MODES = require('./modes') var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer var StreamCipher = require('./streamCipher') var Transform = require('cipher-base') var aes = require('./aes') var ebtk = require('evp_bytestokey') var inherits = require('inherits') function Cipher (mode, key, iv) { Transform.call(this) this._cache = new Splitter() this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._mode = mode this._autopadding = true } inherits(Cipher, Transform) Cipher.prototype._update = function (data) { this._cache.add(data) var chunk var thing var out = [] while ((chunk = this._cache.get())) { thing = this._mode.encrypt(this, chunk) out.push(thing) } return Buffer.concat(out) } var PADDING = Buffer.alloc(16, 0x10) Cipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { chunk = this._mode.encrypt(this, chunk) this._cipher.scrub() return chunk } if (!chunk.equals(PADDING)) { this._cipher.scrub() throw new Error('data not multiple of block length') } } Cipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } function Splitter () { this.cache = Buffer.allocUnsafe(0) } Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } Splitter.prototype.get = function () { if (this.cache.length > 15) { var out = this.cache.slice(0, 16) this.cache = this.cache.slice(16) return out } return null } Splitter.prototype.flush = function () { var len = 16 - this.cache.length var padBuff = Buffer.allocUnsafe(len) var i = -1 while (++i < len) { padBuff.writeUInt8(len, i) } return Buffer.concat([this.cache, padBuff]) } function createCipheriv (suite, password, iv) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') if (typeof password === 'string') password = Buffer.from(password) if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) if (typeof iv === 'string') iv = Buffer.from(iv) if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) if (config.type === 'stream') { return new StreamCipher(config.module, password, iv) } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv) } return new Cipher(config.module, password, iv) } function createCipher (suite, password) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') var keys = ebtk(password, false, config.key, config.iv) return createCipheriv(suite, keys.key, keys.iv) } exports.createCipheriv = createCipheriv exports.createCipher = createCipher },{"./aes":94,"./authCipher":95,"./modes":107,"./streamCipher":110,"cipher-base":145,"evp_bytestokey":317,"inherits":334,"safe-buffer":537}],99:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var ZEROES = Buffer.alloc(16, 0) function toArray (buf) { return [ buf.readUInt32BE(0), buf.readUInt32BE(4), buf.readUInt32BE(8), buf.readUInt32BE(12) ] } function fromArray (out) { var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0] >>> 0, 0) buf.writeUInt32BE(out[1] >>> 0, 4) buf.writeUInt32BE(out[2] >>> 0, 8) buf.writeUInt32BE(out[3] >>> 0, 12) return buf } function GHASH (key) { this.h = key this.state = Buffer.alloc(16, 0) this.cache = Buffer.allocUnsafe(0) } // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html // by Juho Vähä-Herttua GHASH.prototype.ghash = function (block) { var i = -1 while (++i < block.length) { this.state[i] ^= block[i] } this._multiply() } GHASH.prototype._multiply = function () { var Vi = toArray(this.h) var Zi = [0, 0, 0, 0] var j, xi, lsbVi var i = -1 while (++i < 128) { xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 if (xi) { // Z_i+1 = Z_i ^ V_i Zi[0] ^= Vi[0] Zi[1] ^= Vi[1] Zi[2] ^= Vi[2] Zi[3] ^= Vi[3] } // Store the value of LSB(V_i) lsbVi = (Vi[3] & 1) !== 0 // V_i+1 = V_i >> 1 for (j = 3; j > 0; j--) { Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) } Vi[0] = Vi[0] >>> 1 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R if (lsbVi) { Vi[0] = Vi[0] ^ (0xe1 << 24) } } this.state = fromArray(Zi) } GHASH.prototype.update = function (buf) { this.cache = Buffer.concat([this.cache, buf]) var chunk while (this.cache.length >= 16) { chunk = this.cache.slice(0, 16) this.cache = this.cache.slice(16) this.ghash(chunk) } } GHASH.prototype.final = function (abl, bl) { if (this.cache.length) { this.ghash(Buffer.concat([this.cache, ZEROES], 16)) } this.ghash(fromArray([0, abl, 0, bl])) return this.state } module.exports = GHASH },{"safe-buffer":537}],100:[function(require,module,exports){ function incr32 (iv) { var len = iv.length var item while (len--) { item = iv.readUInt8(len) if (item === 255) { iv.writeUInt8(0, len) } else { item++ iv.writeUInt8(item, len) break } } } module.exports = incr32 },{}],101:[function(require,module,exports){ var xor = require('buffer-xor') exports.encrypt = function (self, block) { var data = xor(block, self._prev) self._prev = self._cipher.encryptBlock(data) return self._prev } exports.decrypt = function (self, block) { var pad = self._prev self._prev = block var out = self._cipher.decryptBlock(block) return xor(out, pad) } },{"buffer-xor":143}],102:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var xor = require('buffer-xor') function encryptStart (self, data, decrypt) { var len = data.length var out = xor(data, self._cache) self._cache = self._cache.slice(len) self._prev = Buffer.concat([self._prev, decrypt ? data : out]) return out } exports.encrypt = function (self, data, decrypt) { var out = Buffer.allocUnsafe(0) var len while (data.length) { if (self._cache.length === 0) { self._cache = self._cipher.encryptBlock(self._prev) self._prev = Buffer.allocUnsafe(0) } if (self._cache.length <= data.length) { len = self._cache.length out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) data = data.slice(len) } else { out = Buffer.concat([out, encryptStart(self, data, decrypt)]) break } } return out } },{"buffer-xor":143,"safe-buffer":537}],103:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer function encryptByte (self, byteParam, decrypt) { var pad var i = -1 var len = 8 var out = 0 var bit, value while (++i < len) { pad = self._cipher.encryptBlock(self._prev) bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 value = pad[0] ^ bit out += ((value & 0x80) >> (i % 8)) self._prev = shiftIn(self._prev, decrypt ? bit : value) } return out } function shiftIn (buffer, value) { var len = buffer.length var i = -1 var out = Buffer.allocUnsafe(buffer.length) buffer = Buffer.concat([buffer, Buffer.from([value])]) while (++i < len) { out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) } return out } exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length var out = Buffer.allocUnsafe(len) var i = -1 while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt) } return out } },{"safe-buffer":537}],104:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer function encryptByte (self, byteParam, decrypt) { var pad = self._cipher.encryptBlock(self._prev) var out = pad[0] ^ byteParam self._prev = Buffer.concat([ self._prev.slice(1), Buffer.from([decrypt ? byteParam : out]) ]) return out } exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length var out = Buffer.allocUnsafe(len) var i = -1 while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt) } return out } },{"safe-buffer":537}],105:[function(require,module,exports){ var xor = require('buffer-xor') var Buffer = require('safe-buffer').Buffer var incr32 = require('../incr32') function getBlock (self) { var out = self._cipher.encryptBlockRaw(self._prev) incr32(self._prev) return out } var blockSize = 16 exports.encrypt = function (self, chunk) { var chunkNum = Math.ceil(chunk.length / blockSize) var start = self._cache.length self._cache = Buffer.concat([ self._cache, Buffer.allocUnsafe(chunkNum * blockSize) ]) for (var i = 0; i < chunkNum; i++) { var out = getBlock(self) var offset = start + i * blockSize self._cache.writeUInt32BE(out[0], offset + 0) self._cache.writeUInt32BE(out[1], offset + 4) self._cache.writeUInt32BE(out[2], offset + 8) self._cache.writeUInt32BE(out[3], offset + 12) } var pad = self._cache.slice(0, chunk.length) self._cache = self._cache.slice(chunk.length) return xor(chunk, pad) } },{"../incr32":100,"buffer-xor":143,"safe-buffer":537}],106:[function(require,module,exports){ exports.encrypt = function (self, block) { return self._cipher.encryptBlock(block) } exports.decrypt = function (self, block) { return self._cipher.decryptBlock(block) } },{}],107:[function(require,module,exports){ var modeModules = { ECB: require('./ecb'), CBC: require('./cbc'), CFB: require('./cfb'), CFB8: require('./cfb8'), CFB1: require('./cfb1'), OFB: require('./ofb'), CTR: require('./ctr'), GCM: require('./ctr') } var modes = require('./list.json') for (var key in modes) { modes[key].module = modeModules[modes[key].mode] } module.exports = modes },{"./cbc":101,"./cfb":102,"./cfb1":103,"./cfb8":104,"./ctr":105,"./ecb":106,"./list.json":108,"./ofb":109}],108:[function(require,module,exports){ module.exports={ "aes-128-ecb": { "cipher": "AES", "key": 128, "iv": 0, "mode": "ECB", "type": "block" }, "aes-192-ecb": { "cipher": "AES", "key": 192, "iv": 0, "mode": "ECB", "type": "block" }, "aes-256-ecb": { "cipher": "AES", "key": 256, "iv": 0, "mode": "ECB", "type": "block" }, "aes-128-cbc": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" }, "aes-192-cbc": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" }, "aes-256-cbc": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" }, "aes128": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" }, "aes192": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" }, "aes256": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" }, "aes-128-cfb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB", "type": "stream" }, "aes-192-cfb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB", "type": "stream" }, "aes-256-cfb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB", "type": "stream" }, "aes-128-cfb8": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB8", "type": "stream" }, "aes-192-cfb8": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB8", "type": "stream" }, "aes-256-cfb8": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB8", "type": "stream" }, "aes-128-cfb1": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB1", "type": "stream" }, "aes-192-cfb1": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB1", "type": "stream" }, "aes-256-cfb1": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB1", "type": "stream" }, "aes-128-ofb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "OFB", "type": "stream" }, "aes-192-ofb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "OFB", "type": "stream" }, "aes-256-ofb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "OFB", "type": "stream" }, "aes-128-ctr": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CTR", "type": "stream" }, "aes-192-ctr": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CTR", "type": "stream" }, "aes-256-ctr": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CTR", "type": "stream" }, "aes-128-gcm": { "cipher": "AES", "key": 128, "iv": 12, "mode": "GCM", "type": "auth" }, "aes-192-gcm": { "cipher": "AES", "key": 192, "iv": 12, "mode": "GCM", "type": "auth" }, "aes-256-gcm": { "cipher": "AES", "key": 256, "iv": 12, "mode": "GCM", "type": "auth" } } },{}],109:[function(require,module,exports){ (function (Buffer){ var xor = require('buffer-xor') function getBlock (self) { self._prev = self._cipher.encryptBlock(self._prev) return self._prev } exports.encrypt = function (self, chunk) { while (self._cache.length < chunk.length) { self._cache = Buffer.concat([self._cache, getBlock(self)]) } var pad = self._cache.slice(0, chunk.length) self._cache = self._cache.slice(chunk.length) return xor(chunk, pad) } }).call(this,require("buffer").Buffer) },{"buffer":144,"buffer-xor":143}],110:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') var inherits = require('inherits') function StreamCipher (mode, key, iv, decrypt) { Transform.call(this) this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._cache = Buffer.allocUnsafe(0) this._secCache = Buffer.allocUnsafe(0) this._decrypt = decrypt this._mode = mode } inherits(StreamCipher, Transform) StreamCipher.prototype._update = function (chunk) { return this._mode.encrypt(this, chunk, this._decrypt) } StreamCipher.prototype._final = function () { this._cipher.scrub() } module.exports = StreamCipher },{"./aes":94,"cipher-base":145,"inherits":334,"safe-buffer":537}],111:[function(require,module,exports){ var ebtk = require('evp_bytestokey') var aes = require('browserify-aes/browser') var DES = require('browserify-des') var desModes = require('browserify-des/modes') var aesModes = require('browserify-aes/modes') function createCipher (suite, password) { var keyLen, ivLen suite = suite.toLowerCase() if (aesModes[suite]) { keyLen = aesModes[suite].key ivLen = aesModes[suite].iv } else if (desModes[suite]) { keyLen = desModes[suite].key * 8 ivLen = desModes[suite].iv } else { throw new TypeError('invalid suite type') } var keys = ebtk(password, false, keyLen, ivLen) return createCipheriv(suite, keys.key, keys.iv) } function createDecipher (suite, password) { var keyLen, ivLen suite = suite.toLowerCase() if (aesModes[suite]) { keyLen = aesModes[suite].key ivLen = aesModes[suite].iv } else if (desModes[suite]) { keyLen = desModes[suite].key * 8 ivLen = desModes[suite].iv } else { throw new TypeError('invalid suite type') } var keys = ebtk(password, false, keyLen, ivLen) return createDecipheriv(suite, keys.key, keys.iv) } function createCipheriv (suite, key, iv) { suite = suite.toLowerCase() if (aesModes[suite]) { return aes.createCipheriv(suite, key, iv) } else if (desModes[suite]) { return new DES({ key: key, iv: iv, mode: suite }) } else { throw new TypeError('invalid suite type') } } function createDecipheriv (suite, key, iv) { suite = suite.toLowerCase() if (aesModes[suite]) { return aes.createDecipheriv(suite, key, iv) } else if (desModes[suite]) { return new DES({ key: key, iv: iv, mode: suite, decrypt: true }) } else { throw new TypeError('invalid suite type') } } exports.createCipher = exports.Cipher = createCipher exports.createCipheriv = exports.Cipheriv = createCipheriv exports.createDecipher = exports.Decipher = createDecipher exports.createDecipheriv = exports.Decipheriv = createDecipheriv function getCiphers () { return Object.keys(desModes).concat(aes.getCiphers()) } exports.listCiphers = exports.getCiphers = getCiphers },{"browserify-aes/browser":96,"browserify-aes/modes":107,"browserify-des":112,"browserify-des/modes":113,"evp_bytestokey":317}],112:[function(require,module,exports){ (function (Buffer){ var CipherBase = require('cipher-base') var des = require('des.js') var inherits = require('inherits') var modes = { 'des-ede3-cbc': des.CBC.instantiate(des.EDE), 'des-ede3': des.EDE, 'des-ede-cbc': des.CBC.instantiate(des.EDE), 'des-ede': des.EDE, 'des-cbc': des.CBC.instantiate(des.DES), 'des-ecb': des.DES } modes.des = modes['des-cbc'] modes.des3 = modes['des-ede3-cbc'] module.exports = DES inherits(DES, CipherBase) function DES (opts) { CipherBase.call(this) var modeName = opts.mode.toLowerCase() var mode = modes[modeName] var type if (opts.decrypt) { type = 'decrypt' } else { type = 'encrypt' } var key = opts.key if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { key = Buffer.concat([key, key.slice(0, 8)]) } var iv = opts.iv this._des = mode.create({ key: key, iv: iv, type: type }) } DES.prototype._update = function (data) { return new Buffer(this._des.update(data)) } DES.prototype._final = function () { return new Buffer(this._des.final()) } }).call(this,require("buffer").Buffer) },{"buffer":144,"cipher-base":145,"des.js":290,"inherits":334}],113:[function(require,module,exports){ exports['des-ecb'] = { key: 8, iv: 0 } exports['des-cbc'] = exports.des = { key: 8, iv: 8 } exports['des-ede3-cbc'] = exports.des3 = { key: 24, iv: 8 } exports['des-ede3'] = { key: 24, iv: 0 } exports['des-ede-cbc'] = { key: 16, iv: 8 } exports['des-ede'] = { key: 16, iv: 0 } },{}],114:[function(require,module,exports){ (function (Buffer){ var bn = require('bn.js'); var randomBytes = require('randombytes'); module.exports = crt; function blind(priv) { var r = getr(priv); var blinder = r.toRed(bn.mont(priv.modulus)) .redPow(new bn(priv.publicExponent)).fromRed(); return { blinder: blinder, unblinder:r.invm(priv.modulus) }; } function crt(msg, priv) { var blinds = blind(priv); var len = priv.modulus.byteLength(); var mod = bn.mont(priv.modulus); var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); var c1 = blinded.toRed(bn.mont(priv.prime1)); var c2 = blinded.toRed(bn.mont(priv.prime2)); var qinv = priv.coefficient; var p = priv.prime1; var q = priv.prime2; var m1 = c1.redPow(priv.exponent1); var m2 = c2.redPow(priv.exponent2); m1 = m1.fromRed(); m2 = m2.fromRed(); var h = m1.isub(m2).imul(qinv).umod(p); h.imul(q); m2.iadd(h); return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); } crt.getr = getr; function getr(priv) { var len = priv.modulus.byteLength(); var r = new bn(randomBytes(len)); while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { r = new bn(randomBytes(len)); } return r; } }).call(this,require("buffer").Buffer) },{"bn.js":91,"buffer":144,"randombytes":518}],115:[function(require,module,exports){ module.exports = require('./browser/algorithms.json') },{"./browser/algorithms.json":116}],116:[function(require,module,exports){ module.exports={ "sha224WithRSAEncryption": { "sign": "rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" }, "RSA-SHA224": { "sign": "ecdsa/rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" }, "sha256WithRSAEncryption": { "sign": "rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" }, "RSA-SHA256": { "sign": "ecdsa/rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" }, "sha384WithRSAEncryption": { "sign": "rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" }, "RSA-SHA384": { "sign": "ecdsa/rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" }, "sha512WithRSAEncryption": { "sign": "rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" }, "RSA-SHA512": { "sign": "ecdsa/rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" }, "RSA-SHA1": { "sign": "rsa", "hash": "sha1", "id": "3021300906052b0e03021a05000414" }, "ecdsa-with-SHA1": { "sign": "ecdsa", "hash": "sha1", "id": "" }, "sha256": { "sign": "ecdsa", "hash": "sha256", "id": "" }, "sha224": { "sign": "ecdsa", "hash": "sha224", "id": "" }, "sha384": { "sign": "ecdsa", "hash": "sha384", "id": "" }, "sha512": { "sign": "ecdsa", "hash": "sha512", "id": "" }, "DSA-SHA": { "sign": "dsa", "hash": "sha1", "id": "" }, "DSA-SHA1": { "sign": "dsa", "hash": "sha1", "id": "" }, "DSA": { "sign": "dsa", "hash": "sha1", "id": "" }, "DSA-WITH-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" }, "DSA-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" }, "DSA-WITH-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" }, "DSA-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" }, "DSA-WITH-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" }, "DSA-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" }, "DSA-WITH-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" }, "DSA-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" }, "DSA-RIPEMD160": { "sign": "dsa", "hash": "rmd160", "id": "" }, "ripemd160WithRSA": { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" }, "RSA-RIPEMD160": { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" }, "md5WithRSAEncryption": { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" }, "RSA-MD5": { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" } } },{}],117:[function(require,module,exports){ module.exports={ "1.3.132.0.10": "secp256k1", "1.3.132.0.33": "p224", "1.2.840.10045.3.1.1": "p192", "1.2.840.10045.3.1.7": "p256", "1.3.132.0.34": "p384", "1.3.132.0.35": "p521" } },{}],118:[function(require,module,exports){ (function (Buffer){ var createHash = require('create-hash') var stream = require('stream') var inherits = require('inherits') var sign = require('./sign') var verify = require('./verify') var algorithms = require('./algorithms.json') Object.keys(algorithms).forEach(function (key) { algorithms[key].id = new Buffer(algorithms[key].id, 'hex') algorithms[key.toLowerCase()] = algorithms[key] }) function Sign (algorithm) { stream.Writable.call(this) var data = algorithms[algorithm] if (!data) throw new Error('Unknown message digest') this._hashType = data.hash this._hash = createHash(data.hash) this._tag = data.id this._signType = data.sign } inherits(Sign, stream.Writable) Sign.prototype._write = function _write (data, _, done) { this._hash.update(data) done() } Sign.prototype.update = function update (data, enc) { if (typeof data === 'string') data = new Buffer(data, enc) this._hash.update(data) return this } Sign.prototype.sign = function signMethod (key, enc) { this.end() var hash = this._hash.digest() var sig = sign(hash, key, this._hashType, this._signType, this._tag) return enc ? sig.toString(enc) : sig } function Verify (algorithm) { stream.Writable.call(this) var data = algorithms[algorithm] if (!data) throw new Error('Unknown message digest') this._hash = createHash(data.hash) this._tag = data.id this._signType = data.sign } inherits(Verify, stream.Writable) Verify.prototype._write = function _write (data, _, done) { this._hash.update(data) done() } Verify.prototype.update = function update (data, enc) { if (typeof data === 'string') data = new Buffer(data, enc) this._hash.update(data) return this } Verify.prototype.verify = function verifyMethod (key, sig, enc) { if (typeof sig === 'string') sig = new Buffer(sig, enc) this.end() var hash = this._hash.digest() return verify(sig, hash, key, this._signType, this._tag) } function createSign (algorithm) { return new Sign(algorithm) } function createVerify (algorithm) { return new Verify(algorithm) } module.exports = { Sign: createSign, Verify: createVerify, createSign: createSign, createVerify: createVerify } }).call(this,require("buffer").Buffer) },{"./algorithms.json":116,"./sign":119,"./verify":120,"buffer":144,"create-hash":282,"inherits":334,"stream":548}],119:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var createHmac = require('create-hmac') var crt = require('browserify-rsa') var EC = require('elliptic').ec var BN = require('bn.js') var parseKeys = require('parse-asn1') var curves = require('./curves.json') function sign (hash, key, hashType, signType, tag) { var priv = parseKeys(key) if (priv.curve) { // rsa keys can be interpreted as ecdsa ones in openssl if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') return ecSign(hash, priv) } else if (priv.type === 'dsa') { if (signType !== 'dsa') throw new Error('wrong private key type') return dsaSign(hash, priv, hashType) } else { if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') } hash = Buffer.concat([tag, hash]) var len = priv.modulus.byteLength() var pad = [ 0, 1 ] while (hash.length + pad.length + 1 < len) pad.push(0xff) pad.push(0x00) var i = -1 while (++i < hash.length) pad.push(hash[i]) var out = crt(pad, priv) return out } function ecSign (hash, priv) { var curveId = curves[priv.curve.join('.')] if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) var curve = new EC(curveId) var key = curve.keyFromPrivate(priv.privateKey) var out = key.sign(hash) return new Buffer(out.toDER()) } function dsaSign (hash, priv, algo) { var x = priv.params.priv_key var p = priv.params.p var q = priv.params.q var g = priv.params.g var r = new BN(0) var k var H = bits2int(hash, q).mod(q) var s = false var kv = getKey(x, q, hash, algo) while (s === false) { k = makeKey(q, kv, algo) r = makeR(g, k, p, q) s = k.invm(q).imul(H.add(x.mul(r))).mod(q) if (s.cmpn(0) === 0) { s = false r = new BN(0) } } return toDER(r, s) } function toDER (r, s) { r = r.toArray() s = s.toArray() // Pad values if (r[0] & 0x80) r = [ 0 ].concat(r) if (s[0] & 0x80) s = [ 0 ].concat(s) var total = r.length + s.length + 4 var res = [ 0x30, total, 0x02, r.length ] res = res.concat(r, [ 0x02, s.length ], s) return new Buffer(res) } function getKey (x, q, hash, algo) { x = new Buffer(x.toArray()) if (x.length < q.byteLength()) { var zeros = new Buffer(q.byteLength() - x.length) zeros.fill(0) x = Buffer.concat([ zeros, x ]) } var hlen = hash.length var hbits = bits2octets(hash, q) var v = new Buffer(hlen) v.fill(1) var k = new Buffer(hlen) k.fill(0) k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest() v = createHmac(algo, k).update(v).digest() k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest() v = createHmac(algo, k).update(v).digest() return { k: k, v: v } } function bits2int (obits, q) { var bits = new BN(obits) var shift = (obits.length << 3) - q.bitLength() if (shift > 0) bits.ishrn(shift) return bits } function bits2octets (bits, q) { bits = bits2int(bits, q) bits = bits.mod(q) var out = new Buffer(bits.toArray()) if (out.length < q.byteLength()) { var zeros = new Buffer(q.byteLength() - out.length) zeros.fill(0) out = Buffer.concat([ zeros, out ]) } return out } function makeKey (q, kv, algo) { var t var k do { t = new Buffer(0) while (t.length * 8 < q.bitLength()) { kv.v = createHmac(algo, kv.k).update(kv.v).digest() t = Buffer.concat([ t, kv.v ]) } k = bits2int(t, q) kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest() kv.v = createHmac(algo, kv.k).update(kv.v).digest() } while (k.cmp(q) !== -1) return k } function makeR (g, k, p, q) { return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q) } module.exports = sign module.exports.getKey = getKey module.exports.makeKey = makeKey }).call(this,require("buffer").Buffer) },{"./curves.json":117,"bn.js":91,"browserify-rsa":114,"buffer":144,"create-hmac":285,"elliptic":300,"parse-asn1":499}],120:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var BN = require('bn.js') var EC = require('elliptic').ec var parseKeys = require('parse-asn1') var curves = require('./curves.json') function verify (sig, hash, key, signType, tag) { var pub = parseKeys(key) if (pub.type === 'ec') { // rsa keys can be interpreted as ecdsa ones in openssl if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') return ecVerify(sig, hash, pub) } else if (pub.type === 'dsa') { if (signType !== 'dsa') throw new Error('wrong public key type') return dsaVerify(sig, hash, pub) } else { if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') } hash = Buffer.concat([tag, hash]) var len = pub.modulus.byteLength() var pad = [ 1 ] var padNum = 0 while (hash.length + pad.length + 2 < len) { pad.push(0xff) padNum++ } pad.push(0x00) var i = -1 while (++i < hash.length) { pad.push(hash[i]) } pad = new Buffer(pad) var red = BN.mont(pub.modulus) sig = new BN(sig).toRed(red) sig = sig.redPow(new BN(pub.publicExponent)) sig = new Buffer(sig.fromRed().toArray()) var out = padNum < 8 ? 1 : 0 len = Math.min(sig.length, pad.length) if (sig.length !== pad.length) out = 1 i = -1 while (++i < len) out |= sig[i] ^ pad[i] return out === 0 } function ecVerify (sig, hash, pub) { var curveId = curves[pub.data.algorithm.curve.join('.')] if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')) var curve = new EC(curveId) var pubkey = pub.data.subjectPrivateKey.data return curve.verify(hash, sig, pubkey) } function dsaVerify (sig, hash, pub) { var p = pub.data.p var q = pub.data.q var g = pub.data.g var y = pub.data.pub_key var unpacked = parseKeys.signature.decode(sig, 'der') var s = unpacked.s var r = unpacked.r checkValue(s, q) checkValue(r, q) var montp = BN.mont(p) var w = s.invm(q) var v = g.toRed(montp) .redPow(new BN(hash).mul(w).mod(q)) .fromRed() .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) .mod(p) .mod(q) return v.cmp(r) === 0 } function checkValue (b, q) { if (b.cmpn(0) <= 0) throw new Error('invalid sig') if (b.cmp(q) >= q) throw new Error('invalid sig') } module.exports = verify }).call(this,require("buffer").Buffer) },{"./curves.json":117,"bn.js":91,"buffer":144,"elliptic":300,"parse-asn1":499}],121:[function(require,module,exports){ (function (process,Buffer){ 'use strict'; /* eslint camelcase: "off" */ var assert = require('assert'); var Zstream = require('pako/lib/zlib/zstream'); var zlib_deflate = require('pako/lib/zlib/deflate.js'); var zlib_inflate = require('pako/lib/zlib/inflate.js'); var constants = require('pako/lib/zlib/constants'); for (var key in constants) { exports[key] = constants[key]; } // zlib modes exports.NONE = 0; exports.DEFLATE = 1; exports.INFLATE = 2; exports.GZIP = 3; exports.GUNZIP = 4; exports.DEFLATERAW = 5; exports.INFLATERAW = 6; exports.UNZIP = 7; var GZIP_HEADER_ID1 = 0x1f; var GZIP_HEADER_ID2 = 0x8b; /** * Emulate Node's zlib C++ layer for use by the JS layer in index.js */ function Zlib(mode) { if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { throw new TypeError('Bad argument'); } this.dictionary = null; this.err = 0; this.flush = 0; this.init_done = false; this.level = 0; this.memLevel = 0; this.mode = mode; this.strategy = 0; this.windowBits = 0; this.write_in_progress = false; this.pending_close = false; this.gzip_id_bytes_read = 0; } Zlib.prototype.close = function () { if (this.write_in_progress) { this.pending_close = true; return; } this.pending_close = false; assert(this.init_done, 'close before init'); assert(this.mode <= exports.UNZIP); if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { zlib_deflate.deflateEnd(this.strm); } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { zlib_inflate.inflateEnd(this.strm); } this.mode = exports.NONE; this.dictionary = null; }; Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) { return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); }; Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) { return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); }; Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) { assert.equal(arguments.length, 8); assert(this.init_done, 'write before init'); assert(this.mode !== exports.NONE, 'already finalized'); assert.equal(false, this.write_in_progress, 'write already in progress'); assert.equal(false, this.pending_close, 'close is pending'); this.write_in_progress = true; assert.equal(false, flush === undefined, 'must provide flush value'); this.write_in_progress = true; if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { throw new Error('Invalid flush value'); } if (input == null) { input = Buffer.alloc(0); in_len = 0; in_off = 0; } this.strm.avail_in = in_len; this.strm.input = input; this.strm.next_in = in_off; this.strm.avail_out = out_len; this.strm.output = out; this.strm.next_out = out_off; this.flush = flush; if (!async) { // sync version this._process(); if (this._checkError()) { return this._afterSync(); } return; } // async version var self = this; process.nextTick(function () { self._process(); self._after(); }); return this; }; Zlib.prototype._afterSync = function () { var avail_out = this.strm.avail_out; var avail_in = this.strm.avail_in; this.write_in_progress = false; return [avail_in, avail_out]; }; Zlib.prototype._process = function () { var next_expected_header_byte = null; // If the avail_out is left at 0, then it means that it ran out // of room. If there was avail_out left over, then it means // that all of the input was consumed. switch (this.mode) { case exports.DEFLATE: case exports.GZIP: case exports.DEFLATERAW: this.err = zlib_deflate.deflate(this.strm, this.flush); break; case exports.UNZIP: if (this.strm.avail_in > 0) { next_expected_header_byte = this.strm.next_in; } switch (this.gzip_id_bytes_read) { case 0: if (next_expected_header_byte === null) { break; } if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { this.gzip_id_bytes_read = 1; next_expected_header_byte++; if (this.strm.avail_in === 1) { // The only available byte was already read. break; } } else { this.mode = exports.INFLATE; break; } // fallthrough case 1: if (next_expected_header_byte === null) { break; } if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { this.gzip_id_bytes_read = 2; this.mode = exports.GUNZIP; } else { // There is no actual difference between INFLATE and INFLATERAW // (after initialization). this.mode = exports.INFLATE; } break; default: throw new Error('invalid number of gzip magic number bytes read'); } // fallthrough case exports.INFLATE: case exports.GUNZIP: case exports.INFLATERAW: this.err = zlib_inflate.inflate(this.strm, this.flush // If data was encoded with dictionary );if (this.err === exports.Z_NEED_DICT && this.dictionary) { // Load it this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); if (this.err === exports.Z_OK) { // And try to decode again this.err = zlib_inflate.inflate(this.strm, this.flush); } else if (this.err === exports.Z_DATA_ERROR) { // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR. // Make it possible for After() to tell a bad dictionary from bad // input. this.err = exports.Z_NEED_DICT; } } while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) { // Bytes remain in input buffer. Perhaps this is another compressed // member in the same archive, or just trailing garbage. // Trailing zero bytes are okay, though, since they are frequently // used for padding. this.reset(); this.err = zlib_inflate.inflate(this.strm, this.flush); } break; default: throw new Error('Unknown mode ' + this.mode); } }; Zlib.prototype._checkError = function () { // Acceptable error states depend on the type of zlib stream. switch (this.err) { case exports.Z_OK: case exports.Z_BUF_ERROR: if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { this._error('unexpected end of file'); return false; } break; case exports.Z_STREAM_END: // normal statuses, not fatal break; case exports.Z_NEED_DICT: if (this.dictionary == null) { this._error('Missing dictionary'); } else { this._error('Bad dictionary'); } return false; default: // something else. this._error('Zlib error'); return false; } return true; }; Zlib.prototype._after = function () { if (!this._checkError()) { return; } var avail_out = this.strm.avail_out; var avail_in = this.strm.avail_in; this.write_in_progress = false; // call the write() cb this.callback(avail_in, avail_out); if (this.pending_close) { this.close(); } }; Zlib.prototype._error = function (message) { if (this.strm.msg) { message = this.strm.msg; } this.onerror(message, this.err // no hope of rescue. );this.write_in_progress = false; if (this.pending_close) { this.close(); } }; Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) { assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])'); assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits'); assert(level >= -1 && level <= 9, 'invalid compression level'); assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel'); assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy'); this._init(level, windowBits, memLevel, strategy, dictionary); this._setDictionary(); }; Zlib.prototype.params = function () { throw new Error('deflateParams Not supported'); }; Zlib.prototype.reset = function () { this._reset(); this._setDictionary(); }; Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) { this.level = level; this.windowBits = windowBits; this.memLevel = memLevel; this.strategy = strategy; this.flush = exports.Z_NO_FLUSH; this.err = exports.Z_OK; if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { this.windowBits += 16; } if (this.mode === exports.UNZIP) { this.windowBits += 32; } if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { this.windowBits = -1 * this.windowBits; } this.strm = new Zstream(); switch (this.mode) { case exports.DEFLATE: case exports.GZIP: case exports.DEFLATERAW: this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); break; case exports.INFLATE: case exports.GUNZIP: case exports.INFLATERAW: case exports.UNZIP: this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); break; default: throw new Error('Unknown mode ' + this.mode); } if (this.err !== exports.Z_OK) { this._error('Init error'); } this.dictionary = dictionary; this.write_in_progress = false; this.init_done = true; }; Zlib.prototype._setDictionary = function () { if (this.dictionary == null) { return; } this.err = exports.Z_OK; switch (this.mode) { case exports.DEFLATE: case exports.DEFLATERAW: this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); break; default: break; } if (this.err !== exports.Z_OK) { this._error('Failed to set dictionary'); } }; Zlib.prototype._reset = function () { this.err = exports.Z_OK; switch (this.mode) { case exports.DEFLATE: case exports.DEFLATERAW: case exports.GZIP: this.err = zlib_deflate.deflateReset(this.strm); break; case exports.INFLATE: case exports.INFLATERAW: case exports.GUNZIP: this.err = zlib_inflate.inflateReset(this.strm); break; default: break; } if (this.err !== exports.Z_OK) { this._error('Failed to reset stream'); } }; exports.Zlib = Zlib; }).call(this,require('_process'),require("buffer").Buffer) },{"_process":507,"assert":88,"buffer":144,"pako/lib/zlib/constants":486,"pako/lib/zlib/deflate.js":488,"pako/lib/zlib/inflate.js":490,"pako/lib/zlib/zstream":494}],122:[function(require,module,exports){ (function (process){ 'use strict'; var Buffer = require('buffer').Buffer; var Transform = require('stream').Transform; var binding = require('./binding'); var util = require('util'); var assert = require('assert').ok; var kMaxLength = require('buffer').kMaxLength; var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes'; // zlib doesn't provide these, so kludge them in following the same // const naming scheme zlib uses. binding.Z_MIN_WINDOWBITS = 8; binding.Z_MAX_WINDOWBITS = 15; binding.Z_DEFAULT_WINDOWBITS = 15; // fewer than 64 bytes per chunk is stupid. // technically it could work with as few as 8, but even 64 bytes // is absurdly low. Usually a MB or more is best. binding.Z_MIN_CHUNK = 64; binding.Z_MAX_CHUNK = Infinity; binding.Z_DEFAULT_CHUNK = 16 * 1024; binding.Z_MIN_MEMLEVEL = 1; binding.Z_MAX_MEMLEVEL = 9; binding.Z_DEFAULT_MEMLEVEL = 8; binding.Z_MIN_LEVEL = -1; binding.Z_MAX_LEVEL = 9; binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; // expose all the zlib constants var bkeys = Object.keys(binding); for (var bk = 0; bk < bkeys.length; bk++) { var bkey = bkeys[bk]; if (bkey.match(/^Z/)) { Object.defineProperty(exports, bkey, { enumerable: true, value: binding[bkey], writable: false }); } } // translation table for return codes. var codes = { Z_OK: binding.Z_OK, Z_STREAM_END: binding.Z_STREAM_END, Z_NEED_DICT: binding.Z_NEED_DICT, Z_ERRNO: binding.Z_ERRNO, Z_STREAM_ERROR: binding.Z_STREAM_ERROR, Z_DATA_ERROR: binding.Z_DATA_ERROR, Z_MEM_ERROR: binding.Z_MEM_ERROR, Z_BUF_ERROR: binding.Z_BUF_ERROR, Z_VERSION_ERROR: binding.Z_VERSION_ERROR }; var ckeys = Object.keys(codes); for (var ck = 0; ck < ckeys.length; ck++) { var ckey = ckeys[ck]; codes[codes[ckey]] = ckey; } Object.defineProperty(exports, 'codes', { enumerable: true, value: Object.freeze(codes), writable: false }); exports.Deflate = Deflate; exports.Inflate = Inflate; exports.Gzip = Gzip; exports.Gunzip = Gunzip; exports.DeflateRaw = DeflateRaw; exports.InflateRaw = InflateRaw; exports.Unzip = Unzip; exports.createDeflate = function (o) { return new Deflate(o); }; exports.createInflate = function (o) { return new Inflate(o); }; exports.createDeflateRaw = function (o) { return new DeflateRaw(o); }; exports.createInflateRaw = function (o) { return new InflateRaw(o); }; exports.createGzip = function (o) { return new Gzip(o); }; exports.createGunzip = function (o) { return new Gunzip(o); }; exports.createUnzip = function (o) { return new Unzip(o); }; // Convenience methods. // compress/decompress a string or buffer in one step. exports.deflate = function (buffer, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } return zlibBuffer(new Deflate(opts), buffer, callback); }; exports.deflateSync = function (buffer, opts) { return zlibBufferSync(new Deflate(opts), buffer); }; exports.gzip = function (buffer, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } return zlibBuffer(new Gzip(opts), buffer, callback); }; exports.gzipSync = function (buffer, opts) { return zlibBufferSync(new Gzip(opts), buffer); }; exports.deflateRaw = function (buffer, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } return zlibBuffer(new DeflateRaw(opts), buffer, callback); }; exports.deflateRawSync = function (buffer, opts) { return zlibBufferSync(new DeflateRaw(opts), buffer); }; exports.unzip = function (buffer, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } return zlibBuffer(new Unzip(opts), buffer, callback); }; exports.unzipSync = function (buffer, opts) { return zlibBufferSync(new Unzip(opts), buffer); }; exports.inflate = function (buffer, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } return zlibBuffer(new Inflate(opts), buffer, callback); }; exports.inflateSync = function (buffer, opts) { return zlibBufferSync(new Inflate(opts), buffer); }; exports.gunzip = function (buffer, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } return zlibBuffer(new Gunzip(opts), buffer, callback); }; exports.gunzipSync = function (buffer, opts) { return zlibBufferSync(new Gunzip(opts), buffer); }; exports.inflateRaw = function (buffer, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } return zlibBuffer(new InflateRaw(opts), buffer, callback); }; exports.inflateRawSync = function (buffer, opts) { return zlibBufferSync(new InflateRaw(opts), buffer); }; function zlibBuffer(engine, buffer, callback) { var buffers = []; var nread = 0; engine.on('error', onError); engine.on('end', onEnd); engine.end(buffer); flow(); function flow() { var chunk; while (null !== (chunk = engine.read())) { buffers.push(chunk); nread += chunk.length; } engine.once('readable', flow); } function onError(err) { engine.removeListener('end', onEnd); engine.removeListener('readable', flow); callback(err); } function onEnd() { var buf; var err = null; if (nread >= kMaxLength) { err = new RangeError(kRangeErrorMessage); } else { buf = Buffer.concat(buffers, nread); } buffers = []; engine.close(); callback(err, buf); } } function zlibBufferSync(engine, buffer) { if (typeof buffer === 'string') buffer = Buffer.from(buffer); if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer'); var flushFlag = engine._finishFlushFlag; return engine._processChunk(buffer, flushFlag); } // generic zlib // minimal 2-byte header function Deflate(opts) { if (!(this instanceof Deflate)) return new Deflate(opts); Zlib.call(this, opts, binding.DEFLATE); } function Inflate(opts) { if (!(this instanceof Inflate)) return new Inflate(opts); Zlib.call(this, opts, binding.INFLATE); } // gzip - bigger header, same deflate compression function Gzip(opts) { if (!(this instanceof Gzip)) return new Gzip(opts); Zlib.call(this, opts, binding.GZIP); } function Gunzip(opts) { if (!(this instanceof Gunzip)) return new Gunzip(opts); Zlib.call(this, opts, binding.GUNZIP); } // raw - no header function DeflateRaw(opts) { if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); Zlib.call(this, opts, binding.DEFLATERAW); } function InflateRaw(opts) { if (!(this instanceof InflateRaw)) return new InflateRaw(opts); Zlib.call(this, opts, binding.INFLATERAW); } // auto-detect header. function Unzip(opts) { if (!(this instanceof Unzip)) return new Unzip(opts); Zlib.call(this, opts, binding.UNZIP); } function isValidFlushFlag(flag) { return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK; } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. function Zlib(opts, mode) { var _this = this; this._opts = opts = opts || {}; this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; Transform.call(this, opts); if (opts.flush && !isValidFlushFlag(opts.flush)) { throw new Error('Invalid flush flag: ' + opts.flush); } if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { throw new Error('Invalid flush flag: ' + opts.finishFlush); } this._flushFlag = opts.flush || binding.Z_NO_FLUSH; this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH; if (opts.chunkSize) { if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { throw new Error('Invalid chunk size: ' + opts.chunkSize); } } if (opts.windowBits) { if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { throw new Error('Invalid windowBits: ' + opts.windowBits); } } if (opts.level) { if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { throw new Error('Invalid compression level: ' + opts.level); } } if (opts.memLevel) { if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { throw new Error('Invalid memLevel: ' + opts.memLevel); } } if (opts.strategy) { if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { throw new Error('Invalid strategy: ' + opts.strategy); } } if (opts.dictionary) { if (!Buffer.isBuffer(opts.dictionary)) { throw new Error('Invalid dictionary: it should be a Buffer instance'); } } this._handle = new binding.Zlib(mode); var self = this; this._hadError = false; this._handle.onerror = function (message, errno) { // there is no way to cleanly recover. // continuing only obscures problems. _close(self); self._hadError = true; var error = new Error(message); error.errno = errno; error.code = exports.codes[errno]; self.emit('error', error); }; var level = exports.Z_DEFAULT_COMPRESSION; if (typeof opts.level === 'number') level = opts.level; var strategy = exports.Z_DEFAULT_STRATEGY; if (typeof opts.strategy === 'number') strategy = opts.strategy; this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); this._buffer = Buffer.allocUnsafe(this._chunkSize); this._offset = 0; this._level = level; this._strategy = strategy; this.once('end', this.close); Object.defineProperty(this, '_closed', { get: function () { return !_this._handle; }, configurable: true, enumerable: true }); } util.inherits(Zlib, Transform); Zlib.prototype.params = function (level, strategy, callback) { if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { throw new RangeError('Invalid compression level: ' + level); } if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { throw new TypeError('Invalid strategy: ' + strategy); } if (this._level !== level || this._strategy !== strategy) { var self = this; this.flush(binding.Z_SYNC_FLUSH, function () { assert(self._handle, 'zlib binding closed'); self._handle.params(level, strategy); if (!self._hadError) { self._level = level; self._strategy = strategy; if (callback) callback(); } }); } else { process.nextTick(callback); } }; Zlib.prototype.reset = function () { assert(this._handle, 'zlib binding closed'); return this._handle.reset(); }; // This is the _flush function called by the transform class, // internally, when the last chunk has been written. Zlib.prototype._flush = function (callback) { this._transform(Buffer.alloc(0), '', callback); }; Zlib.prototype.flush = function (kind, callback) { var _this2 = this; var ws = this._writableState; if (typeof kind === 'function' || kind === undefined && !callback) { callback = kind; kind = binding.Z_FULL_FLUSH; } if (ws.ended) { if (callback) process.nextTick(callback); } else if (ws.ending) { if (callback) this.once('end', callback); } else if (ws.needDrain) { if (callback) { this.once('drain', function () { return _this2.flush(kind, callback); }); } } else { this._flushFlag = kind; this.write(Buffer.alloc(0), '', callback); } }; Zlib.prototype.close = function (callback) { _close(this, callback); process.nextTick(emitCloseNT, this); }; function _close(engine, callback) { if (callback) process.nextTick(callback); // Caller may invoke .close after a zlib error (which will null _handle). if (!engine._handle) return; engine._handle.close(); engine._handle = null; } function emitCloseNT(self) { self.emit('close'); } Zlib.prototype._transform = function (chunk, encoding, cb) { var flushFlag; var ws = this._writableState; var ending = ws.ending || ws.ended; var last = ending && (!chunk || ws.length === chunk.length); if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); if (!this._handle) return cb(new Error('zlib binding closed')); // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag // (or whatever flag was provided using opts.finishFlush). // If it's explicitly flushing at some other time, then we use // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression // goodness. if (last) flushFlag = this._finishFlushFlag;else { flushFlag = this._flushFlag; // once we've flushed the last of the queue, stop flushing and // go back to the normal behavior. if (chunk.length >= ws.length) { this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; } } this._processChunk(chunk, flushFlag, cb); }; Zlib.prototype._processChunk = function (chunk, flushFlag, cb) { var availInBefore = chunk && chunk.length; var availOutBefore = this._chunkSize - this._offset; var inOff = 0; var self = this; var async = typeof cb === 'function'; if (!async) { var buffers = []; var nread = 0; var error; this.on('error', function (er) { error = er; }); assert(this._handle, 'zlib binding closed'); do { var res = this._handle.writeSync(flushFlag, chunk, // in inOff, // in_off availInBefore, // in_len this._buffer, // out this._offset, //out_off availOutBefore); // out_len } while (!this._hadError && callback(res[0], res[1])); if (this._hadError) { throw error; } if (nread >= kMaxLength) { _close(this); throw new RangeError(kRangeErrorMessage); } var buf = Buffer.concat(buffers, nread); _close(this); return buf; } assert(this._handle, 'zlib binding closed'); var req = this._handle.write(flushFlag, chunk, // in inOff, // in_off availInBefore, // in_len this._buffer, // out this._offset, //out_off availOutBefore); // out_len req.buffer = chunk; req.callback = callback; function callback(availInAfter, availOutAfter) { // When the callback is used in an async write, the callback's // context is the `req` object that was created. The req object // is === this._handle, and that's why it's important to null // out the values after they are done being used. `this._handle` // can stay in memory longer than the callback and buffer are needed. if (this) { this.buffer = null; this.callback = null; } if (self._hadError) return; var have = availOutBefore - availOutAfter; assert(have >= 0, 'have should not go down'); if (have > 0) { var out = self._buffer.slice(self._offset, self._offset + have); self._offset += have; // serve some output to the consumer. if (async) { self.push(out); } else { buffers.push(out); nread += out.length; } } // exhausted the output buffer, or used all the input create a new one. if (availOutAfter === 0 || self._offset >= self._chunkSize) { availOutBefore = self._chunkSize; self._offset = 0; self._buffer = Buffer.allocUnsafe(self._chunkSize); } if (availOutAfter === 0) { // Not actually done. Need to reprocess. // Also, update the availInBefore to the availInAfter value, // so that if we have to hit it a third (fourth, etc.) time, // it'll have the correct byte counts. inOff += availInBefore - availInAfter; availInBefore = availInAfter; if (!async) return true; var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); newReq.callback = callback; // this same function newReq.buffer = chunk; return; } if (!async) return false; // finished with the chunk. cb(); } }; util.inherits(Deflate, Zlib); util.inherits(Inflate, Zlib); util.inherits(Gzip, Zlib); util.inherits(Gunzip, Zlib); util.inherits(DeflateRaw, Zlib); util.inherits(InflateRaw, Zlib); util.inherits(Unzip, Zlib); }).call(this,require('_process')) },{"./binding":121,"_process":507,"assert":88,"buffer":144,"stream":548,"util":563}],123:[function(require,module,exports){ arguments[4][93][0].apply(exports,arguments) },{"dup":93}],124:[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 } /** * 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); 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 = new Buffer(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 = new Buffer(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 = new Buffer(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 = new Buffer(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 : {}) },{"buffer":144}],125:[function(require,module,exports){ (function (Buffer){ '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'); /** * @ignore * @api private */ // Max Size var MAXSIZE = 1024 * 1024 * 17; // Max Document Buffer size var buffer = new Buffer(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)**. * @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; // Attempt to serialize var serializationIndex = serializer( buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, [] ); // Create the final buffer var finishedBuffer = new Buffer(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( buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined ); buffer.copy(finalBuffer, startIndex, 0, serializationIndex); // 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; }).call(this,require("buffer").Buffer) },{"./binary":124,"./code":126,"./db_ref":127,"./decimal128":128,"./double":129,"./int_32":131,"./long":132,"./map":133,"./max_key":134,"./min_key":135,"./objectid":136,"./parser/calculate_size":137,"./parser/deserializer":138,"./parser/serializer":139,"./regexp":140,"./symbol":141,"./timestamp":142,"buffer":144}],126:[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; },{}],127:[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; },{}],128:[function(require,module,exports){ (function (Buffer){ '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+)?$/; // 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 = new Buffer(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 = new Buffer(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(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); } else if (string[index] === 'N') { return new Decimal128(new Buffer(NAN_BUFFER)); } } // Read all the digits while (isDigit(string[index]) || string[index] === '.') { if (string[index] === '.') { if (sawRadix) { return new Decimal128(new Buffer(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(new Buffer(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(new Buffer(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(new Buffer(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(new Buffer(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( new Buffer(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 = new Buffer(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; }).call(this,require("buffer").Buffer) },{"./long":132,"buffer":144}],129:[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; },{}],130:[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; },{}],131:[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; },{}],132:[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; },{}],133:[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 : {}) },{}],134:[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; },{}],135:[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; },{}],136:[function(require,module,exports){ (function (process,Buffer){ /** * 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; } 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(new Buffer(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 = new Buffer(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 = new Buffer([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(new Buffer(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) },{"_process":507,"buffer":144}],137:[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; // 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') { 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(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) ); } else if (serializeFunctions) { return ( (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.toString(), '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":124,"../code":126,"../db_ref":127,"../decimal128":128,"../double":129,"../long":132,"../max_key":134,"../min_key":135,"../objectid":136,"../regexp":140,"../symbol":141,"../timestamp":142,"buffer":144}],138:[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, 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 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 = new Buffer(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 = new Buffer(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 = new Buffer(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; }).call(this,require("buffer").Buffer) },{"../binary":124,"../code":126,"../db_ref":127,"../decimal128":128,"../double":129,"../int_32":131,"../long":132,"../max_key":134,"../min_key":135,"../objectid":136,"../regexp":140,"../symbol":141,"../timestamp":142,"buffer":144}],139:[function(require,module,exports){ (function (Buffer){ 'use strict'; var writeIEEE754 = require('../float_parser').writeIEEE754, Long = require('../long').Long, MinKey = require('../min_key').MinKey, Map = require('../map'), Binary = require('../binary').Binary; // try { // var _Buffer = Uint8Array; // } catch (e) { // _Buffer = Buffer; // } var regexp = /\x00/; // eslint-disable-line no-control-regex // 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 instanceof 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 = value.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 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') { 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 (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 (key !== '$db' && key !== '$ref' && key !== '$id') { 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') { 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 { // 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 (key !== '$db' && key !== '$ref' && key !== '$id') { 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') { 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); } } } // 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":335,"../binary":124,"../float_parser":130,"../long":132,"../map":133,"../min_key":135}],140:[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; },{}],141:[function(require,module,exports){ /** * 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; },{}],142:[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; },{}],143:[function(require,module,exports){ (function (Buffer){ module.exports = function xor (a, b) { var length = Math.min(a.length, b.length) var buffer = new Buffer(length) for (var i = 0; i < length; ++i) { buffer[i] = a[i] ^ b[i] } return buffer } }).call(this,require("buffer").Buffer) },{"buffer":144}],144:[function(require,module,exports){ /*! * 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', { get: function () { if (!(this instanceof Buffer)) { return undefined } return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { get: function () { if (!(this instanceof Buffer)) { return undefined } return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('Invalid typed array length') } // 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 Error( 'If encoding is specified then the first argument must be a string' ) } 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 && 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 === 'number') { throw new TypeError('"value" argument must not be a number') } if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return fromObject(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('"size" argument must not be negative') } } 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) { if (ArrayBuffer.isView(obj) || 'length' in obj) { 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) } } throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.') } 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 } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } 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 (ArrayBuffer.isView(buf)) { 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) || isArrayBuffer(string)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (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': case undefined: 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 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 if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } 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 : new Buffer(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 } // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 function isArrayBuffer (obj) { return obj instanceof ArrayBuffer || (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && typeof obj.byteLength === 'number') } function numberIsNaN (obj) { return obj !== obj // eslint-disable-line no-self-compare } },{"base64-js":89,"ieee754":332}],145:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var Transform = require('stream').Transform var StringDecoder = require('string_decoder').StringDecoder var inherits = require('inherits') function CipherBase (hashMode) { Transform.call(this) this.hashMode = typeof hashMode === 'string' if (this.hashMode) { this[hashMode] = this._finalOrDigest } else { this.final = this._finalOrDigest } if (this._final) { this.__final = this._final this._final = null } this._decoder = null this._encoding = null } inherits(CipherBase, Transform) CipherBase.prototype.update = function (data, inputEnc, outputEnc) { if (typeof data === 'string') { data = Buffer.from(data, inputEnc) } var outData = this._update(data) if (this.hashMode) return this if (outputEnc) { outData = this._toString(outData, outputEnc) } return outData } CipherBase.prototype.setAutoPadding = function () {} CipherBase.prototype.getAuthTag = function () { throw new Error('trying to get auth tag in unsupported state') } CipherBase.prototype.setAuthTag = function () { throw new Error('trying to set auth tag in unsupported state') } CipherBase.prototype.setAAD = function () { throw new Error('trying to set aad in unsupported state') } CipherBase.prototype._transform = function (data, _, next) { var err try { if (this.hashMode) { this._update(data) } else { this.push(this._update(data)) } } catch (e) { err = e } finally { next(err) } } CipherBase.prototype._flush = function (done) { var err try { this.push(this.__final()) } catch (e) { err = e } done(err) } CipherBase.prototype._finalOrDigest = function (outputEnc) { var outData = this.__final() || Buffer.alloc(0) if (outputEnc) { outData = this._toString(outData, outputEnc, true) } return outData } CipherBase.prototype._toString = function (value, enc, fin) { if (!this._decoder) { this._decoder = new StringDecoder(enc) this._encoding = enc } if (this._encoding !== enc) throw new Error('can\'t switch encodings') var out = this._decoder.write(value) if (fin) { out += this._decoder.end() } return out } module.exports = CipherBase },{"inherits":334,"safe-buffer":537,"stream":548,"string_decoder":549}],146:[function(require,module,exports){ (function (Buffer){ // 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. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } 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 objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (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 = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":335}],147:[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":152}],148:[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":152}],149:[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":152,"./fhir/models":235,"./util/util":280}],150:[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.Context = context.Context; module.exports.PatientContext = context.PatientContext; module.exports.PopulationContext = context.PopulationContext; module.exports.Executor = exec.Executor; module.exports.Results = results.Results; module.exports.Code = datatypes.Code; module.exports.Quantity = quantity.Quantity; module.exports.Expression = expression.Expression; module.exports.ValueSet = datatypes.ValueSet; module.exports.DateTime = datatypes.DateTime; module.exports.Interval = datatypes.Interval; module.exports.Patient = patient.Patient; module.exports.PatientSource = patient.PatientSource; module.exports.CodeService = codeservice.CodeService; }).call(this); },{"./cql-code-service":147,"./cql-patient":149,"./datatypes/datatypes":152,"./elm/expression":166,"./elm/library":171,"./elm/quantity":178,"./runtime/context":274,"./runtime/executor":275,"./runtime/repository":276,"./runtime/results":277}],151:[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; } Code.prototype.hasMatch = function(code) { return codesInList(toCodeList(code), [this]); }; return Code; })(); module.exports.Concept = Concept = (function() { function Concept(codes, display) { this.codes = codes != null ? codes : []; this.display = display; } 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 : []; } ValueSet.prototype.hasMatch = function(code) { return codesInList(toCodeList(code), 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 if (typeof c === 'string') { return [new Code(c)]; } else { return [c]; } }; codesInList = function(cl1, cl2) { return cl1.some(function(c1) { return cl2.some(function(c2) { return codesMatch(c1, c2); }); }); }; codesMatch = function(code1, code2) { if (code1.code !== code2.code) { return false; } if ((code1.system != null) && (code2.system != null) && code1.system !== code2.system) { return false; } return true; }; module.exports.CodeSystem = CodeSystem = (function() { function CodeSystem(id, version) { this.id = id; this.version = version; } return CodeSystem; })(); }).call(this); },{"../util/util":280}],152:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var clinical, datetime, element, i, interval, j, len, len1, lib, libs, logic, ref, uncertainty; logic = require('./logic'); clinical = require('./clinical'); uncertainty = require('./uncertainty'); datetime = require('./datetime'); interval = require('./interval'); libs = [logic, clinical, uncertainty, datetime, interval]; 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":151,"./datetime":153,"./interval":155,"./logic":156,"./uncertainty":157}],153:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DateTime, Uncertainty, moment; Uncertainty = require('./uncertainty').Uncertainty; moment = require('moment'); module.exports.DateTime = DateTime = (function() { 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, match, num, regex; match = regex = /(\d{4})(-(\d{2}))?(-(\d{2}))?(T((\d{2})(\:(\d{2})(\:(\d{2})(\.(\d+))?)?)?)?(([+-])(\d{2})(\:?(\d{2}))?)?)?/.exec(string); if ((match != null ? match[0] : void 0) === string) { args = [match[1], match[3], match[5], match[8], match[10], match[12], match[14]]; if (args[6] != null) { args[6] = (args[6] + "00").substring(0, 3); } 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 (match[17] != null) { num = parseInt(match[17], 10) + (match[19] != null ? parseInt(match[19], 10) / 60 : 0); args.push(match[16] === '+' ? num : num * -1); } 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(){}); } else { return null; } }; DateTime.fromDate = function(date, timezoneOffset) { if (timezoneOffset != null) { date = new Date(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(year, month, day, hour, minute, second, millisecond, timezoneOffset1) { this.year = year != null ? year : null; this.month = month != null ? month : 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 (this.timezoneOffset == null) { this.timezoneOffset = (new Date()).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.fromDate(this.toJSDate(), timezoneOffset); return d.reducedPrecision(this.getPrecision()); }; DateTime.prototype.sameAs = function(other, precision) { var diff; if (precision == null) { precision = DateTime.Unit.MILLISECOND; } if (!(other instanceof DateTime)) { null; } diff = this.differenceBetween(other, precision); switch (false) { case !(diff.low === 0 && diff.high === 0): return true; case !(diff.low <= 0 && diff.high >= 0): return null; default: return false; } }; DateTime.prototype.equals = function(other) { return this.sameAs(other, DateTime.Unit.MILLISECOND); }; DateTime.prototype.sameOrBefore = function(other, precision) { var diff; if (precision == null) { precision = DateTime.Unit.MILLISECOND; } if (!(other instanceof DateTime)) { return false; } diff = this.differenceBetween(other, precision); switch (false) { case !(diff.low >= 0 && diff.high >= 0): return true; case !(diff.low < 0 && diff.high < 0): return false; default: return null; } }; DateTime.prototype.sameOrAfter = function(other, precision) { var diff; if (precision == null) { precision = DateTime.Unit.MILLISECOND; } if (!(other instanceof DateTime)) { return false; } diff = this.differenceBetween(other, precision); switch (false) { case !(diff.low <= 0 && diff.high <= 0): return true; case !(diff.low > 0 && diff.high > 0): return false; default: return null; } }; DateTime.prototype.before = function(other, precision) { var diff; if (precision == null) { precision = DateTime.Unit.MILLISECOND; } if (!(other instanceof DateTime)) { return false; } diff = this.differenceBetween(other, precision); switch (false) { case !(diff.low > 0 && diff.high > 0): return true; case !(diff.low <= 0 && diff.high <= 0): return false; default: return null; } }; DateTime.prototype.after = function(other, precision) { var diff; if (precision == null) { precision = DateTime.Unit.MILLISECOND; } if (!(other instanceof DateTime)) { return false; } diff = this.differenceBetween(other, precision); switch (false) { case !(diff.low < 0 && diff.high < 0): return true; case !(diff.low >= 0 && diff.high >= 0): return false; default: return null; } }; DateTime.prototype.add = function(offset, field) { var i, len, normalized, ref, result; result = this.copy(); if (field === DateTime.Unit.WEEK) { offset = offset * 7; field = DateTime.Unit.DAY; } if (result[field] != null) { result[field] = result[field] + offset; normalized = DateTime.fromDate(result.toJSDate(), this.timezoneOffset); ref = DateTime.FIELDS; for (i = 0, len = ref.length; i < len; i++) { field = ref[i]; if (result[field] != null) { result[field] = normalized[field]; } } } return result; }; DateTime.prototype.differenceBetween = function(other, unitField) { var a, aHighMoment, aJS, aLowMoment, aUncertainty, b, bHighMoment, bJS, bLowMoment, bUncertainty, tzDiff; if (!(other instanceof DateTime)) { return null; } a = this.copy(); b = other.copy(); if (unitField === DateTime.Unit.MONTH || unitField === DateTime.Unit.YEAR) { if (a.timezoneOffset !== b.timezoneOffset) { b = b.convertToTimezoneOffset(a.timezoneOffset); } aJS = a.toJSDate(true); bJS = b.toJSDate(true); tzDiff = a.isUTC() && b.isUTC() ? 0 : 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 Date(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; if (!(other instanceof DateTime)) { 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 Date(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.isPrecise = function() { return DateTime.FIELDS.every((function(_this) { return function(field) { return _this[field] != null; }; })(this)); }; DateTime.prototype.isImprecise = function() { return !this.isPrecise(); }; DateTime.prototype.isMorePrecise = function(other) { var field, i, len, ref; ref = DateTime.FIELDS; for (i = 0, len = ref.length; i < len; i++) { field = ref[i]; if ((other[field] != null) && (this[field] == null)) { return false; } } return !this.isSamePrecision(other); }; DateTime.prototype.isLessPrecise = function(other) { return !this.isSamePrecision(other) && !this.isMorePrecise(other); }; DateTime.prototype.isSamePrecision = function(other) { var field, i, len, ref; ref = DateTime.FIELDS; for (i = 0, len = ref.length; i < len; i++) { field = ref[i]; if ((this[field] != null) && (other[field] == null)) { return false; } if ((this[field] == null) && (other[field] != null)) { return false; } } return true; }; 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, ref, ref1, ref2, ref3, ref4, ref5, ref6; if (ignoreTimezone == null) { ignoreTimezone = false; } low = this.toJSDate(ignoreTimezone); high = (new DateTime(this.year, (ref = this.month) != null ? ref : 12, (ref1 = this.day) != null ? ref1 : (new Date(this.year, (ref2 = this.month) != null ? ref2 : 12, 0)).getDate(), (ref3 = this.hour) != null ? ref3 : 23, (ref4 = this.minute) != null ? ref4 : 59, (ref5 = this.second) != null ? ref5 : 59, (ref6 = this.millisecond) != null ? ref6 : 999, this.timezoneOffset)).toJSDate(ignoreTimezone); return new Uncertainty(low, high); }; DateTime.prototype.toJSDate = function(ignoreTimezone) { var d, h, mi, mo, ms, ref, ref1, ref2, ref3, ref4, ref5, s, y; if (ignoreTimezone == null) { ignoreTimezone = false; } ref5 = [this.year, (this.month != null ? this.month - 1 : 0), (ref = this.day) != null ? ref : 1, (ref1 = this.hour) != null ? ref1 : 0, (ref2 = this.minute) != null ? ref2 : 0, (ref3 = this.second) != null ? ref3 : 0, (ref4 = this.millisecond) != null ? ref4 : 0], y = ref5[0], mo = ref5[1], d = ref5[2], h = ref5[3], mi = ref5[4], s = ref5[5], ms = ref5[6]; if ((this.timezoneOffset != null) && !ignoreTimezone) { return new Date(Date.UTC(y, mo, d, h, mi, s, ms) - (this.timezoneOffset * 60 * 60 * 1000)); } else { return new Date(y, mo, d, h, mi, s, ms); } }; DateTime.prototype.toJSON = function() { return this.toString(); }; DateTime.prototype._pad = function(num) { return String("0" + num).slice(-2); }; DateTime.prototype.toString = 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 += '.' + this._pad(this.millisecond); } } } } } } } 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.getDate = function() { return this.reducedPrecision(DateTime.Unit.DAY); }; DateTime.prototype.getTime = function() { return new DateTime(0, 1, 1, this.hour, this.minute, this.second, this.millisecond, this.timezoneOffset); }; DateTime.prototype.isTime = function() { return this.year === 0 && this.month === 1 && this.day === 1; }; 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; })(); }).call(this); },{"./uncertainty":157,"moment":344}],154:[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); },{}],155:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DateTime, Interval, ThreeValuedLogic, Uncertainty, cmp, maxValueForInstance, minValueForInstance, predecessor, ref, successor; DateTime = require('./datetime').DateTime; Uncertainty = require('./uncertainty').Uncertainty; ThreeValuedLogic = require('./logic').ThreeValuedLogic; ref = require('../util/math'), successor = ref.successor, predecessor = ref.predecessor, maxValueForInstance = ref.maxValueForInstance, minValueForInstance = ref.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; } Interval.prototype.contains = function(item, precision) { var closed; if (item instanceof Interval) { throw new Error("Argument to contains must be a point"); } closed = this.toClosed(); return ThreeValuedLogic.and(cmp.lessThanOrEquals(closed.low, item, precision), cmp.greaterThanOrEquals(closed.high, item, precision)); }; Interval.prototype.properlyIncludes = function(other, precision) { if (!(other instanceof Interval)) { 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 instanceof Interval)) { throw new Error("Argument to includes must be an interval"); } 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) { if (!(other instanceof Interval)) { throw new Error("Argument to includedIn must be an interval"); } return other.includes(this); }; Interval.prototype.overlaps = function(item, precision) { var closed, high, itemClosed, low, ref1; closed = this.toClosed(); ref1 = item instanceof Interval ? (itemClosed = item.toClosed(), [itemClosed.low, itemClosed.high]) : [item, item], low = ref1[0], high = ref1[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 instanceof Interval ? 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 instanceof Interval ? 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 instanceof DateTime; }); }; areNumeric = function(x, y) { return [x, y].every(function(z) { return typeof z === 'number' || (z instanceof Uncertainty && typeof z.low === 'number'); }); }; lowestNumericUncertainty = function(x, y) { var high, low; if (!(x instanceof Uncertainty)) { x = new Uncertainty(x); } if (!(y instanceof Uncertainty)) { 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 instanceof Uncertainty)) { x = new Uncertainty(x); } if (!(y instanceof Uncertainty)) { 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, ref1, ref2, ref3; if (!(other instanceof Interval)) { throw new Error("Argument to union must be an interval"); } if (this.overlaps(other) || this.meets(other)) { ref1 = [this.toClosed(), other.toClosed()], a = ref1[0], b = ref1[1]; ref2 = (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 = ref2[0], lc = ref2[1]; ref3 = (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.low, b.low): 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 = ref3[0], hc = ref3[1]; return new Interval(l, h, lc, hc); } else { return null; } }; Interval.prototype.intersect = function(other) { var a, b, h, hc, l, lc, ref1, ref2, ref3; if (!(other instanceof Interval)) { throw new Error("Argument to union must be an interval"); } if (this.overlaps(other)) { ref1 = [this.toClosed(), other.toClosed()], a = ref1[0], b = ref1[1]; ref2 = (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 = ref2[0], lc = ref2[1]; ref3 = (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.low, b.low): 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 = ref3[0], hc = ref3[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 instanceof Interval)) { 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.equals = function(other) { var a, b, ref1; if (other instanceof Interval) { ref1 = [this.toClosed(), other.toClosed()], a = ref1[0], b = ref1[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 ref1; try { if ((precision != null) && this.low instanceof DateTime) { return this.toClosed().low.sameAs((ref1 = other.toClosed().high) != null ? ref1.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 ref1; try { if ((precision != null) && this.high instanceof DateTime) { return this.toClosed().high.sameAs((ref1 = other.toClosed().low) != null ? ref1.add(-1, precision) : void 0, precision); } else { return cmp.equals(this.toClosed().high, predecessor(other.toClosed().low)); } } catch (error) { return false; } }; Interval.prototype.width = function() { var closed, diff; if (this.low instanceof DateTime || this.high instanceof DateTime) { throw new Error("Width of DateTime intervals is not supported"); } closed = this.toClosed(); if (closed.low instanceof Uncertainty || closed.high instanceof Uncertainty) { return null; } else { diff = Math.abs(closed.high - closed.low); return Math.round(diff * Math.pow(10, 8)) / Math.pow(10, 8); } }; Interval.prototype.toClosed = function() { var high, low, point, ref1, ref2; point = (ref1 = this.low) != null ? ref1 : this.high; if (typeof point === 'number' || point instanceof DateTime || (point != null ? (ref2 = point.constructor) != null ? ref2.name : void 0 : void 0) === 'Quantity') { 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); } }; return Interval; })(); }).call(this); },{"../util/comparison":278,"../util/math":279,"./datetime":153,"./logic":156,"./uncertainty":157}],156:[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); },{}],157:[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 instanceof Uncertainty) { return obj; } else { return new Uncertainty(obj); } }; function Uncertainty(low, high) { var gt, 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; } }; if (typeof this.high === 'undefined') { this.high = this.low; } 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]; } } 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":156}],158:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var AggregateExpression, AllTrue, AnyTrue, Avg, Count, Exception, Expression, Max, Median, Min, Mode, PopulationStdDev, PopulationVariance, Quantity, StdDev, Sum, Variance, allTrue, anyTrue, build, compact, numerical_sort, quantitiesOrArg, quantityOrValue, 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, 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, compact = ref.compact, numerical_sort = ref.numerical_sort; build = require('./builder').build; Exception = require('../datatypes/exception').Exception; Quantity = require('./quantity'); quantitiesOrArg = function(arr) { var allQs, i, j, len, someQs, unit, values; arr = compact(arr); if (arr.length === 0) { return arr; } allQs = arr.every(function(x) { return x.constructor.name === "Quantity"; }); someQs = arr.some(function(x) { return x.constructor.name === "Quantity"; }); if (allQs) { unit = arr[0].unit; values = []; for (j = 0, len = arr.length; j < len; j++) { i = arr[j]; values.push(i.convertUnits(unit)); } return values; } else if (someQs) { throw new Exception("Cannot perform aggregate operations on mixed values of Quantities and non Quantities"); } else { return arr; } }; quantityOrValue = function(value, arr) { var ref1; if (arr != null ? (ref1 = arr[0]) != null ? ref1.unit : void 0 : void 0) { return Quantity.createQuantity(value, arr[0].unit); } else { return value; } }; 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 arg; arg = this.source.execute(ctx); if (typeIsArray(arg)) { return compact(arg).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 arg, filtered, val; arg = this.source.execute(ctx); if (typeIsArray(arg)) { filtered = quantitiesOrArg(arg); val = filtered.length === 0 ? null : filtered.reduce(function(x, y) { return x + y; }); return quantityOrValue(val, arg); } }; 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 arg, filtered; arg = this.source.execute(ctx); if (typeIsArray(arg)) { filtered = numerical_sort(quantitiesOrArg(arg), "asc"); return quantityOrValue(filtered[0], arg); } }; 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 arg, filtered; arg = this.source.execute(ctx); if (typeIsArray(arg)) { filtered = numerical_sort(quantitiesOrArg(arg), "desc"); return quantityOrValue(filtered[0], arg); } }; 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 arg, filtered, sum; arg = this.source.execute(ctx); if (typeIsArray(arg)) { filtered = quantitiesOrArg(arg); if (filtered.length === 0) { return null; } sum = filtered.reduce(function(x, y) { return x + y; }); return quantityOrValue(sum / filtered.length, arg); } }; 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 arg, filtered, v; arg = this.source.execute(ctx); if (typeIsArray(arg)) { filtered = numerical_sort(quantitiesOrArg(arg), "asc"); if (filtered.length === 0) { return null; } else if (filtered.length % 2 === 1) { return quantityOrValue(filtered[(filtered.length - 1) / 2], arg); } else { v = (filtered[(filtered.length / 2) - 1] + filtered[filtered.length / 2]) / 2; return quantityOrValue(v, arg); } } }; 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 arg, filtered, mode; arg = this.source.execute(ctx); if (typeIsArray(arg)) { filtered = compact(arg); mode = this.mode(filtered); if (mode.length === 1) { return mode[0]; } else { return mode; } } }; Mode.prototype.mode = function(arr) { var cnt, counts, elem, j, len, max, ref1, results; max = 0; counts = {}; results = []; for (j = 0, len = arr.length; j < len; j++) { elem = arr[j]; cnt = counts[elem] = ((ref1 = counts[elem]) != null ? ref1 : 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 args, val; args = this.source.execute(ctx); if (typeIsArray(args)) { val = quantitiesOrArg(args); if (val.length > 0) { return quantityOrValue(this.calculate(val), args); } else { return null; } } }; StdDev.prototype.calculate = function(list) { var val; val = this.stats(list); if (val) { return val[this.type]; } }; StdDev.prototype.stats = function(list) { var j, 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 (j = 0, len = list.length; j < len; j++) { sq = list[j]; 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.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 args; args = this.source.execute(ctx); return allTrue(args); }; 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 args; args = this.source.execute(ctx); return anyTrue(args); }; return AnyTrue; })(AggregateExpression); }).call(this); },{"../datatypes/exception":154,"../util/util":280,"./builder":160,"./expression":166,"./quantity":178}],159:[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, 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; ref = require('../util/util'), typeIsArray = ref.typeIsArray, allTrue = ref.allTrue, anyTrue = ref.anyTrue; build = require('./builder').build; MathUtil = require('../util/math'); Quantity = require('./quantity'); 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; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { return null; } else { return args != null ? args.reduce(function(x, y) { if (x.constructor.name === 'Quantity' || x.constructor.name === 'DateTime') { return Quantity.doAddition(x, y); } else { return x + y; } }) : void 0; } }; 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; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { return null; } else { return args.reduce(function(x, y) { if (x.constructor.name === 'Quantity' || x.constructor.name === 'DateTime') { return Quantity.doSubtraction(x, y); } else { return x - y; } }); } }; 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; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { return null; } else { return args != null ? args.reduce(function(x, y) { if (x.constructor.name === 'Quantity' || y.constructor.name === 'Quantity') { return Quantity.doMultiplication(x, y); } else { return x * y; } }) : void 0; } }; 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; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { return null; } else { return args != null ? args.reduce(function(x, y) { if (x.constructor.name === 'Quantity') { return Quantity.doDivision(x, y); } else { return x / y; } }) : void 0; } }; 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; args = this.execArgs(ctx); if ((args == null) || args.some(function(x) { return x == null; })) { return null; } else { return Math.floor(args.reduce(function(x, y) { return x / y; })); } }; 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.constructor.name === 'Quantity') { return Quantity.createQuantity(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.constructor.name === 'Quantity') { return Quantity.createQuantity(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; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return Math.exp(arg); } }; 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; 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.pow(x, y); }); } }; return Power; })(Expression); module.exports.MinValue = MinValue = (function(superClass) { extend(MinValue, superClass); MinValue.prototype.MIN_VALUES = { "Integer": MathUtil.MIN_INT_VALUE, "Real": MathUtil.MIN_FLOAT_VALUE, "DateTime": MathUtil.MIN_DATE_VALUE }; function MinValue(json) { MinValue.__super__.constructor.apply(this, arguments); } MinValue.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return MIN_VALUES[arg]; } }; return MinValue; })(Expression); module.exports.MaxValue = MaxValue = (function(superClass) { extend(MaxValue, superClass); MaxValue.prototype.MAX_VALUES = { "Integer": MathUtil.MAX_INT_VALUE, "Real": MathUtil.MAX_FLOAT_VALUE, "DateTime": MathUtil.MAX_DATE_VALUE }; function MaxValue(json) { MaxValue.__super__.constructor.apply(this, arguments); } MaxValue.prototype.exec = function(ctx) { var arg; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return MAX_VALUES[arg]; } }; 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; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return MathUtil.successor(arg); } }; 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; arg = this.execArgs(ctx); if (arg == null) { return null; } else { return MathUtil.predecessor(arg); } }; return Predecessor; })(Expression); }).call(this); },{"../util/math":279,"../util/util":280,"./builder":160,"./expression":166,"./quantity":178}],160:[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":280,"./expressions":167}],161:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var CalculateAge, CalculateAgeAt, 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; } ValueSetRef.prototype.exec = function(ctx) { var valueset; valueset = ctx.getValueSet(this.name); if (valueset instanceof Expression) { valueset = valueset.execute(ctx); } return valueset; }; return ValueSetRef; })(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 null; } if (this.valueset == null) { return false; } code = this.code.execute(ctx); if (code == null) { return null; } valueset = this.valueset.execute(ctx); if (valueset != null) { return valueset.hasMatch(code); } else { return false; } }; 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; } CodeRef.prototype.exec = function(ctx) { var ref; return (ref = ctx.getCode(this.name)) != null ? ref.execute(ctx) : void 0; }; return CodeRef; })(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; } 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.fromDate(new Date()); 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)) { 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":152,"./builder":160,"./expression":166}],162:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Expression, Greater, GreaterOrEqual, IncompatibleTypesException, 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; IncompatibleTypesException = require('./quantity').IncompatibleTypesException; 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, error; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); try { return args[0].lessThan(args[1]); } catch (error1) { error = error1; if (error instanceof IncompatibleTypesException) { return null; } else { throw error; } } }; 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, error; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); try { return args[0].lessThanOrEquals(args[1]); } catch (error1) { error = error1; if (error instanceof IncompatibleTypesException) { return null; } else { throw error; } } }; 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, error; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); try { return args[0].greaterThan(args[1]); } catch (error1) { error = error1; if (error instanceof IncompatibleTypesException) { return null; } else { throw error; } } }; 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, error; args = this.execArgs(ctx).map(function(x) { return Uncertainty.from(x); }); try { return args[0].greaterThanOrEquals(args[1]); } catch (error1) { error = error1; if (error instanceof IncompatibleTypesException) { return null; } else { throw error; } } }; return GreaterOrEqual; })(Expression); }).call(this); },{"../datatypes/datatypes":152,"./expression":166,"./quantity":178}],163:[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":278,"./builder":160,"./expression":166}],164:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DT, DateFrom, DateTime, DateTimeComponentFrom, DifferenceBetween, DurationBetween, Expression, Now, SameAs, SameOrAfter, SameOrBefore, Time, TimeFrom, TimeOfDay, TimezoneFrom, 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; 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(json) { var i, len, property, ref; DateTime.__super__.constructor.apply(this, arguments); ref = DateTime.PROPERTIES; for (i = 0, len = ref.length; i < len; i++) { property = ref[i]; if (json[property] != null) { this[property] = build(json[property]); } } } DateTime.prototype.exec = function(ctx) { var args, p; args = (function() { var i, len, ref, results; ref = DateTime.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, args, function(){}); }; return DateTime; })(Expression); module.exports.Time = Time = (function(superClass) { extend(Time, superClass); Time.PROPERTIES = ['hour', 'minute', 'second', 'millisecond', 'timezoneOffset']; 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 DT.DateTime.fromDate(new Date()).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 DT.DateTime.fromDate(new Date()); }; 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 DT.DateTime.fromDate(new Date()).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.TimezoneFrom = TimezoneFrom = (function(superClass) { extend(TimezoneFrom, superClass); function TimezoneFrom(json) { TimezoneFrom.__super__.constructor.apply(this, arguments); } TimezoneFrom.prototype.exec = function(ctx) { var date; date = this.execArgs(ctx); if (date != null) { return date.timezoneOffset; } else { return null; } }; return TimezoneFrom; })(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 d1, d2, ref, ref1; ref = this.execArgs(ctx), d1 = ref[0], d2 = ref[1]; if ((d1 != null) && (d2 != null)) { return d1.sameAs(d2, (ref1 = this.precision) != null ? ref1.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, ref, ref1; ref = this.execArgs(ctx), d1 = ref[0], d2 = ref[1]; if ((d1 != null) && (d2 != null)) { return d1.sameOrAfter(d2, (ref1 = this.precision) != null ? ref1.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, ref, ref1; ref = this.execArgs(ctx), d1 = ref[0], d2 = ref[1]; if ((d1 != null) && (d2 != null)) { return d1.sameOrBefore(d2, (ref1 = this.precision) != null ? ref1.toLowerCase() : void 0); } else { return null; } }; return SameOrBefore; })(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":152,"./builder":160,"./expression":166}],165:[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":166}],166:[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":280,"./builder":160}],167:[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, 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', 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, 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":158,"./arithmetic":159,"./clinical":161,"./comparison":162,"./conditional":163,"./datetime":164,"./declaration":165,"./expression":166,"./external":168,"./instance":169,"./interval":170,"./list":172,"./literal":173,"./logical":174,"./nullological":175,"./overloaded":176,"./parameters":177,"./quantity":178,"./query":179,"./reusable":180,"./string":181,"./structured":182,"./type":183}],168:[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) { 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":280,"./builder":160,"./expression":166}],169:[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('./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); 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":152,"./builder":160,"./expression":166,"./quantity":178}],170:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Collapse, End, Ends, Expression, Interval, Meets, MeetsAfter, MeetsBefore, Overlaps, OverlapsAfter, OverlapsBefore, Start, Starts, ThreeValuedLogic, UnimplementedExpression, Width, build, cmp, doIncludes, dtivl, 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; ThreeValuedLogic = require('../datatypes/logic').ThreeValuedLogic; build = require('./builder').build; 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); } 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 ref1; Meets.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } Meets.prototype.exec = function(ctx) { var a, b, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[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 ref1; MeetsAfter.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } MeetsAfter.prototype.exec = function(ctx) { var a, b, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[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 ref1; MeetsBefore.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } MeetsBefore.prototype.exec = function(ctx) { var a, b, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[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 ref1; Overlaps.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } Overlaps.prototype.exec = function(ctx) { var a, b, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[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 ref1; OverlapsAfter.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } OverlapsAfter.prototype.exec = function(ctx) { var a, b, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[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 ref1; OverlapsBefore.__super__.constructor.apply(this, arguments); this.precision = (ref1 = json.precision) != null ? ref1.toLowerCase() : void 0; } OverlapsBefore.prototype.exec = function(ctx) { var a, b, ref1; ref1 = this.execArgs(ctx), a = ref1[0], b = ref1[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 ref1; return (ref1 = this.arg.execute(ctx)) != null ? ref1.width() : void 0; }; return Width; })(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 ref1; return (ref1 = this.arg.execute(ctx)) != null ? ref1.low : void 0; }; 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 ref1; return (ref1 = this.arg.execute(ctx)) != null ? ref1.high : void 0; }; return End; })(Expression); module.exports.Starts = Starts = (function(superClass) { extend(Starts, superClass); function Starts() { return Starts.__super__.constructor.apply(this, arguments); } return Starts; })(UnimplementedExpression); module.exports.Ends = Ends = (function(superClass) { extend(Ends, superClass); function Ends() { return Ends.__super__.constructor.apply(this, arguments); } return Ends; })(UnimplementedExpression); module.exports.Collapse = Collapse = (function(superClass) { extend(Collapse, superClass); function Collapse(json) { Collapse.__super__.constructor.apply(this, arguments); } Collapse.prototype.exec = function(ctx) { var a, b, base, base1, collapsedIntervals, i, intervals, len; intervals = this.execArgs(ctx); if ((intervals != null ? intervals.length : void 0) <= 1) { return intervals; } else { for (i = 0, len = intervals.length; i < len; i++) { a = intervals[i]; if ((typeof (base = a.low).isImprecise === "function" ? base.isImprecise() : void 0) || (typeof (base1 = a.high).isImprecise === "function" ? base1.isImprecise() : void 0)) { throw new Error("Collapse does not support imprecise dates at this time."); } } intervals.sort(function(a, b) { if (typeof a.low.before === 'function') { if (a.low.before(b.low)) { return -1; } if (a.low.after(b.low)) { return 1; } } else { if (a.low < b.low) { return -1; } if (a.low > b.low) { return 1; } } return 0; }); collapsedIntervals = []; a = intervals.shift(); b = intervals.shift(); while (b) { if (typeof b.low.sameOrBefore === 'function') { if (b.low.sameOrBefore(a.high)) { if (b.high.after(a.high)) { a.high = b.high; } } else { collapsedIntervals.push(a); a = b; } } else { if (b.low <= a.high) { if (b.high > a.high) { a.high = b.high; } } else { collapsedIntervals.push(a); a = b; } } b = intervals.shift(); } collapsedIntervals.push(a); return collapsedIntervals; } }; return Collapse; })(Expression); }).call(this); },{"../datatypes/interval":155,"../datatypes/logic":156,"../util/comparison":278,"./builder":160,"./expression":166}],171:[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) { return this.valuesets[identifier]; }; 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":277,"./expressions":167}],172:[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, equivalent, 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; ref = require('./expression'), Expression = ref.Expression, UnimplementedExpression = ref.UnimplementedExpression; ValueSet = require('../datatypes/datatypes').ValueSet; build = require('./builder').build; typeIsArray = require('../util/util').typeIsArray; ref1 = require('../util/comparison'), equals = ref1.equals, equivalent = ref1.equivalent; module.exports.List = List = (function(superClass) { extend(List, superClass); function List(json) { var ref2; List.__super__.constructor.apply(this, arguments); this.elements = (ref2 = build(json.element)) != null ? ref2 : []; } List.prototype.exec = function(ctx) { var item, j, len, ref2, results; ref2 = this.elements; results = []; for (j = 0, len = ref2.length; j < len; j++) { item = ref2[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 ref2; return ((ref2 = this.execArgs(ctx)) != null ? ref2.length : void 0) > 0; }; return Exists; })(Expression); module.exports.doUnion = function(a, b) { return doDistinct(a.concat(b)); }; module.exports.doExcept = function(a, b) { var itm, j, len, results; results = []; for (j = 0, len = a.length; j < len; j++) { itm = a[j]; if (!doContains(b, itm)) { results.push(itm); } } return results; }; module.exports.doIntersect = function(a, b) { var itm, j, len, results; results = []; for (j = 0, len = a.length; j < len; j++) { itm = a[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.exec(ctx); el = this.element.exec(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 (equivalent(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) { return doDistinct(this.execArgs(ctx)); }; return Distinct; })(Expression); doDistinct = function(list) { var seen; seen = []; return list.filter(function(item) { var isNew; isNew = seen.every(function(seenItem) { return !equals(item, seenItem); }); if (isNew) { seen.push(item); } return isNew; }); }; 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":152,"../util/comparison":278,"../util/util":280,"./builder":160,"./expression":166}],173:[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'; } 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); } 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); } 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); } StringLiteral.prototype.exec = function(ctx) { return this.value.replace(/\\'/g, "'").replace(/\\"/g, "\""); }; return StringLiteral; })(Literal); }).call(this); },{"./expression":166}],174:[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":152,"./expression":166}],175:[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":166}],176:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var After, ArrayIndexOutOfBoundsException, Contains, DT, DateTime, Equal, Equivalent, Except, Exception, Expression, IVL, In, IncludedIn, Includes, IncompatibleTypesException, Indexer, Intersect, LIST, Length, NotEqual, ProperIncludedIn, ProperIncludes, STRING, 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; IncompatibleTypesException = require('./quantity').IncompatibleTypesException; 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 error; try { return equals.apply(null, this.execArgs(ctx)); } catch (error1) { error = error1; if (error instanceof IncompatibleTypesException) { return null; } else { throw error; } } }; 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 error; try { return ThreeValuedLogic.not(equals.apply(null, this.execArgs(ctx))); } catch (error1) { error = error1; if (error instanceof IncompatibleTypesException) { return null; } else { throw error; } } }; 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.ArrayIndexOutOfBoundsException = ArrayIndexOutOfBoundsException = ArrayIndexOutOfBoundsException = (function(superClass) { extend(ArrayIndexOutOfBoundsException, superClass); function ArrayIndexOutOfBoundsException() { return ArrayIndexOutOfBoundsException.__super__.constructor.apply(this, arguments); } return ArrayIndexOutOfBoundsException; })(Exception); 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) { throw new ArrayIndexOutOfBoundsException(); } 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 ((item == null) || (container == 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 ((item == null) || (container == 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); }).call(this); },{"../datatypes/datetime":153,"../datatypes/exception":154,"../datatypes/logic":156,"../util/comparison":278,"../util/util":280,"./builder":160,"./datetime":164,"./expression":166,"./interval":170,"./list":172,"./quantity":178,"./string":181}],177:[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":160,"./expression":166}],178:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Code, Exception, Expression, FunctionRef, IncompatibleTypesException, Quantity, ValueSet, build, clean_unit, convert_value, createQuantity, decimalAdjust, is_valid_ucum_unit, ref, ucum, ucum_multiply, ucum_time_units, ucum_to_cql_units, ucum_unit, unitValidityCache, units_to_string, 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; decimalAdjust = require('../util/math').decimalAdjust; ref = require('../datatypes/datatypes'), ValueSet = ref.ValueSet, Code = ref.Code; Exception = require('../datatypes/exception').Exception; build = require('./builder').build; ucum = require('ucum'); module.exports.IncompatibleTypesException = IncompatibleTypesException = IncompatibleTypesException = (function(superClass) { extend(IncompatibleTypesException, superClass); function IncompatibleTypesException(a1, b1, e) { this.a = a1; this.b = b1; IncompatibleTypesException.__super__.constructor.call(this, "Incompatible Types '" + this.a + "' and '" + this.b + "'", e); } return IncompatibleTypesException; })(Exception); module.exports.Quantity = Quantity = (function(superClass) { extend(Quantity, superClass); function Quantity(json) { Quantity.__super__.constructor.apply(this, arguments); this.unit = json.unit; this.value = parseFloat(json.value); if (!is_valid_ucum_unit(this.unit)) { throw new Error("\'" + this.unit + "\' is not a valid UCUM unit."); } } Quantity.prototype.clone = function() { return new Quantity({ value: this.value, unit: this.unit }); }; Quantity.prototype.exec = function(ctx) { return this; }; Quantity.prototype.toString = function() { return this.value + " '" + this.unit + "'"; }; Quantity.prototype.sameOrBefore = function(other) { var other_v; if (other instanceof Quantity) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); return this.value <= other_v; } }; Quantity.prototype.sameOrAfter = function(other) { var other_v; if (other instanceof Quantity) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); return this.value >= other_v; } }; Quantity.prototype.after = function(other) { var other_v; if (other instanceof Quantity) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); return this.value > other_v; } }; Quantity.prototype.before = function(other) { var other_v; if (other instanceof Quantity) { other_v = convert_value(other.value, ucum_unit(other.unit), ucum_unit(this.unit)); return this.value < other_v; } }; Quantity.prototype.equals = function(other) { var other_v; if (other instanceof Quantity) { 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)); return decimalAdjust("round", this.value, -8) === decimalAdjust("round", other_v, -8); } } }; Quantity.prototype.convertUnits = function(to_units) { return convert_value(this.value, this.unit, to_units); }; 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 can_val, other_can_value, ucum_value, unit, value; if (other instanceof Quantity) { if (this.unit && other.unit) { can_val = this.to_ucum(); other_can_value = other.to_ucum(); ucum_value = ucum_multiply(can_val, [[operator, other_can_value]]); return createQuantity(ucum_value.value, units_to_string(ucum_value.units)); } else { value = operator === "/" ? this.value / other.value : this.value * other.value; unit = this.unit || other.unit; return createQuantity(decimalAdjust("round", value, -8), unit); } } else { value = operator === "/" ? this.value / other : this.value * other; return createQuantity(decimalAdjust("round", value, -8), this.unit); } }; Quantity.prototype.to_ucum = function() { var u; u = ucum.parse(ucum_unit(this.unit)); u.value *= this.value; return u; }; return Quantity; })(Expression); 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; throw new IncompatibleTypesException(from, to, e); } }; 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 null; } 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.createQuantity = createQuantity = function(value, unit) { return new Quantity({ value: value, unit: unit }); }; module.exports.parseQuantity = function(str) { var components, unit, value; components = /([+|-]?\d+\.?\d*)\s*'(.+)'/.exec(str); if ((components != null) && (components[1] != null) && (components[2] != null)) { value = parseFloat(components[1]); unit = components[2].trim(); return new Quantity({ value: value, unit: unit }); } else { return null; } }; module.exports.doAddition = function(a, b) { var base, val; if (a instanceof Quantity && b instanceof Quantity) { val = convert_value(b.value, b.unit, a.unit); return new Quantity({ unit: a.unit, value: a.value + val }); } else { return typeof a.copy === "function" ? typeof (base = a.copy()).add === "function" ? base.add(b.value, clean_unit(b.unit)) : void 0 : void 0; } }; module.exports.doSubtraction = function(a, b) { var base, val; if (a instanceof Quantity && b instanceof Quantity) { val = convert_value(b.value, b.unit, a.unit); return new Quantity({ unit: a.unit, value: a.value - val }); } else { return typeof a.copy === "function" ? typeof (base = a.copy()).add === "function" ? base.add(b.value * -1, clean_unit(b.unit)) : void 0 : void 0; } }; module.exports.doDivision = function(a, b) { if (a instanceof Quantity) { return a.dividedBy(b); } }; module.exports.doMultiplication = function(a, b) { if (a instanceof Quantity) { return a.multiplyBy(b); } else { return b.multiplyBy(a); } }; }).call(this); },{"../datatypes/datatypes":152,"../datatypes/exception":154,"../util/math":279,"./builder":160,"./expression":166,"./reusable":180,"ucum":557}],179:[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 < 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 < 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":274,"../util/comparison":278,"../util/util":280,"./builder":160,"./expression":166}],180:[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":160,"./expression":166}],181:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Combine, Concatenate, Expression, Lower, PositionOf, Split, Substring, Upper, 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.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 separator, source; source = this.source.execute(ctx); separator = this.separator != null ? this.separator.execute(ctx) : ''; if ((source == null) || source.some(function(x) { return x == null; })) { return null; } else { return source.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.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.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); }).call(this); },{"./builder":160,"./expression":166}],182:[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; Tuple.__super__.constructor.apply(this, arguments); this.elements = (function() { var i, len, ref1, results; ref1 = json.element; results = []; for (i = 0, len = ref1.length; i < len; i++) { el = ref1[i]; results.push({ name: el.name, value: build(el.value) }); } return results; })(); } 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":160,"./expression":166}],183:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var As, Concept, Convert, DateTime, Expression, FunctionRef, IntervalTypeSpecifier, Is, ListTypeSpecifier, NamedTypeSpecifier, ToBoolean, ToConcept, ToDateTime, ToDecimal, ToInteger, ToQuantity, ToString, ToTime, TupleTypeSpecifier, UnimplementedExpression, parseQuantity, 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; FunctionRef = require('./reusable').FunctionRef; DateTime = require('../datatypes/datetime').DateTime; Concept = require('../datatypes/clinical').Concept; parseQuantity = require('./quantity').parseQuantity; module.exports.As = As = (function(superClass) { extend(As, superClass); function As(json) { var ref1; As.__super__.constructor.apply(this, arguments); this.asType = json.asType; this.asTypeSpecifier = json.asTypeSpecifier; this.strict = (ref1 = json.strict) != null ? ref1 : 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(); 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 { throw new Error("cannot convert " + strArg + " to Boolean"); } } 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.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) && typeof arg !== 'undefined') { return DateTime.parse(arg.toString()); } else { return null; } }; 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; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { return parseFloat(arg.toString()); } else { 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; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { return parseInt(arg.toString()); } else { 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; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { return parseQuantity(arg.toString()); } else { return null; } }; return ToQuantity; })(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, dt; arg = this.execArgs(ctx); if ((arg != null) && typeof arg !== 'undefined') { dt = DateTime.parse(arg.toString()); if ((dt != null) && typeof dt !== 'undefined') { return dt.getTime(); } else { return 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}Time": return new ToTime({ "type": "ToTime", "operand": this.operand }).execute(ctx); default: return this.execArgs(ctx); } }; return Convert; })(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":151,"../datatypes/datetime":153,"./expression":166,"./quantity":178,"./reusable":180}],184:[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":148,"./core":201}],185:[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":148,"./core":201}],186:[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":148,"./core":201}],187:[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":148,"./core":201}],188:[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":148,"./core":201}],189:[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":148,"./core":201}],190:[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":148,"./core":201}],191:[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":148,"./core":201}],192:[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":148,"./core":201}],193:[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":148,"./core":201}],194:[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":148,"./core":201}],195:[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":148,"./core":201}],196:[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":148,"./core":201}],197:[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":148,"./core":201}],198:[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":148,"./core":201}],199:[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":148,"./core":201}],200:[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":148,"./core":201}],201:[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":148}],202:[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":148,"./core":201}],203:[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":148,"./core":201}],204:[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":148,"./core":201}],205:[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":148,"./core":201}],206:[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":148,"./core":201}],207:[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":148,"./core":201}],208:[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":148,"./core":201}],209:[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":148,"./core":201}],210:[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":148,"./core":201}],211:[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":148,"./core":201}],212:[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":148,"./core":201}],213:[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":148,"./core":201}],214:[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":148,"./core":201}],215:[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":148,"./core":201}],216:[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":148,"./core":201}],217:[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":148,"./core":201}],218:[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":148,"./core":201}],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, 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":148,"./core":201}],220:[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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],225:[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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],235:[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":184,"./allergyintolerance":185,"./appointment":186,"./appointmentresponse":187,"./availability":188,"./basic":189,"./binary":190,"./bundle":191,"./careplan":192,"./claimresponse":193,"./communicationrequest":194,"./composition":195,"./conceptmap":196,"./condition":197,"./conformance":198,"./contract":199,"./contraindication":200,"./core":201,"./coverage":202,"./dataelement":203,"./device":204,"./devicecomponent":205,"./deviceuserequest":206,"./deviceusestatement":207,"./diagnosticorder":208,"./diagnosticreport":209,"./documentmanifest":210,"./documentreference":211,"./eligibility":212,"./eligibilityresponse":213,"./encounter":214,"./enrollment":215,"./enrollmentresponse":216,"./explanationofbenefit":217,"./extensiondefinition":218,"./familyhistory":219,"./group":220,"./healthcareservice":221,"./imagingobjectselection":222,"./imagingstudy":223,"./immunization":224,"./immunizationrecommendation":225,"./list":226,"./location":227,"./media":228,"./medication":229,"./medicationadministration":230,"./medicationdispense":231,"./medicationprescription":232,"./medicationstatement":233,"./messageheader":234,"./namingsystem":236,"./nutritionorder":237,"./observation":238,"./operationdefinition":239,"./operationoutcome":240,"./oralhealthclaim":241,"./order":242,"./orderresponse":243,"./organization":244,"./other":245,"./patient":246,"./paymentnotice":247,"./paymentreconciliation":248,"./pendedrequest":249,"./practitioner":250,"./procedure":251,"./procedurerequest":252,"./profile":253,"./provenance":254,"./query":255,"./questionnaire":256,"./questionnaireanswers":257,"./readjudicate":258,"./referralrequest":259,"./relatedperson":260,"./reversal":261,"./riskassessment":262,"./searchparameter":263,"./securityevent":264,"./slot":265,"./specimen":266,"./statusrequest":267,"./statusresponse":268,"./subscription":269,"./substance":270,"./supply":271,"./supportingdocumentation":272,"./valueset":273}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],241:[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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],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, 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":148,"./core":201}],245:[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":148,"./core":201}],246:[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":148,"./core":201}],247:[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":148,"./core":201}],248:[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":148,"./core":201}],249:[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":148,"./core":201}],250:[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":148,"./core":201}],251:[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":148,"./core":201}],252:[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":148,"./core":201}],253:[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":148,"./core":201}],254:[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":148,"./core":201}],255:[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":148,"./core":201}],256:[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":148,"./core":201}],257:[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":148,"./core":201}],258:[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":148,"./core":201}],259:[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":148,"./core":201}],260:[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":148,"./core":201}],261:[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":148,"./core":201}],262:[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":148,"./core":201}],263:[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":148,"./core":201}],264:[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":148,"./core":201}],265:[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":148,"./core":201}],266:[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":148,"./core":201}],267:[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":148,"./core":201}],268:[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":148,"./core":201}],269:[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":148,"./core":201}],270:[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":148,"./core":201}],271:[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":148,"./core":201}],272:[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":148,"./core":201}],273:[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":148,"./core":201}],274:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Context, Exception, Library, PatientContext, PopulationContext, 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; 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.getValueSet = function(name) { var ref; return (ref = this.parent) != null ? ref.getValueSet(name) : 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 { 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; 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.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.type); }; })(this)); }; Context.prototype.matchesIntervalTypeSpecifier = function(val, spec) { var ref; return ((ref = val.constructor) != null ? ref.name : void 0) === "Interval" && ((val.low == null) || this.matchesTypeSpecifier(val.low, spec.pointType)) && ((val.high == null) || this.matchesTypeSpecifier(val.high, spec.pointType)); }; Context.prototype.matchesNamedTypeSpecifier = function(val, spec) { var ref, ref1, ref2, ref3; 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 ? (ref = val.constructor) != null ? ref.name : void 0 : void 0) === 'Concept'; case "{urn:hl7-org:elm-types:r1}DateTime": return (val != null ? (ref1 = val.constructor) != null ? ref1.name : void 0 : void 0) === 'DateTime'; case "{urn:hl7-org:elm-types:r1}Quantity": return (val != null ? (ref2 = val.constructor) != null ? ref2.name : void 0 : void 0) === 'Quantity'; case "{urn:hl7-org:elm-types:r1}Time": return (val != null ? (ref3 = val.constructor) != null ? ref3.name : void 0 : void 0) === 'DateTime' && val.isTime(); default: return true; } }; Context.prototype.matchesInstanceType = function(val, inst) { var ref, ref1, ref2, ref3, ref4; switch ((ref = inst.constructor) != null ? ref.name : void 0) { case "BooleanLiteral": return typeof val === "boolean"; case "DecimalLiteral": return typeof val === "number"; case "IntegerLiteral": return typeof val === "number" && Math.floor(val) === val; case "StringLiteral": return typeof val === "string"; case "Concept": return (val != null ? (ref1 = val.constructor) != null ? ref1.name : void 0 : void 0) === "Concept"; case "DateTime": return (val != null ? (ref2 = val.constructor) != null ? ref2.name : void 0 : void 0) === "DateTime"; case "Quantity": return (val != null ? (ref3 = val.constructor) != null ? ref3.name : void 0 : void 0) === "Quantity"; case "Time": return (val != null ? (ref4 = val.constructor) != null ? ref4.name : void 0 : void 0) === "DateTime" && val.isTime(); case "List": return this.matchesListInstanceType(val, inst); case "Tuple": return this.matchesTupleInstanceType(val, inst); case "Interval": 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, ref1; pointType = (ref = ivl.low) != null ? ref : ivl.high; return ((ref1 = val.constructor) != null ? ref1.name : void 0) === "Interval" && ((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) { this.library = library1; this.patient = patient; 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)); }; 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)); }; PatientContext.prototype.findRecords = function(profile) { var ref; return (ref = this.patient) != null ? ref.findRecords(profile) : void 0; }; return PatientContext; })(Context); module.exports.PopulationContext = PopulationContext = (function(superClass) { extend(PopulationContext, superClass); function PopulationContext(library1, results, codeService, parameters) { this.library = library1; this.results = results; PopulationContext.__super__.constructor.call(this, this.library, codeService, parameters); } PopulationContext.prototype.rootContext = function() { return this; }; PopulationContext.prototype.findRecords = function(template) { throw new Exception("Retreives are not currently supported in Population Context"); }; PopulationContext.prototype.getLibraryContext = function(library) { throw new Exception("Library expressions are not currently supported in Population Context"); }; PopulationContext.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) === "Population") { return this.library.expressions[identifier]; } ref1 = this.results.patientResults; results = []; for (pid in ref1) { res = ref1[pid]; results.push(res[identifier]); } return results; }; return PopulationContext; })(Context); }).call(this); },{"../datatypes/exception":154,"../elm/library":171,"../util/util":280,"util":563}],275:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Executor, PatientContext, PopulationContext, Results, 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) { var expr, key, popContext, r, ref; Results(r = this.exec_patient_context(patientSource)); popContext = new PopulationContext(this.library, r, this.codeService, this.parameters); ref = this.library.expressions; for (key in ref) { expr = ref[key]; if (expr.context === "Population") { r.recordPopulationResult(key, expr.exec(popContext)); } } return r; }; Executor.prototype.exec_patient_context = function(patientSource) { 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); 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'), PopulationContext = ref.PopulationContext, PatientContext = ref.PatientContext; }).call(this); },{"./context":274,"./results":277}],276:[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":150}],277:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var Results; module.exports.Results = Results = (function() { function Results() { this.patientResults = {}; this.populationResults = {}; this.localIdPatientResultsMap = {}; } Results.prototype.recordPatientResult = function(patient_ctx, resultName, result) { var base, patientId; patientId = patient_ctx.patient.id(); if ((base = this.patientResults)[patientId] == null) { base[patientId] = {}; } this.patientResults[patientId][resultName] = result; return this.localIdPatientResultsMap[patientId] = patient_ctx.getAllLocalIds(); }; Results.prototype.recordPopulationResult = function(resultName, result) { return this.populationResults[resultName] = result; }; return Results; })(); }).call(this); },{}],278:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DateTime, Uncertainty, areDateTimesOrQuantities, areNumbers, equals, equivalent, 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) { var ref, ref1; return (a instanceof DateTime && b instanceof DateTime) || ((a != null ? (ref = a.constructor) != null ? ref.name : void 0 : void 0) === 'Quantity' && (b != null ? (ref1 = b.constructor) != null ? ref1.name : void 0 : void 0) === 'Quantity'); }; isUncertainty = function(x) { return x instanceof Uncertainty; }; module.exports.lessThan = function(a, b, precision) { if (precision == null) { precision = DateTime.Unit.MILLISECOND; } 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) { if (precision == null) { precision = DateTime.Unit.MILLISECOND; } 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) { if (precision == null) { precision = DateTime.Unit.MILLISECOND; } 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) { if (precision == null) { precision = DateTime.Unit.MILLISECOND; } 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) { if (typeof a.hasMatch === 'function') { return a.hasMatch(b); } return equals(a, b); }; module.exports.equals = equals = function(a, b) { var aClass, aKeys, bClass, bKeys, key, obj, ref, ref1; if (!((a != null) && (b != null))) { return null; } if ((a != null ? (ref = a.constructor) != null ? ref.name : void 0 : void 0) === 'Quantity') { 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 (a === b) { return true; } ref1 = (function() { var j, len, ref1, results; ref1 = [a, b]; results = []; for (j = 0, len = ref1.length; j < len; j++) { obj = ref1[j]; results.push({}.toString.call(obj)); } return results; })(), aClass = ref1[0], bClass = ref1[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]': return a.length === b.length && a.every(function(item, i) { return equals(item, b[i]); }); case '[object Object]': if (!(b instanceof a.constructor && a instanceof b.constructor)) { return false; } aKeys = ((function() { var results; if (typeof key !== 'function') { results = []; for (key in a) { results.push(key); } return results; } })()); bKeys = ((function() { var results; if (typeof key !== 'function') { results = []; for (key in b) { results.push(key); } return results; } })()); return aKeys.length === bKeys.length && aKeys.every(function(key) { return equals(a[key], b[key]); }); } return false; }; }).call(this); },{"../datatypes/datetime":153,"../datatypes/uncertainty":157}],279:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var DateTime, Exception, MAX_DATE_VALUE, MAX_FLOAT_VALUE, MAX_INT_VALUE, MIN_DATE_VALUE, MIN_FLOAT_PRECISION_VALUE, MIN_FLOAT_VALUE, MIN_INT_VALUE, OverFlowException, Uncertainty, predecessor, 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; DateTime = require('../datatypes/datetime').DateTime; 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 = (Math.pow(10, 37) - 1) / Math.pow(10, 8); module.exports.MIN_FLOAT_VALUE = MIN_FLOAT_VALUE = (Math.pow(-10, 37) + 1) / Math.pow(10, 8); module.exports.MIN_FLOAT_PRECISION_VALUE = MIN_FLOAT_PRECISION_VALUE = Math.pow(10, -8); module.exports.MIN_DATE_VALUE = MIN_DATE_VALUE = DateTime.parse("0001-01-01T00:00:00.000"); module.exports.MAX_DATE_VALUE = MAX_DATE_VALUE = DateTime.parse("9999-12-31T23:59:59.999"); 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, ref, 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 instanceof DateTime) { if (val.sameAs(MAX_DATE_VALUE)) { throw new OverFlowException(); } else { return val.successor(); } } else if (val instanceof Uncertainty) { 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 ? (ref = val.constructor) != null ? ref.name : void 0 : void 0) === 'Quantity') { 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, ref; 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 instanceof DateTime) { if (val.sameAs(MIN_DATE_VALUE)) { throw new OverFlowException(); } else { return val.predecessor(); } } else if (val instanceof Uncertainty) { 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 ? (ref = val.constructor) != null ? ref.name : void 0 : void 0) === 'Quantity') { pred = val.clone(); pred.value = predecessor(val.value); return pred; } else if (val == null) { return null; } }; module.exports.maxValueForInstance = function(val) { var ref, val2; if (typeof val === "number") { if (parseInt(val) === val) { return MAX_INT_VALUE; } else { return MAX_FLOAT_VALUE; } } else if (val instanceof DateTime) { return MAX_DATE_VALUE; } else if ((val != null ? (ref = val.constructor) != null ? ref.name : void 0 : void 0) === 'Quantity') { val2 = val.clone(); val2.value = maxValueForInstance(val2.value); return val2; } else { return null; } }; module.exports.minValueForInstance = function(val) { var ref, val2; if (typeof val === "number") { if (parseInt(val) === val) { return MIN_INT_VALUE; } else { return MIN_FLOAT_VALUE; } } else if (val instanceof DateTime) { return MIN_DATE_VALUE; } else if ((val != null ? (ref = val.constructor) != null ? ref.name : void 0 : void 0) === 'Quantity') { 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":153,"../datatypes/exception":154,"../datatypes/uncertainty":157}],280:[function(require,module,exports){ // Generated by CoffeeScript 1.12.7 (function() { var typeIsArray; module.exports.compact = 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; } }; }).call(this); },{}],281:[function(require,module,exports){ (function (Buffer){ var elliptic = require('elliptic'); var BN = require('bn.js'); module.exports = function createECDH(curve) { return new ECDH(curve); }; var aliases = { secp256k1: { name: 'secp256k1', byteLength: 32 }, secp224r1: { name: 'p224', byteLength: 28 }, prime256v1: { name: 'p256', byteLength: 32 }, prime192v1: { name: 'p192', byteLength: 24 }, ed25519: { name: 'ed25519', byteLength: 32 }, secp384r1: { name: 'p384', byteLength: 48 }, secp521r1: { name: 'p521', byteLength: 66 } }; aliases.p224 = aliases.secp224r1; aliases.p256 = aliases.secp256r1 = aliases.prime256v1; aliases.p192 = aliases.secp192r1 = aliases.prime192v1; aliases.p384 = aliases.secp384r1; aliases.p521 = aliases.secp521r1; function ECDH(curve) { this.curveType = aliases[curve]; if (!this.curveType ) { this.curveType = { name: curve }; } this.curve = new elliptic.ec(this.curveType.name); this.keys = void 0; } ECDH.prototype.generateKeys = function (enc, format) { this.keys = this.curve.genKeyPair(); return this.getPublicKey(enc, format); }; ECDH.prototype.computeSecret = function (other, inenc, enc) { inenc = inenc || 'utf8'; if (!Buffer.isBuffer(other)) { other = new Buffer(other, inenc); } var otherPub = this.curve.keyFromPublic(other).getPublic(); var out = otherPub.mul(this.keys.getPrivate()).getX(); return formatReturnValue(out, enc, this.curveType.byteLength); }; ECDH.prototype.getPublicKey = function (enc, format) { var key = this.keys.getPublic(format === 'compressed', true); if (format === 'hybrid') { if (key[key.length - 1] % 2) { key[0] = 7; } else { key [0] = 6; } } return formatReturnValue(key, enc); }; ECDH.prototype.getPrivateKey = function (enc) { return formatReturnValue(this.keys.getPrivate(), enc); }; ECDH.prototype.setPublicKey = function (pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { pub = new Buffer(pub, enc); } this.keys._importPublic(pub); return this; }; ECDH.prototype.setPrivateKey = function (priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { priv = new Buffer(priv, enc); } var _priv = new BN(priv); _priv = _priv.toString(16); this.keys._importPrivate(_priv); return this; }; function formatReturnValue(bn, enc, len) { if (!Array.isArray(bn)) { bn = bn.toArray(); } var buf = new Buffer(bn); if (len && buf.length < len) { var zeros = new Buffer(len - buf.length); zeros.fill(0); buf = Buffer.concat([zeros, buf]); } if (!enc) { return buf; } else { return buf.toString(enc); } } }).call(this,require("buffer").Buffer) },{"bn.js":91,"buffer":144,"elliptic":300}],282:[function(require,module,exports){ (function (Buffer){ 'use strict' var inherits = require('inherits') var md5 = require('./md5') var RIPEMD160 = require('ripemd160') var sha = require('sha.js') var Base = require('cipher-base') function HashNoConstructor (hash) { Base.call(this, 'digest') this._hash = hash this.buffers = [] } inherits(HashNoConstructor, Base) HashNoConstructor.prototype._update = function (data) { this.buffers.push(data) } HashNoConstructor.prototype._final = function () { var buf = Buffer.concat(this.buffers) var r = this._hash(buf) this.buffers = null return r } function Hash (hash) { Base.call(this, 'digest') this._hash = hash } inherits(Hash, Base) Hash.prototype._update = function (data) { this._hash.update(data) } Hash.prototype._final = function () { return this._hash.digest() } module.exports = function createHash (alg) { alg = alg.toLowerCase() if (alg === 'md5') return new HashNoConstructor(md5) if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160()) return new Hash(sha(alg)) } }).call(this,require("buffer").Buffer) },{"./md5":284,"buffer":144,"cipher-base":145,"inherits":334,"ripemd160":536,"sha.js":540}],283:[function(require,module,exports){ (function (Buffer){ 'use strict' var intSize = 4 var zeroBuffer = new Buffer(intSize) zeroBuffer.fill(0) var charSize = 8 var hashSize = 16 function toArray (buf) { if ((buf.length % intSize) !== 0) { var len = buf.length + (intSize - (buf.length % intSize)) buf = Buffer.concat([buf, zeroBuffer], len) } var arr = new Array(buf.length >>> 2) for (var i = 0, j = 0; i < buf.length; i += intSize, j++) { arr[j] = buf.readInt32LE(i) } return arr } module.exports = function hash (buf, fn) { var arr = fn(toArray(buf), buf.length * charSize) buf = new Buffer(hashSize) for (var i = 0; i < arr.length; i++) { buf.writeInt32LE(arr[i], i << 2, true) } return buf } }).call(this,require("buffer").Buffer) },{"buffer":144}],284:[function(require,module,exports){ 'use strict' /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ var makeHash = require('./make-hash') /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function core_md5 (x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32) x[(((len + 64) >>> 9) << 4) + 14] = len var a = 1732584193 var b = -271733879 var c = -1732584194 var d = 271733878 for (var i = 0; i < x.length; i += 16) { var olda = a var oldb = b var oldc = c var oldd = d a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936) d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586) c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819) b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330) a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897) d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426) c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341) b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983) a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416) d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417) c = md5_ff(c, d, a, b, x[i + 10], 17, -42063) b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162) a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682) d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101) c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290) b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329) a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510) d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632) c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713) b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302) a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691) d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083) c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335) b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848) a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438) d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690) c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961) b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501) a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467) d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784) c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473) b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734) a = md5_hh(a, b, c, d, x[i + 5], 4, -378558) d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463) c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562) b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556) a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060) d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353) c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632) b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640) a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174) d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222) c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979) b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189) a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487) d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835) c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520) b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651) a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844) d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415) c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905) b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055) a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571) d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606) c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523) b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799) a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359) d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744) c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380) b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649) a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070) d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379) c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259) b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551) a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) } return [a, b, c, d] } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn (q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) } function md5_ff (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) } function md5_gg (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) } function md5_hh (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t) } function md5_ii (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF) var msw = (x >> 16) + (y >> 16) + (lsw >> 16) return (msw << 16) | (lsw & 0xFFFF) } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)) } module.exports = function md5 (buf) { return makeHash(buf, core_md5) } },{"./make-hash":283}],285:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var Legacy = require('./legacy') var Base = require('cipher-base') var Buffer = require('safe-buffer').Buffer var md5 = require('create-hash/md5') var RIPEMD160 = require('ripemd160') var sha = require('sha.js') var ZEROS = Buffer.alloc(128) function Hmac (alg, key) { Base.call(this, 'digest') if (typeof key === 'string') { key = Buffer.from(key) } var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 this._alg = alg this._key = key if (key.length > blocksize) { var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) key = hash.update(key).digest() } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } var ipad = this._ipad = Buffer.allocUnsafe(blocksize) var opad = this._opad = Buffer.allocUnsafe(blocksize) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) this._hash.update(ipad) } inherits(Hmac, Base) Hmac.prototype._update = function (data) { this._hash.update(data) } Hmac.prototype._final = function () { var h = this._hash.digest() var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) return hash.update(this._opad).update(h).digest() } module.exports = function createHmac (alg, key) { alg = alg.toLowerCase() if (alg === 'rmd160' || alg === 'ripemd160') { return new Hmac('rmd160', key) } if (alg === 'md5') { return new Legacy(md5, key) } return new Hmac(alg, key) } },{"./legacy":286,"cipher-base":145,"create-hash/md5":284,"inherits":334,"ripemd160":536,"safe-buffer":537,"sha.js":540}],286:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var Buffer = require('safe-buffer').Buffer var Base = require('cipher-base') var ZEROS = Buffer.alloc(128) var blocksize = 64 function Hmac (alg, key) { Base.call(this, 'digest') if (typeof key === 'string') { key = Buffer.from(key) } this._alg = alg this._key = key if (key.length > blocksize) { key = alg(key) } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } var ipad = this._ipad = Buffer.allocUnsafe(blocksize) var opad = this._opad = Buffer.allocUnsafe(blocksize) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } this._hash = [ipad] } inherits(Hmac, Base) Hmac.prototype._update = function (data) { this._hash.push(data) } Hmac.prototype._final = function () { var h = this._alg(Buffer.concat(this._hash)) return this._alg(Buffer.concat([this._opad, h])) } module.exports = Hmac },{"cipher-base":145,"inherits":334,"safe-buffer":537}],287:[function(require,module,exports){ 'use strict' exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') exports.createHash = exports.Hash = require('create-hash') exports.createHmac = exports.Hmac = require('create-hmac') var algos = require('browserify-sign/algos') var algoKeys = Object.keys(algos) var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) exports.getHashes = function () { return hashes } var p = require('pbkdf2') exports.pbkdf2 = p.pbkdf2 exports.pbkdf2Sync = p.pbkdf2Sync var aes = require('browserify-cipher') exports.Cipher = aes.Cipher exports.createCipher = aes.createCipher exports.Cipheriv = aes.Cipheriv exports.createCipheriv = aes.createCipheriv exports.Decipher = aes.Decipher exports.createDecipher = aes.createDecipher exports.Decipheriv = aes.Decipheriv exports.createDecipheriv = aes.createDecipheriv exports.getCiphers = aes.getCiphers exports.listCiphers = aes.listCiphers var dh = require('diffie-hellman') exports.DiffieHellmanGroup = dh.DiffieHellmanGroup exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup exports.getDiffieHellman = dh.getDiffieHellman exports.createDiffieHellman = dh.createDiffieHellman exports.DiffieHellman = dh.DiffieHellman var sign = require('browserify-sign') exports.createSign = sign.createSign exports.Sign = sign.Sign exports.createVerify = sign.createVerify exports.Verify = sign.Verify exports.createECDH = require('create-ecdh') var publicEncrypt = require('public-encrypt') exports.publicEncrypt = publicEncrypt.publicEncrypt exports.privateEncrypt = publicEncrypt.privateEncrypt exports.publicDecrypt = publicEncrypt.publicDecrypt exports.privateDecrypt = publicEncrypt.privateDecrypt // the least I can do is make error messages for the rest of the node.js/crypto api. // ;[ // 'createCredentials' // ].forEach(function (name) { // exports[name] = function () { // throw new Error([ // 'sorry, ' + name + ' is not implemented yet', // 'we accept pull requests', // 'https://github.com/crypto-browserify/crypto-browserify' // ].join('\n')) // } // }) var rf = require('randomfill') exports.randomFill = rf.randomFill exports.randomFillSync = rf.randomFillSync exports.createCredentials = function () { throw new Error([ 'sorry, createCredentials is not implemented yet', 'we accept pull requests', 'https://github.com/crypto-browserify/crypto-browserify' ].join('\n')) } exports.constants = { 'DH_CHECK_P_NOT_SAFE_PRIME': 2, 'DH_CHECK_P_NOT_PRIME': 1, 'DH_UNABLE_TO_CHECK_GENERATOR': 4, 'DH_NOT_SUITABLE_GENERATOR': 8, 'NPN_ENABLED': 1, 'ALPN_ENABLED': 1, 'RSA_PKCS1_PADDING': 1, 'RSA_SSLV23_PADDING': 2, 'RSA_NO_PADDING': 3, 'RSA_PKCS1_OAEP_PADDING': 4, 'RSA_X931_PADDING': 5, 'RSA_PKCS1_PSS_PADDING': 6, 'POINT_CONVERSION_COMPRESSED': 2, 'POINT_CONVERSION_UNCOMPRESSED': 4, 'POINT_CONVERSION_HYBRID': 6 } },{"browserify-cipher":111,"browserify-sign":118,"browserify-sign/algos":115,"create-ecdh":281,"create-hash":282,"create-hmac":285,"diffie-hellman":296,"pbkdf2":501,"public-encrypt":508,"randombytes":518,"randomfill":519}],288:[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 = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * 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; } // 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":289,"_process":507}],289:[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'); /** * 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 = {}; /** * Previous log timestamp. */ var prevTime; /** * 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) { 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); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * 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 split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (var 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 + '$')); } } } /** * 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) { 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":482}],290:[function(require,module,exports){ 'use strict'; exports.utils = require('./des/utils'); exports.Cipher = require('./des/cipher'); exports.DES = require('./des/des'); exports.CBC = require('./des/cbc'); exports.EDE = require('./des/ede'); },{"./des/cbc":291,"./des/cipher":292,"./des/des":293,"./des/ede":294,"./des/utils":295}],291:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); var inherits = require('inherits'); var proto = {}; function CBCState(iv) { assert.equal(iv.length, 8, 'Invalid IV length'); this.iv = new Array(8); for (var i = 0; i < this.iv.length; i++) this.iv[i] = iv[i]; } function instantiate(Base) { function CBC(options) { Base.call(this, options); this._cbcInit(); } inherits(CBC, Base); var keys = Object.keys(proto); for (var i = 0; i < keys.length; i++) { var key = keys[i]; CBC.prototype[key] = proto[key]; } CBC.create = function create(options) { return new CBC(options); }; return CBC; } exports.instantiate = instantiate; proto._cbcInit = function _cbcInit() { var state = new CBCState(this.options.iv); this._cbcState = state; }; proto._update = function _update(inp, inOff, out, outOff) { var state = this._cbcState; var superProto = this.constructor.super_.prototype; var iv = state.iv; if (this.type === 'encrypt') { for (var i = 0; i < this.blockSize; i++) iv[i] ^= inp[inOff + i]; superProto._update.call(this, iv, 0, out, outOff); for (var i = 0; i < this.blockSize; i++) iv[i] = out[outOff + i]; } else { superProto._update.call(this, inp, inOff, out, outOff); for (var i = 0; i < this.blockSize; i++) out[outOff + i] ^= iv[i]; for (var i = 0; i < this.blockSize; i++) iv[i] = inp[inOff + i]; } }; },{"inherits":334,"minimalistic-assert":342}],292:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); function Cipher(options) { this.options = options; this.type = this.options.type; this.blockSize = 8; this._init(); this.buffer = new Array(this.blockSize); this.bufferOff = 0; } module.exports = Cipher; Cipher.prototype._init = function _init() { // Might be overrided }; Cipher.prototype.update = function update(data) { if (data.length === 0) return []; if (this.type === 'decrypt') return this._updateDecrypt(data); else return this._updateEncrypt(data); }; Cipher.prototype._buffer = function _buffer(data, off) { // Append data to buffer var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); for (var i = 0; i < min; i++) this.buffer[this.bufferOff + i] = data[off + i]; this.bufferOff += min; // Shift next return min; }; Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { this._update(this.buffer, 0, out, off); this.bufferOff = 0; return this.blockSize; }; Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { var inputOff = 0; var outputOff = 0; var count = ((this.bufferOff + data.length) / this.blockSize) | 0; var out = new Array(count * this.blockSize); if (this.bufferOff !== 0) { inputOff += this._buffer(data, inputOff); if (this.bufferOff === this.buffer.length) outputOff += this._flushBuffer(out, outputOff); } // Write blocks var max = data.length - ((data.length - inputOff) % this.blockSize); for (; inputOff < max; inputOff += this.blockSize) { this._update(data, inputOff, out, outputOff); outputOff += this.blockSize; } // Queue rest for (; inputOff < data.length; inputOff++, this.bufferOff++) this.buffer[this.bufferOff] = data[inputOff]; return out; }; Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { var inputOff = 0; var outputOff = 0; var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; var out = new Array(count * this.blockSize); // TODO(indutny): optimize it, this is far from optimal for (; count > 0; count--) { inputOff += this._buffer(data, inputOff); outputOff += this._flushBuffer(out, outputOff); } // Buffer rest of the input inputOff += this._buffer(data, inputOff); return out; }; Cipher.prototype.final = function final(buffer) { var first; if (buffer) first = this.update(buffer); var last; if (this.type === 'encrypt') last = this._finalEncrypt(); else last = this._finalDecrypt(); if (first) return first.concat(last); else return last; }; Cipher.prototype._pad = function _pad(buffer, off) { if (off === 0) return false; while (off < buffer.length) buffer[off++] = 0; return true; }; Cipher.prototype._finalEncrypt = function _finalEncrypt() { if (!this._pad(this.buffer, this.bufferOff)) return []; var out = new Array(this.blockSize); this._update(this.buffer, 0, out, 0); return out; }; Cipher.prototype._unpad = function _unpad(buffer) { return buffer; }; Cipher.prototype._finalDecrypt = function _finalDecrypt() { assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); var out = new Array(this.blockSize); this._flushBuffer(out, 0); return this._unpad(out); }; },{"minimalistic-assert":342}],293:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); var inherits = require('inherits'); var des = require('../des'); var utils = des.utils; var Cipher = des.Cipher; function DESState() { this.tmp = new Array(2); this.keys = null; } function DES(options) { Cipher.call(this, options); var state = new DESState(); this._desState = state; this.deriveKeys(state, options.key); } inherits(DES, Cipher); module.exports = DES; DES.create = function create(options) { return new DES(options); }; var shiftTable = [ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ]; DES.prototype.deriveKeys = function deriveKeys(state, key) { state.keys = new Array(16 * 2); assert.equal(key.length, this.blockSize, 'Invalid key length'); var kL = utils.readUInt32BE(key, 0); var kR = utils.readUInt32BE(key, 4); utils.pc1(kL, kR, state.tmp, 0); kL = state.tmp[0]; kR = state.tmp[1]; for (var i = 0; i < state.keys.length; i += 2) { var shift = shiftTable[i >>> 1]; kL = utils.r28shl(kL, shift); kR = utils.r28shl(kR, shift); utils.pc2(kL, kR, state.keys, i); } }; DES.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._desState; var l = utils.readUInt32BE(inp, inOff); var r = utils.readUInt32BE(inp, inOff + 4); // Initial Permutation utils.ip(l, r, state.tmp, 0); l = state.tmp[0]; r = state.tmp[1]; if (this.type === 'encrypt') this._encrypt(state, l, r, state.tmp, 0); else this._decrypt(state, l, r, state.tmp, 0); l = state.tmp[0]; r = state.tmp[1]; utils.writeUInt32BE(out, l, outOff); utils.writeUInt32BE(out, r, outOff + 4); }; DES.prototype._pad = function _pad(buffer, off) { var value = buffer.length - off; for (var i = off; i < buffer.length; i++) buffer[i] = value; return true; }; DES.prototype._unpad = function _unpad(buffer) { var pad = buffer[buffer.length - 1]; for (var i = buffer.length - pad; i < buffer.length; i++) assert.equal(buffer[i], pad); return buffer.slice(0, buffer.length - pad); }; DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { var l = lStart; var r = rStart; // Apply f() x16 times for (var i = 0; i < state.keys.length; i += 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; // f(r, k) utils.expand(r, state.tmp, 0); keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); var t = r; r = (l ^ f) >>> 0; l = t; } // Reverse Initial Permutation utils.rip(r, l, out, off); }; DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { var l = rStart; var r = lStart; // Apply f() x16 times for (var i = state.keys.length - 2; i >= 0; i -= 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; // f(r, k) utils.expand(l, state.tmp, 0); keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); var t = l; l = (r ^ f) >>> 0; r = t; } // Reverse Initial Permutation utils.rip(l, r, out, off); }; },{"../des":290,"inherits":334,"minimalistic-assert":342}],294:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); var inherits = require('inherits'); var des = require('../des'); var Cipher = des.Cipher; var DES = des.DES; function EDEState(type, key) { assert.equal(key.length, 24, 'Invalid key length'); var k1 = key.slice(0, 8); var k2 = key.slice(8, 16); var k3 = key.slice(16, 24); if (type === 'encrypt') { this.ciphers = [ DES.create({ type: 'encrypt', key: k1 }), DES.create({ type: 'decrypt', key: k2 }), DES.create({ type: 'encrypt', key: k3 }) ]; } else { this.ciphers = [ DES.create({ type: 'decrypt', key: k3 }), DES.create({ type: 'encrypt', key: k2 }), DES.create({ type: 'decrypt', key: k1 }) ]; } } function EDE(options) { Cipher.call(this, options); var state = new EDEState(this.type, this.options.key); this._edeState = state; } inherits(EDE, Cipher); module.exports = EDE; EDE.create = function create(options) { return new EDE(options); }; EDE.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._edeState; state.ciphers[0]._update(inp, inOff, out, outOff); state.ciphers[1]._update(out, outOff, out, outOff); state.ciphers[2]._update(out, outOff, out, outOff); }; EDE.prototype._pad = DES.prototype._pad; EDE.prototype._unpad = DES.prototype._unpad; },{"../des":290,"inherits":334,"minimalistic-assert":342}],295:[function(require,module,exports){ 'use strict'; exports.readUInt32BE = function readUInt32BE(bytes, off) { var res = (bytes[0 + off] << 24) | (bytes[1 + off] << 16) | (bytes[2 + off] << 8) | bytes[3 + off]; return res >>> 0; }; exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { bytes[0 + off] = value >>> 24; bytes[1 + off] = (value >>> 16) & 0xff; bytes[2 + off] = (value >>> 8) & 0xff; bytes[3 + off] = value & 0xff; }; exports.ip = function ip(inL, inR, out, off) { var outL = 0; var outR = 0; for (var i = 6; i >= 0; i -= 2) { for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inR >>> (j + i)) & 1; } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inL >>> (j + i)) & 1; } } for (var i = 6; i >= 0; i -= 2) { for (var j = 1; j <= 25; j += 8) { outR <<= 1; outR |= (inR >>> (j + i)) & 1; } for (var j = 1; j <= 25; j += 8) { outR <<= 1; outR |= (inL >>> (j + i)) & 1; } } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.rip = function rip(inL, inR, out, off) { var outL = 0; var outR = 0; for (var i = 0; i < 4; i++) { for (var j = 24; j >= 0; j -= 8) { outL <<= 1; outL |= (inR >>> (j + i)) & 1; outL <<= 1; outL |= (inL >>> (j + i)) & 1; } } for (var i = 4; i < 8; i++) { for (var j = 24; j >= 0; j -= 8) { outR <<= 1; outR |= (inR >>> (j + i)) & 1; outR <<= 1; outR |= (inL >>> (j + i)) & 1; } } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.pc1 = function pc1(inL, inR, out, off) { var outL = 0; var outR = 0; // 7, 15, 23, 31, 39, 47, 55, 63 // 6, 14, 22, 30, 39, 47, 55, 63 // 5, 13, 21, 29, 39, 47, 55, 63 // 4, 12, 20, 28 for (var i = 7; i >= 5; i--) { for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inR >> (j + i)) & 1; } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inL >> (j + i)) & 1; } } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inR >> (j + i)) & 1; } // 1, 9, 17, 25, 33, 41, 49, 57 // 2, 10, 18, 26, 34, 42, 50, 58 // 3, 11, 19, 27, 35, 43, 51, 59 // 36, 44, 52, 60 for (var i = 1; i <= 3; i++) { for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= (inR >> (j + i)) & 1; } for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= (inL >> (j + i)) & 1; } } for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= (inL >> (j + i)) & 1; } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.r28shl = function r28shl(num, shift) { return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); }; var pc2table = [ // inL => outL 14, 11, 17, 4, 27, 23, 25, 0, 13, 22, 7, 18, 5, 9, 16, 24, 2, 20, 12, 21, 1, 8, 15, 26, // inR => outR 15, 4, 25, 19, 9, 1, 26, 16, 5, 11, 23, 8, 12, 7, 17, 0, 22, 3, 10, 14, 6, 20, 27, 24 ]; exports.pc2 = function pc2(inL, inR, out, off) { var outL = 0; var outR = 0; var len = pc2table.length >>> 1; for (var i = 0; i < len; i++) { outL <<= 1; outL |= (inL >>> pc2table[i]) & 0x1; } for (var i = len; i < pc2table.length; i++) { outR <<= 1; outR |= (inR >>> pc2table[i]) & 0x1; } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.expand = function expand(r, out, off) { var outL = 0; var outR = 0; outL = ((r & 1) << 5) | (r >>> 27); for (var i = 23; i >= 15; i -= 4) { outL <<= 6; outL |= (r >>> i) & 0x3f; } for (var i = 11; i >= 3; i -= 4) { outR |= (r >>> i) & 0x3f; outR <<= 6; } outR |= ((r & 0x1f) << 1) | (r >>> 31); out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; var sTable = [ 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 ]; exports.substitute = function substitute(inL, inR) { var out = 0; for (var i = 0; i < 4; i++) { var b = (inL >>> (18 - i * 6)) & 0x3f; var sb = sTable[i * 0x40 + b]; out <<= 4; out |= sb; } for (var i = 0; i < 4; i++) { var b = (inR >>> (18 - i * 6)) & 0x3f; var sb = sTable[4 * 0x40 + i * 0x40 + b]; out <<= 4; out |= sb; } return out >>> 0; }; var permuteTable = [ 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 ]; exports.permute = function permute(num) { var out = 0; for (var i = 0; i < permuteTable.length; i++) { out <<= 1; out |= (num >>> permuteTable[i]) & 0x1; } return out >>> 0; }; exports.padSplit = function padSplit(num, size, group) { var str = num.toString(2); while (str.length < size) str = '0' + str; var out = []; for (var i = 0; i < size; i += group) out.push(str.slice(i, i + group)); return out.join(' '); }; },{}],296:[function(require,module,exports){ (function (Buffer){ var generatePrime = require('./lib/generatePrime') var primes = require('./lib/primes.json') var DH = require('./lib/dh') function getDiffieHellman (mod) { var prime = new Buffer(primes[mod].prime, 'hex') var gen = new Buffer(primes[mod].gen, 'hex') return new DH(prime, gen) } var ENCODINGS = { 'binary': true, 'hex': true, 'base64': true } function createDiffieHellman (prime, enc, generator, genc) { if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { return createDiffieHellman(prime, 'binary', enc, generator) } enc = enc || 'binary' genc = genc || 'binary' generator = generator || new Buffer([2]) if (!Buffer.isBuffer(generator)) { generator = new Buffer(generator, genc) } if (typeof prime === 'number') { return new DH(generatePrime(prime, generator), generator, true) } if (!Buffer.isBuffer(prime)) { prime = new Buffer(prime, enc) } return new DH(prime, generator, true) } exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman }).call(this,require("buffer").Buffer) },{"./lib/dh":297,"./lib/generatePrime":298,"./lib/primes.json":299,"buffer":144}],297:[function(require,module,exports){ (function (Buffer){ var BN = require('bn.js'); var MillerRabin = require('miller-rabin'); var millerRabin = new MillerRabin(); var TWENTYFOUR = new BN(24); var ELEVEN = new BN(11); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); var primes = require('./generatePrime'); var randomBytes = require('randombytes'); module.exports = DH; function setPublicKey(pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { pub = new Buffer(pub, enc); } this._pub = new BN(pub); return this; } function setPrivateKey(priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { priv = new Buffer(priv, enc); } this._priv = new BN(priv); return this; } var primeCache = {}; function checkPrime(prime, generator) { var gen = generator.toString('hex'); var hex = [gen, prime.toString(16)].join('_'); if (hex in primeCache) { return primeCache[hex]; } var error = 0; if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) { //not a prime so +1 error += 1; if (gen === '02' || gen === '05') { // we'd be able to check the generator // it would fail so +8 error += 8; } else { //we wouldn't be able to test the generator // so +4 error += 4; } primeCache[hex] = error; return error; } if (!millerRabin.test(prime.shrn(1))) { //not a safe prime error += 2; } var rem; switch (gen) { case '02': if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { // unsuidable generator error += 8; } break; case '05': rem = prime.mod(TEN); if (rem.cmp(THREE) && rem.cmp(SEVEN)) { // prime mod 10 needs to equal 3 or 7 error += 8; } break; default: error += 4; } primeCache[hex] = error; return error; } function DH(prime, generator, malleable) { this.setGenerator(generator); this.__prime = new BN(prime); this._prime = BN.mont(this.__prime); this._primeLen = prime.length; this._pub = undefined; this._priv = undefined; this._primeCode = undefined; if (malleable) { this.setPublicKey = setPublicKey; this.setPrivateKey = setPrivateKey; } else { this._primeCode = 8; } } Object.defineProperty(DH.prototype, 'verifyError', { enumerable: true, get: function () { if (typeof this._primeCode !== 'number') { this._primeCode = checkPrime(this.__prime, this.__gen); } return this._primeCode; } }); DH.prototype.generateKeys = function () { if (!this._priv) { this._priv = new BN(randomBytes(this._primeLen)); } this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); return this.getPublicKey(); }; DH.prototype.computeSecret = function (other) { other = new BN(other); other = other.toRed(this._prime); var secret = other.redPow(this._priv).fromRed(); var out = new Buffer(secret.toArray()); var prime = this.getPrime(); if (out.length < prime.length) { var front = new Buffer(prime.length - out.length); front.fill(0); out = Buffer.concat([front, out]); } return out; }; DH.prototype.getPublicKey = function getPublicKey(enc) { return formatReturnValue(this._pub, enc); }; DH.prototype.getPrivateKey = function getPrivateKey(enc) { return formatReturnValue(this._priv, enc); }; DH.prototype.getPrime = function (enc) { return formatReturnValue(this.__prime, enc); }; DH.prototype.getGenerator = function (enc) { return formatReturnValue(this._gen, enc); }; DH.prototype.setGenerator = function (gen, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(gen)) { gen = new Buffer(gen, enc); } this.__gen = gen; this._gen = new BN(gen); return this; }; function formatReturnValue(bn, enc) { var buf = new Buffer(bn.toArray()); if (!enc) { return buf; } else { return buf.toString(enc); } } }).call(this,require("buffer").Buffer) },{"./generatePrime":298,"bn.js":91,"buffer":144,"miller-rabin":341,"randombytes":518}],298:[function(require,module,exports){ var randomBytes = require('randombytes'); module.exports = findPrime; findPrime.simpleSieve = simpleSieve; findPrime.fermatTest = fermatTest; var BN = require('bn.js'); var TWENTYFOUR = new BN(24); var MillerRabin = require('miller-rabin'); var millerRabin = new MillerRabin(); var ONE = new BN(1); var TWO = new BN(2); var FIVE = new BN(5); var SIXTEEN = new BN(16); var EIGHT = new BN(8); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); var ELEVEN = new BN(11); var FOUR = new BN(4); var TWELVE = new BN(12); var primes = null; function _getPrimes() { if (primes !== null) return primes; var limit = 0x100000; var res = []; res[0] = 2; for (var i = 1, k = 3; k < limit; k += 2) { var sqrt = Math.ceil(Math.sqrt(k)); for (var j = 0; j < i && res[j] <= sqrt; j++) if (k % res[j] === 0) break; if (i !== j && res[j] <= sqrt) continue; res[i++] = k; } primes = res; return res; } function simpleSieve(p) { var primes = _getPrimes(); for (var i = 0; i < primes.length; i++) if (p.modn(primes[i]) === 0) { if (p.cmpn(primes[i]) === 0) { return true; } else { return false; } } return true; } function fermatTest(p) { var red = BN.mont(p); return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; } function findPrime(bits, gen) { if (bits < 16) { // this is what openssl does if (gen === 2 || gen === 5) { return new BN([0x8c, 0x7b]); } else { return new BN([0x8c, 0x27]); } } gen = new BN(gen); var num, n2; while (true) { num = new BN(randomBytes(Math.ceil(bits / 8))); while (num.bitLength() > bits) { num.ishrn(1); } if (num.isEven()) { num.iadd(ONE); } if (!num.testn(1)) { num.iadd(TWO); } if (!gen.cmp(TWO)) { while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { num.iadd(FOUR); } } else if (!gen.cmp(FIVE)) { while (num.mod(TEN).cmp(THREE)) { num.iadd(FOUR); } } n2 = num.shrn(1); if (simpleSieve(n2) && simpleSieve(num) && fermatTest(n2) && fermatTest(num) && millerRabin.test(n2) && millerRabin.test(num)) { return num; } } } },{"bn.js":91,"miller-rabin":341,"randombytes":518}],299:[function(require,module,exports){ module.exports={ "modp1": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" }, "modp2": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" }, "modp5": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" }, "modp14": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" }, "modp15": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" }, "modp16": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" }, "modp17": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" }, "modp18": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" } } },{}],300:[function(require,module,exports){ 'use strict'; var elliptic = exports; elliptic.version = require('../package.json').version; elliptic.utils = require('./elliptic/utils'); elliptic.rand = require('brorand'); elliptic.curve = require('./elliptic/curve'); elliptic.curves = require('./elliptic/curves'); // Protocols elliptic.ec = require('./elliptic/ec'); elliptic.eddsa = require('./elliptic/eddsa'); },{"../package.json":315,"./elliptic/curve":303,"./elliptic/curves":306,"./elliptic/ec":307,"./elliptic/eddsa":310,"./elliptic/utils":314,"brorand":92}],301:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); var elliptic = require('../../elliptic'); var utils = elliptic.utils; var getNAF = utils.getNAF; var getJSF = utils.getJSF; var assert = utils.assert; function BaseCurve(type, conf) { this.type = type; this.p = new BN(conf.p, 16); // Use Montgomery, when there is no fast reduction for the prime this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); // Useful for many curves this.zero = new BN(0).toRed(this.red); this.one = new BN(1).toRed(this.red); this.two = new BN(2).toRed(this.red); // Curve configuration, optional this.n = conf.n && new BN(conf.n, 16); this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); // Temporary arrays this._wnafT1 = new Array(4); this._wnafT2 = new Array(4); this._wnafT3 = new Array(4); this._wnafT4 = new Array(4); // Generalized Greg Maxwell's trick var adjustCount = this.n && this.p.div(this.n); if (!adjustCount || adjustCount.cmpn(100) > 0) { this.redN = null; } else { this._maxwellTrick = true; this.redN = this.n.toRed(this.red); } } module.exports = BaseCurve; BaseCurve.prototype.point = function point() { throw new Error('Not implemented'); }; BaseCurve.prototype.validate = function validate() { throw new Error('Not implemented'); }; BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { assert(p.precomputed); var doubles = p._getDoubles(); var naf = getNAF(k, 1); var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); I /= 3; // Translate into more windowed form var repr = []; for (var j = 0; j < naf.length; j += doubles.step) { var nafW = 0; for (var k = j + doubles.step - 1; k >= j; k--) nafW = (nafW << 1) + naf[k]; repr.push(nafW); } var a = this.jpoint(null, null, null); var b = this.jpoint(null, null, null); for (var i = I; i > 0; i--) { for (var j = 0; j < repr.length; j++) { var nafW = repr[j]; if (nafW === i) b = b.mixedAdd(doubles.points[j]); else if (nafW === -i) b = b.mixedAdd(doubles.points[j].neg()); } a = a.add(b); } return a.toP(); }; BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { var w = 4; // Precompute window var nafPoints = p._getNAFPoints(w); w = nafPoints.wnd; var wnd = nafPoints.points; // Get NAF form var naf = getNAF(k, w); // Add `this`*(N+1) for every w-NAF index var acc = this.jpoint(null, null, null); for (var i = naf.length - 1; i >= 0; i--) { // Count zeroes for (var k = 0; i >= 0 && naf[i] === 0; i--) k++; if (i >= 0) k++; acc = acc.dblp(k); if (i < 0) break; var z = naf[i]; assert(z !== 0); if (p.type === 'affine') { // J +- P if (z > 0) acc = acc.mixedAdd(wnd[(z - 1) >> 1]); else acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); } else { // J +- J if (z > 0) acc = acc.add(wnd[(z - 1) >> 1]); else acc = acc.add(wnd[(-z - 1) >> 1].neg()); } } return p.type === 'affine' ? acc.toP() : acc; }; BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) { var wndWidth = this._wnafT1; var wnd = this._wnafT2; var naf = this._wnafT3; // Fill all arrays var max = 0; for (var i = 0; i < len; i++) { var p = points[i]; var nafPoints = p._getNAFPoints(defW); wndWidth[i] = nafPoints.wnd; wnd[i] = nafPoints.points; } // Comb small window NAFs for (var i = len - 1; i >= 1; i -= 2) { var a = i - 1; var b = i; if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { naf[a] = getNAF(coeffs[a], wndWidth[a]); naf[b] = getNAF(coeffs[b], wndWidth[b]); max = Math.max(naf[a].length, max); max = Math.max(naf[b].length, max); continue; } var comb = [ points[a], /* 1 */ null, /* 3 */ null, /* 5 */ points[b] /* 7 */ ]; // Try to avoid Projective points, if possible if (points[a].y.cmp(points[b].y) === 0) { comb[1] = points[a].add(points[b]); comb[2] = points[a].toJ().mixedAdd(points[b].neg()); } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { comb[1] = points[a].toJ().mixedAdd(points[b]); comb[2] = points[a].add(points[b].neg()); } else { comb[1] = points[a].toJ().mixedAdd(points[b]); comb[2] = points[a].toJ().mixedAdd(points[b].neg()); } var index = [ -3, /* -1 -1 */ -1, /* -1 0 */ -5, /* -1 1 */ -7, /* 0 -1 */ 0, /* 0 0 */ 7, /* 0 1 */ 5, /* 1 -1 */ 1, /* 1 0 */ 3 /* 1 1 */ ]; var jsf = getJSF(coeffs[a], coeffs[b]); max = Math.max(jsf[0].length, max); naf[a] = new Array(max); naf[b] = new Array(max); for (var j = 0; j < max; j++) { var ja = jsf[0][j] | 0; var jb = jsf[1][j] | 0; naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; naf[b][j] = 0; wnd[a] = comb; } } var acc = this.jpoint(null, null, null); var tmp = this._wnafT4; for (var i = max; i >= 0; i--) { var k = 0; while (i >= 0) { var zero = true; for (var j = 0; j < len; j++) { tmp[j] = naf[j][i] | 0; if (tmp[j] !== 0) zero = false; } if (!zero) break; k++; i--; } if (i >= 0) k++; acc = acc.dblp(k); if (i < 0) break; for (var j = 0; j < len; j++) { var z = tmp[j]; var p; if (z === 0) continue; else if (z > 0) p = wnd[j][(z - 1) >> 1]; else if (z < 0) p = wnd[j][(-z - 1) >> 1].neg(); if (p.type === 'affine') acc = acc.mixedAdd(p); else acc = acc.add(p); } } // Zeroify references for (var i = 0; i < len; i++) wnd[i] = null; if (jacobianResult) return acc; else return acc.toP(); }; function BasePoint(curve, type) { this.curve = curve; this.type = type; this.precomputed = null; } BaseCurve.BasePoint = BasePoint; BasePoint.prototype.eq = function eq(/*other*/) { throw new Error('Not implemented'); }; BasePoint.prototype.validate = function validate() { return this.curve.validate(this); }; BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { bytes = utils.toArray(bytes, enc); var len = this.p.byteLength(); // uncompressed, hybrid-odd, hybrid-even if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && bytes.length - 1 === 2 * len) { if (bytes[0] === 0x06) assert(bytes[bytes.length - 1] % 2 === 0); else if (bytes[0] === 0x07) assert(bytes[bytes.length - 1] % 2 === 1); var res = this.point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len)); return res; } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && bytes.length - 1 === len) { return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); } throw new Error('Unknown point format'); }; BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { return this.encode(enc, true); }; BasePoint.prototype._encode = function _encode(compact) { var len = this.curve.p.byteLength(); var x = this.getX().toArray('be', len); if (compact) return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; }; BasePoint.prototype.encode = function encode(enc, compact) { return utils.encode(this._encode(compact), enc); }; BasePoint.prototype.precompute = function precompute(power) { if (this.precomputed) return this; var precomputed = { doubles: null, naf: null, beta: null }; precomputed.naf = this._getNAFPoints(8); precomputed.doubles = this._getDoubles(4, power); precomputed.beta = this._getBeta(); this.precomputed = precomputed; return this; }; BasePoint.prototype._hasDoubles = function _hasDoubles(k) { if (!this.precomputed) return false; var doubles = this.precomputed.doubles; if (!doubles) return false; return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); }; BasePoint.prototype._getDoubles = function _getDoubles(step, power) { if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; var doubles = [ this ]; var acc = this; for (var i = 0; i < power; i += step) { for (var j = 0; j < step; j++) acc = acc.dbl(); doubles.push(acc); } return { step: step, points: doubles }; }; BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; var res = [ this ]; var max = (1 << wnd) - 1; var dbl = max === 1 ? null : this.dbl(); for (var i = 1; i < max; i++) res[i] = res[i - 1].add(dbl); return { wnd: wnd, points: res }; }; BasePoint.prototype._getBeta = function _getBeta() { return null; }; BasePoint.prototype.dblp = function dblp(k) { var r = this; for (var i = 0; i < k; i++) r = r.dbl(); return r; }; },{"../../elliptic":300,"bn.js":91}],302:[function(require,module,exports){ 'use strict'; var curve = require('../curve'); var elliptic = require('../../elliptic'); var BN = require('bn.js'); var inherits = require('inherits'); var Base = curve.base; var assert = elliptic.utils.assert; function EdwardsCurve(conf) { // NOTE: Important as we are creating point in Base.call() this.twisted = (conf.a | 0) !== 1; this.mOneA = this.twisted && (conf.a | 0) === -1; this.extended = this.mOneA; Base.call(this, 'edwards', conf); this.a = new BN(conf.a, 16).umod(this.red.m); this.a = this.a.toRed(this.red); this.c = new BN(conf.c, 16).toRed(this.red); this.c2 = this.c.redSqr(); this.d = new BN(conf.d, 16).toRed(this.red); this.dd = this.d.redAdd(this.d); assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); this.oneC = (conf.c | 0) === 1; } inherits(EdwardsCurve, Base); module.exports = EdwardsCurve; EdwardsCurve.prototype._mulA = function _mulA(num) { if (this.mOneA) return num.redNeg(); else return this.a.redMul(num); }; EdwardsCurve.prototype._mulC = function _mulC(num) { if (this.oneC) return num; else return this.c.redMul(num); }; // Just for compatibility with Short curve EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { return this.point(x, y, z, t); }; EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { x = new BN(x, 16); if (!x.red) x = x.toRed(this.red); var x2 = x.redSqr(); var rhs = this.c2.redSub(this.a.redMul(x2)); var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); var y2 = rhs.redMul(lhs.redInvm()); var y = y2.redSqrt(); if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point'); var isOdd = y.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); return this.point(x, y); }; EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { y = new BN(y, 16); if (!y.red) y = y.toRed(this.red); // x^2 = (y^2 - 1) / (d y^2 + 1) var y2 = y.redSqr(); var lhs = y2.redSub(this.one); var rhs = y2.redMul(this.d).redAdd(this.one); var x2 = lhs.redMul(rhs.redInvm()); if (x2.cmp(this.zero) === 0) { if (odd) throw new Error('invalid point'); else return this.point(this.zero, y); } var x = x2.redSqrt(); if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) throw new Error('invalid point'); if (x.isOdd() !== odd) x = x.redNeg(); return this.point(x, y); }; EdwardsCurve.prototype.validate = function validate(point) { if (point.isInfinity()) return true; // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) point.normalize(); var x2 = point.x.redSqr(); var y2 = point.y.redSqr(); var lhs = x2.redMul(this.a).redAdd(y2); var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); return lhs.cmp(rhs) === 0; }; function Point(curve, x, y, z, t) { Base.BasePoint.call(this, curve, 'projective'); if (x === null && y === null && z === null) { this.x = this.curve.zero; this.y = this.curve.one; this.z = this.curve.one; this.t = this.curve.zero; this.zOne = true; } else { this.x = new BN(x, 16); this.y = new BN(y, 16); this.z = z ? new BN(z, 16) : this.curve.one; this.t = t && new BN(t, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); if (this.t && !this.t.red) this.t = this.t.toRed(this.curve.red); this.zOne = this.z === this.curve.one; // Use extended coordinates if (this.curve.extended && !this.t) { this.t = this.x.redMul(this.y); if (!this.zOne) this.t = this.t.redMul(this.z.redInvm()); } } } inherits(Point, Base.BasePoint); EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); }; EdwardsCurve.prototype.point = function point(x, y, z, t) { return new Point(this, x, y, z, t); }; Point.fromJSON = function fromJSON(curve, obj) { return new Point(curve, obj[0], obj[1], obj[2]); }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.x.cmpn(0) === 0 && this.y.cmp(this.z) === 0; }; Point.prototype._extDbl = function _extDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #doubling-dbl-2008-hwcd // 4M + 4S // A = X1^2 var a = this.x.redSqr(); // B = Y1^2 var b = this.y.redSqr(); // C = 2 * Z1^2 var c = this.z.redSqr(); c = c.redIAdd(c); // D = a * A var d = this.curve._mulA(a); // E = (X1 + Y1)^2 - A - B var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); // G = D + B var g = d.redAdd(b); // F = G - C var f = g.redSub(c); // H = D - B var h = d.redSub(b); // X3 = E * F var nx = e.redMul(f); // Y3 = G * H var ny = g.redMul(h); // T3 = E * H var nt = e.redMul(h); // Z3 = F * G var nz = f.redMul(g); return this.curve.point(nx, ny, nz, nt); }; Point.prototype._projDbl = function _projDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #doubling-dbl-2008-bbjlp // #doubling-dbl-2007-bl // and others // Generally 3M + 4S or 2M + 4S // B = (X1 + Y1)^2 var b = this.x.redAdd(this.y).redSqr(); // C = X1^2 var c = this.x.redSqr(); // D = Y1^2 var d = this.y.redSqr(); var nx; var ny; var nz; if (this.curve.twisted) { // E = a * C var e = this.curve._mulA(c); // F = E + D var f = e.redAdd(d); if (this.zOne) { // X3 = (B - C - D) * (F - 2) nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); // Y3 = F * (E - D) ny = f.redMul(e.redSub(d)); // Z3 = F^2 - 2 * F nz = f.redSqr().redSub(f).redSub(f); } else { // H = Z1^2 var h = this.z.redSqr(); // J = F - 2 * H var j = f.redSub(h).redISub(h); // X3 = (B-C-D)*J nx = b.redSub(c).redISub(d).redMul(j); // Y3 = F * (E - D) ny = f.redMul(e.redSub(d)); // Z3 = F * J nz = f.redMul(j); } } else { // E = C + D var e = c.redAdd(d); // H = (c * Z1)^2 var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); // J = E - 2 * H var j = e.redSub(h).redSub(h); // X3 = c * (B - E) * J nx = this.curve._mulC(b.redISub(e)).redMul(j); // Y3 = c * E * (C - D) ny = this.curve._mulC(e).redMul(c.redISub(d)); // Z3 = E * J nz = e.redMul(j); } return this.curve.point(nx, ny, nz); }; Point.prototype.dbl = function dbl() { if (this.isInfinity()) return this; // Double in extended coordinates if (this.curve.extended) return this._extDbl(); else return this._projDbl(); }; Point.prototype._extAdd = function _extAdd(p) { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #addition-add-2008-hwcd-3 // 8M // A = (Y1 - X1) * (Y2 - X2) var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); // B = (Y1 + X1) * (Y2 + X2) var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); // C = T1 * k * T2 var c = this.t.redMul(this.curve.dd).redMul(p.t); // D = Z1 * 2 * Z2 var d = this.z.redMul(p.z.redAdd(p.z)); // E = B - A var e = b.redSub(a); // F = D - C var f = d.redSub(c); // G = D + C var g = d.redAdd(c); // H = B + A var h = b.redAdd(a); // X3 = E * F var nx = e.redMul(f); // Y3 = G * H var ny = g.redMul(h); // T3 = E * H var nt = e.redMul(h); // Z3 = F * G var nz = f.redMul(g); return this.curve.point(nx, ny, nz, nt); }; Point.prototype._projAdd = function _projAdd(p) { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #addition-add-2008-bbjlp // #addition-add-2007-bl // 10M + 1S // A = Z1 * Z2 var a = this.z.redMul(p.z); // B = A^2 var b = a.redSqr(); // C = X1 * X2 var c = this.x.redMul(p.x); // D = Y1 * Y2 var d = this.y.redMul(p.y); // E = d * C * D var e = this.curve.d.redMul(c).redMul(d); // F = B - E var f = b.redSub(e); // G = B + E var g = b.redAdd(e); // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); var nx = a.redMul(f).redMul(tmp); var ny; var nz; if (this.curve.twisted) { // Y3 = A * G * (D - a * C) ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); // Z3 = F * G nz = f.redMul(g); } else { // Y3 = A * G * (D - C) ny = a.redMul(g).redMul(d.redSub(c)); // Z3 = c * F * G nz = this.curve._mulC(f).redMul(g); } return this.curve.point(nx, ny, nz); }; Point.prototype.add = function add(p) { if (this.isInfinity()) return p; if (p.isInfinity()) return this; if (this.curve.extended) return this._extAdd(p); else return this._projAdd(p); }; Point.prototype.mul = function mul(k) { if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k); else return this.curve._wnafMul(this, k); }; Point.prototype.mulAdd = function mulAdd(k1, p, k2) { return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); }; Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); }; Point.prototype.normalize = function normalize() { if (this.zOne) return this; // Normalize coordinates var zi = this.z.redInvm(); this.x = this.x.redMul(zi); this.y = this.y.redMul(zi); if (this.t) this.t = this.t.redMul(zi); this.z = this.curve.one; this.zOne = true; return this; }; Point.prototype.neg = function neg() { return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg()); }; Point.prototype.getX = function getX() { this.normalize(); return this.x.fromRed(); }; Point.prototype.getY = function getY() { this.normalize(); return this.y.fromRed(); }; Point.prototype.eq = function eq(other) { return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0; }; Point.prototype.eqXToP = function eqXToP(x) { var rx = x.toRed(this.curve.red).redMul(this.z); if (this.x.cmp(rx) === 0) return true; var xc = x.clone(); var t = this.curve.redN.redMul(this.z); for (;;) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } return false; }; // Compatibility with BaseCurve Point.prototype.toP = Point.prototype.normalize; Point.prototype.mixedAdd = Point.prototype.add; },{"../../elliptic":300,"../curve":303,"bn.js":91,"inherits":334}],303:[function(require,module,exports){ 'use strict'; var curve = exports; curve.base = require('./base'); curve.short = require('./short'); curve.mont = require('./mont'); curve.edwards = require('./edwards'); },{"./base":301,"./edwards":302,"./mont":304,"./short":305}],304:[function(require,module,exports){ 'use strict'; var curve = require('../curve'); var BN = require('bn.js'); var inherits = require('inherits'); var Base = curve.base; var elliptic = require('../../elliptic'); var utils = elliptic.utils; function MontCurve(conf) { Base.call(this, 'mont', conf); this.a = new BN(conf.a, 16).toRed(this.red); this.b = new BN(conf.b, 16).toRed(this.red); this.i4 = new BN(4).toRed(this.red).redInvm(); this.two = new BN(2).toRed(this.red); this.a24 = this.i4.redMul(this.a.redAdd(this.two)); } inherits(MontCurve, Base); module.exports = MontCurve; MontCurve.prototype.validate = function validate(point) { var x = point.normalize().x; var x2 = x.redSqr(); var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); var y = rhs.redSqrt(); return y.redSqr().cmp(rhs) === 0; }; function Point(curve, x, z) { Base.BasePoint.call(this, curve, 'projective'); if (x === null && z === null) { this.x = this.curve.one; this.z = this.curve.zero; } else { this.x = new BN(x, 16); this.z = new BN(z, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); } } inherits(Point, Base.BasePoint); MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { return this.point(utils.toArray(bytes, enc), 1); }; MontCurve.prototype.point = function point(x, z) { return new Point(this, x, z); }; MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { return Point.fromJSON(this, obj); }; Point.prototype.precompute = function precompute() { // No-op }; Point.prototype._encode = function _encode() { return this.getX().toArray('be', this.curve.p.byteLength()); }; Point.fromJSON = function fromJSON(curve, obj) { return new Point(curve, obj[0], obj[1] || curve.one); }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.z.cmpn(0) === 0; }; Point.prototype.dbl = function dbl() { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 // 2M + 2S + 4A // A = X1 + Z1 var a = this.x.redAdd(this.z); // AA = A^2 var aa = a.redSqr(); // B = X1 - Z1 var b = this.x.redSub(this.z); // BB = B^2 var bb = b.redSqr(); // C = AA - BB var c = aa.redSub(bb); // X3 = AA * BB var nx = aa.redMul(bb); // Z3 = C * (BB + A24 * C) var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); return this.curve.point(nx, nz); }; Point.prototype.add = function add() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.diffAdd = function diffAdd(p, diff) { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 // 4M + 2S + 6A // A = X2 + Z2 var a = this.x.redAdd(this.z); // B = X2 - Z2 var b = this.x.redSub(this.z); // C = X3 + Z3 var c = p.x.redAdd(p.z); // D = X3 - Z3 var d = p.x.redSub(p.z); // DA = D * A var da = d.redMul(a); // CB = C * B var cb = c.redMul(b); // X5 = Z1 * (DA + CB)^2 var nx = diff.z.redMul(da.redAdd(cb).redSqr()); // Z5 = X1 * (DA - CB)^2 var nz = diff.x.redMul(da.redISub(cb).redSqr()); return this.curve.point(nx, nz); }; Point.prototype.mul = function mul(k) { var t = k.clone(); var a = this; // (N / 2) * Q + Q var b = this.curve.point(null, null); // (N / 2) * Q var c = this; // Q for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) bits.push(t.andln(1)); for (var i = bits.length - 1; i >= 0; i--) { if (bits[i] === 0) { // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q a = a.diffAdd(b, c); // N * Q = 2 * ((N / 2) * Q + Q)) b = b.dbl(); } else { // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) b = a.diffAdd(b, c); // N * Q + Q = 2 * ((N / 2) * Q + Q) a = a.dbl(); } } return b; }; Point.prototype.mulAdd = function mulAdd() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.jumlAdd = function jumlAdd() { throw new Error('Not supported on Montgomery curve'); }; Point.prototype.eq = function eq(other) { return this.getX().cmp(other.getX()) === 0; }; Point.prototype.normalize = function normalize() { this.x = this.x.redMul(this.z.redInvm()); this.z = this.curve.one; return this; }; Point.prototype.getX = function getX() { // Normalize coordinates this.normalize(); return this.x.fromRed(); }; },{"../../elliptic":300,"../curve":303,"bn.js":91,"inherits":334}],305:[function(require,module,exports){ 'use strict'; var curve = require('../curve'); var elliptic = require('../../elliptic'); var BN = require('bn.js'); var inherits = require('inherits'); var Base = curve.base; var assert = elliptic.utils.assert; function ShortCurve(conf) { Base.call(this, 'short', conf); this.a = new BN(conf.a, 16).toRed(this.red); this.b = new BN(conf.b, 16).toRed(this.red); this.tinv = this.two.redInvm(); this.zeroA = this.a.fromRed().cmpn(0) === 0; this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; // If the curve is endomorphic, precalculate beta and lambda this.endo = this._getEndomorphism(conf); this._endoWnafT1 = new Array(4); this._endoWnafT2 = new Array(4); } inherits(ShortCurve, Base); module.exports = ShortCurve; ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { // No efficient endomorphism if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return; // Compute beta and lambda, that lambda * P = (beta * Px; Py) var beta; var lambda; if (conf.beta) { beta = new BN(conf.beta, 16).toRed(this.red); } else { var betas = this._getEndoRoots(this.p); // Choose the smallest beta beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; beta = beta.toRed(this.red); } if (conf.lambda) { lambda = new BN(conf.lambda, 16); } else { // Choose the lambda that is matching selected beta var lambdas = this._getEndoRoots(this.n); if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { lambda = lambdas[0]; } else { lambda = lambdas[1]; assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } } // Get basis vectors, used for balanced length-two representation var basis; if (conf.basis) { basis = conf.basis.map(function(vec) { return { a: new BN(vec.a, 16), b: new BN(vec.b, 16) }; }); } else { basis = this._getEndoBasis(lambda); } return { beta: beta, lambda: lambda, basis: basis }; }; ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { // Find roots of for x^2 + x + 1 in F // Root = (-1 +- Sqrt(-3)) / 2 // var red = num === this.p ? this.red : BN.mont(num); var tinv = new BN(2).toRed(red).redInvm(); var ntinv = tinv.redNeg(); var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); var l1 = ntinv.redAdd(s).fromRed(); var l2 = ntinv.redSub(s).fromRed(); return [ l1, l2 ]; }; ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { // aprxSqrt >= sqrt(this.n) var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); // 3.74 // Run EGCD, until r(L + 1) < aprxSqrt var u = lambda; var v = this.n.clone(); var x1 = new BN(1); var y1 = new BN(0); var x2 = new BN(0); var y2 = new BN(1); // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) var a0; var b0; // First vector var a1; var b1; // Second vector var a2; var b2; var prevR; var i = 0; var r; var x; while (u.cmpn(0) !== 0) { var q = v.div(u); r = v.sub(q.mul(u)); x = x2.sub(q.mul(x1)); var y = y2.sub(q.mul(y1)); if (!a1 && r.cmp(aprxSqrt) < 0) { a0 = prevR.neg(); b0 = x1; a1 = r.neg(); b1 = x; } else if (a1 && ++i === 2) { break; } prevR = r; v = u; u = r; x2 = x1; x1 = x; y2 = y1; y1 = y; } a2 = r.neg(); b2 = x; var len1 = a1.sqr().add(b1.sqr()); var len2 = a2.sqr().add(b2.sqr()); if (len2.cmp(len1) >= 0) { a2 = a0; b2 = b0; } // Normalize signs if (a1.negative) { a1 = a1.neg(); b1 = b1.neg(); } if (a2.negative) { a2 = a2.neg(); b2 = b2.neg(); } return [ { a: a1, b: b1 }, { a: a2, b: b2 } ]; }; ShortCurve.prototype._endoSplit = function _endoSplit(k) { var basis = this.endo.basis; var v1 = basis[0]; var v2 = basis[1]; var c1 = v2.b.mul(k).divRound(this.n); var c2 = v1.b.neg().mul(k).divRound(this.n); var p1 = c1.mul(v1.a); var p2 = c2.mul(v2.a); var q1 = c1.mul(v1.b); var q2 = c2.mul(v2.b); // Calculate answer var k1 = k.sub(p1).sub(p2); var k2 = q1.add(q2).neg(); return { k1: k1, k2: k2 }; }; ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { x = new BN(x, 16); if (!x.red) x = x.toRed(this.red); var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); var y = y2.redSqrt(); if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error('invalid point'); // XXX Is there any way to tell if the number is odd without converting it // to non-red form? var isOdd = y.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); return this.point(x, y); }; ShortCurve.prototype.validate = function validate(point) { if (point.inf) return true; var x = point.x; var y = point.y; var ax = this.a.redMul(x); var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); return y.redSqr().redISub(rhs).cmpn(0) === 0; }; ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) { var npoints = this._endoWnafT1; var ncoeffs = this._endoWnafT2; for (var i = 0; i < points.length; i++) { var split = this._endoSplit(coeffs[i]); var p = points[i]; var beta = p._getBeta(); if (split.k1.negative) { split.k1.ineg(); p = p.neg(true); } if (split.k2.negative) { split.k2.ineg(); beta = beta.neg(true); } npoints[i * 2] = p; npoints[i * 2 + 1] = beta; ncoeffs[i * 2] = split.k1; ncoeffs[i * 2 + 1] = split.k2; } var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); // Clean-up references to points and coefficients for (var j = 0; j < i * 2; j++) { npoints[j] = null; ncoeffs[j] = null; } return res; }; function Point(curve, x, y, isRed) { Base.BasePoint.call(this, curve, 'affine'); if (x === null && y === null) { this.x = null; this.y = null; this.inf = true; } else { this.x = new BN(x, 16); this.y = new BN(y, 16); // Force redgomery representation when loading from JSON if (isRed) { this.x.forceRed(this.curve.red); this.y.forceRed(this.curve.red); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); this.inf = false; } } inherits(Point, Base.BasePoint); ShortCurve.prototype.point = function point(x, y, isRed) { return new Point(this, x, y, isRed); }; ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { return Point.fromJSON(this, obj, red); }; Point.prototype._getBeta = function _getBeta() { if (!this.curve.endo) return; var pre = this.precomputed; if (pre && pre.beta) return pre.beta; var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); if (pre) { var curve = this.curve; var endoMul = function(p) { return curve.point(p.x.redMul(curve.endo.beta), p.y); }; pre.beta = beta; beta.precomputed = { beta: null, naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(endoMul) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(endoMul) } }; } return beta; }; Point.prototype.toJSON = function toJSON() { if (!this.precomputed) return [ this.x, this.y ]; return [ this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } } ]; }; Point.fromJSON = function fromJSON(curve, obj, red) { if (typeof obj === 'string') obj = JSON.parse(obj); var res = curve.point(obj[0], obj[1], red); if (!obj[2]) return res; function obj2point(obj) { return curve.point(obj[0], obj[1], red); } var pre = obj[2]; res.precomputed = { beta: null, doubles: pre.doubles && { step: pre.doubles.step, points: [ res ].concat(pre.doubles.points.map(obj2point)) }, naf: pre.naf && { wnd: pre.naf.wnd, points: [ res ].concat(pre.naf.points.map(obj2point)) } }; return res; }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; Point.prototype.isInfinity = function isInfinity() { return this.inf; }; Point.prototype.add = function add(p) { // O + P = P if (this.inf) return p; // P + O = P if (p.inf) return this; // P + P = 2P if (this.eq(p)) return this.dbl(); // P + (-P) = O if (this.neg().eq(p)) return this.curve.point(null, null); // P + Q = O if (this.x.cmp(p.x) === 0) return this.curve.point(null, null); var c = this.y.redSub(p.y); if (c.cmpn(0) !== 0) c = c.redMul(this.x.redSub(p.x).redInvm()); var nx = c.redSqr().redISub(this.x).redISub(p.x); var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.dbl = function dbl() { if (this.inf) return this; // 2P = O var ys1 = this.y.redAdd(this.y); if (ys1.cmpn(0) === 0) return this.curve.point(null, null); var a = this.curve.a; var x2 = this.x.redSqr(); var dyinv = ys1.redInvm(); var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); var nx = c.redSqr().redISub(this.x.redAdd(this.x)); var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.getX = function getX() { return this.x.fromRed(); }; Point.prototype.getY = function getY() { return this.y.fromRed(); }; Point.prototype.mul = function mul(k) { k = new BN(k, 16); if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k); else if (this.curve.endo) return this.curve._endoWnafMulAdd([ this ], [ k ]); else return this.curve._wnafMul(this, k); }; Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { var points = [ this, p2 ]; var coeffs = [ k1, k2 ]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs); else return this.curve._wnafMulAdd(1, points, coeffs, 2); }; Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { var points = [ this, p2 ]; var coeffs = [ k1, k2 ]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true); else return this.curve._wnafMulAdd(1, points, coeffs, 2, true); }; Point.prototype.eq = function eq(p) { return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); }; Point.prototype.neg = function neg(_precompute) { if (this.inf) return this; var res = this.curve.point(this.x, this.y.redNeg()); if (_precompute && this.precomputed) { var pre = this.precomputed; var negate = function(p) { return p.neg(); }; res.precomputed = { naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(negate) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(negate) } }; } return res; }; Point.prototype.toJ = function toJ() { if (this.inf) return this.curve.jpoint(null, null, null); var res = this.curve.jpoint(this.x, this.y, this.curve.one); return res; }; function JPoint(curve, x, y, z) { Base.BasePoint.call(this, curve, 'jacobian'); if (x === null && y === null && z === null) { this.x = this.curve.one; this.y = this.curve.one; this.z = new BN(0); } else { this.x = new BN(x, 16); this.y = new BN(y, 16); this.z = new BN(z, 16); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); this.zOne = this.z === this.curve.one; } inherits(JPoint, Base.BasePoint); ShortCurve.prototype.jpoint = function jpoint(x, y, z) { return new JPoint(this, x, y, z); }; JPoint.prototype.toP = function toP() { if (this.isInfinity()) return this.curve.point(null, null); var zinv = this.z.redInvm(); var zinv2 = zinv.redSqr(); var ax = this.x.redMul(zinv2); var ay = this.y.redMul(zinv2).redMul(zinv); return this.curve.point(ax, ay); }; JPoint.prototype.neg = function neg() { return this.curve.jpoint(this.x, this.y.redNeg(), this.z); }; JPoint.prototype.add = function add(p) { // O + P = P if (this.isInfinity()) return p; // P + O = P if (p.isInfinity()) return this; // 12M + 4S + 7A var pz2 = p.z.redSqr(); var z2 = this.z.redSqr(); var u1 = this.x.redMul(pz2); var u2 = p.x.redMul(z2); var s1 = this.y.redMul(pz2.redMul(p.z)); var s2 = p.y.redMul(z2.redMul(this.z)); var h = u1.redSub(u2); var r = s1.redSub(s2); if (h.cmpn(0) === 0) { if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h2 = h.redSqr(); var h3 = h2.redMul(h); var v = u1.redMul(h2); var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); var nz = this.z.redMul(p.z).redMul(h); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mixedAdd = function mixedAdd(p) { // O + P = P if (this.isInfinity()) return p.toJ(); // P + O = P if (p.isInfinity()) return this; // 8M + 3S + 7A var z2 = this.z.redSqr(); var u1 = this.x; var u2 = p.x.redMul(z2); var s1 = this.y; var s2 = p.y.redMul(z2).redMul(this.z); var h = u1.redSub(u2); var r = s1.redSub(s2); if (h.cmpn(0) === 0) { if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h2 = h.redSqr(); var h3 = h2.redMul(h); var v = u1.redMul(h2); var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); var nz = this.z.redMul(h); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.dblp = function dblp(pow) { if (pow === 0) return this; if (this.isInfinity()) return this; if (!pow) return this.dbl(); if (this.curve.zeroA || this.curve.threeA) { var r = this; for (var i = 0; i < pow; i++) r = r.dbl(); return r; } // 1M + 2S + 1A + N * (4S + 5M + 8A) // N = 1 => 6M + 6S + 9A var a = this.curve.a; var tinv = this.curve.tinv; var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); // Reuse results var jyd = jy.redAdd(jy); for (var i = 0; i < pow; i++) { var jx2 = jx.redSqr(); var jyd2 = jyd.redSqr(); var jyd4 = jyd2.redSqr(); var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); var t1 = jx.redMul(jyd2); var nx = c.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var dny = c.redMul(t2); dny = dny.redIAdd(dny).redISub(jyd4); var nz = jyd.redMul(jz); if (i + 1 < pow) jz4 = jz4.redMul(jyd4); jx = nx; jz = nz; jyd = dny; } return this.curve.jpoint(jx, jyd.redMul(tinv), jz); }; JPoint.prototype.dbl = function dbl() { if (this.isInfinity()) return this; if (this.curve.zeroA) return this._zeroDbl(); else if (this.curve.threeA) return this._threeDbl(); else return this._dbl(); }; JPoint.prototype._zeroDbl = function _zeroDbl() { var nx; var ny; var nz; // Z = 1 if (this.zOne) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-mdbl-2007-bl // 1M + 5S + 14A // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s = s.redIAdd(s); // M = 3 * XX + a; a = 0 var m = xx.redAdd(xx).redIAdd(xx); // T = M ^ 2 - 2*S var t = m.redSqr().redISub(s).redISub(s); // 8 * YYYY var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); // X3 = T nx = t; // Y3 = M * (S - T) - 8 * YYYY ny = m.redMul(s.redISub(t)).redISub(yyyy8); // Z3 = 2*Y1 nz = this.y.redAdd(this.y); } else { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-dbl-2009-l // 2M + 5S + 13A // A = X1^2 var a = this.x.redSqr(); // B = Y1^2 var b = this.y.redSqr(); // C = B^2 var c = b.redSqr(); // D = 2 * ((X1 + B)^2 - A - C) var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); d = d.redIAdd(d); // E = 3 * A var e = a.redAdd(a).redIAdd(a); // F = E^2 var f = e.redSqr(); // 8 * C var c8 = c.redIAdd(c); c8 = c8.redIAdd(c8); c8 = c8.redIAdd(c8); // X3 = F - 2 * D nx = f.redISub(d).redISub(d); // Y3 = E * (D - X3) - 8 * C ny = e.redMul(d.redISub(nx)).redISub(c8); // Z3 = 2 * Y1 * Z1 nz = this.y.redMul(this.z); nz = nz.redIAdd(nz); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._threeDbl = function _threeDbl() { var nx; var ny; var nz; // Z = 1 if (this.zOne) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html // #doubling-mdbl-2007-bl // 1M + 5S + 15A // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s = s.redIAdd(s); // M = 3 * XX + a var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); // T = M^2 - 2 * S var t = m.redSqr().redISub(s).redISub(s); // X3 = T nx = t; // Y3 = M * (S - T) - 8 * YYYY var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); ny = m.redMul(s.redISub(t)).redISub(yyyy8); // Z3 = 2 * Y1 nz = this.y.redAdd(this.y); } else { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b // 3M + 5S // delta = Z1^2 var delta = this.z.redSqr(); // gamma = Y1^2 var gamma = this.y.redSqr(); // beta = X1 * gamma var beta = this.x.redMul(gamma); // alpha = 3 * (X1 - delta) * (X1 + delta) var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); alpha = alpha.redAdd(alpha).redIAdd(alpha); // X3 = alpha^2 - 8 * beta var beta4 = beta.redIAdd(beta); beta4 = beta4.redIAdd(beta4); var beta8 = beta4.redAdd(beta4); nx = alpha.redSqr().redISub(beta8); // Z3 = (Y1 + Z1)^2 - gamma - delta nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 var ggamma8 = gamma.redSqr(); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._dbl = function _dbl() { var a = this.curve.a; // 4M + 6S + 10A var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); var jx2 = jx.redSqr(); var jy2 = jy.redSqr(); var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); var jxd4 = jx.redAdd(jx); jxd4 = jxd4.redIAdd(jxd4); var t1 = jxd4.redMul(jy2); var nx = c.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var jyd8 = jy2.redSqr(); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); var ny = c.redMul(t2).redISub(jyd8); var nz = jy.redAdd(jy).redMul(jz); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.trpl = function trpl() { if (!this.curve.zeroA) return this.dbl().add(this); // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl // 5M + 10S + ... // XX = X1^2 var xx = this.x.redSqr(); // YY = Y1^2 var yy = this.y.redSqr(); // ZZ = Z1^2 var zz = this.z.redSqr(); // YYYY = YY^2 var yyyy = yy.redSqr(); // M = 3 * XX + a * ZZ2; a = 0 var m = xx.redAdd(xx).redIAdd(xx); // MM = M^2 var mm = m.redSqr(); // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); e = e.redIAdd(e); e = e.redAdd(e).redIAdd(e); e = e.redISub(mm); // EE = E^2 var ee = e.redSqr(); // T = 16*YYYY var t = yyyy.redIAdd(yyyy); t = t.redIAdd(t); t = t.redIAdd(t); t = t.redIAdd(t); // U = (M + E)^2 - MM - EE - T var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); // X3 = 4 * (X1 * EE - 4 * YY * U) var yyu4 = yy.redMul(u); yyu4 = yyu4.redIAdd(yyu4); yyu4 = yyu4.redIAdd(yyu4); var nx = this.x.redMul(ee).redISub(yyu4); nx = nx.redIAdd(nx); nx = nx.redIAdd(nx); // Y3 = 8 * Y1 * (U * (T - U) - E * EE) var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); // Z3 = (Z1 + E)^2 - ZZ - EE var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mul = function mul(k, kbase) { k = new BN(k, kbase); return this.curve._wnafMul(this, k); }; JPoint.prototype.eq = function eq(p) { if (p.type === 'affine') return this.eq(p.toJ()); if (this === p) return true; // x1 * z2^2 == x2 * z1^2 var z2 = this.z.redSqr(); var pz2 = p.z.redSqr(); if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return false; // y1 * z2^3 == y2 * z1^3 var z3 = z2.redMul(this.z); var pz3 = pz2.redMul(p.z); return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; }; JPoint.prototype.eqXToP = function eqXToP(x) { var zs = this.z.redSqr(); var rx = x.toRed(this.curve.red).redMul(zs); if (this.x.cmp(rx) === 0) return true; var xc = x.clone(); var t = this.curve.redN.redMul(zs); for (;;) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } return false; }; JPoint.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; return ''; }; JPoint.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.z.cmpn(0) === 0; }; },{"../../elliptic":300,"../curve":303,"bn.js":91,"inherits":334}],306:[function(require,module,exports){ 'use strict'; var curves = exports; var hash = require('hash.js'); var elliptic = require('../elliptic'); var assert = elliptic.utils.assert; function PresetCurve(options) { if (options.type === 'short') this.curve = new elliptic.curve.short(options); else if (options.type === 'edwards') this.curve = new elliptic.curve.edwards(options); else this.curve = new elliptic.curve.mont(options); this.g = this.curve.g; this.n = this.curve.n; this.hash = options.hash; assert(this.g.validate(), 'Invalid curve'); assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); } curves.PresetCurve = PresetCurve; function defineCurve(name, options) { Object.defineProperty(curves, name, { configurable: true, enumerable: true, get: function() { var curve = new PresetCurve(options); Object.defineProperty(curves, name, { configurable: true, enumerable: true, value: curve }); return curve; } }); } defineCurve('p192', { type: 'short', prime: 'p192', p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', hash: hash.sha256, gRed: false, g: [ '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' ] }); defineCurve('p224', { type: 'short', prime: 'p224', p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', hash: hash.sha256, gRed: false, g: [ 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' ] }); defineCurve('p256', { type: 'short', prime: null, p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', hash: hash.sha256, gRed: false, g: [ '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' ] }); defineCurve('p384', { type: 'short', prime: null, p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 ffffffff', a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'fffffffe ffffffff 00000000 00000000 fffffffc', b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', hash: hash.sha384, gRed: false, g: [ 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + '5502f25d bf55296c 3a545e38 72760ab7', '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' ] }); defineCurve('p521', { type: 'short', prime: null, p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff', a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff ffffffff ffffffff fffffffc', b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', hash: hash.sha512, gRed: false, g: [ '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + '3fad0761 353c7086 a272c240 88be9476 9fd16650' ] }); defineCurve('curve25519', { type: 'mont', prime: 'p25519', p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', a: '76d06', b: '1', n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', hash: hash.sha256, gRed: false, g: [ '9' ] }); defineCurve('ed25519', { type: 'edwards', prime: 'p25519', p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', a: '-1', c: '1', // -121665 * (121666^(-1)) (mod P) d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', hash: hash.sha256, gRed: false, g: [ '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', // 4/5 '6666666666666666666666666666666666666666666666666666666666666658' ] }); var pre; try { pre = require('./precomputed/secp256k1'); } catch (e) { pre = undefined; } defineCurve('secp256k1', { type: 'short', prime: 'k256', p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', a: '0', b: '7', n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', h: '1', hash: hash.sha256, // Precomputed endomorphism beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', basis: [ { a: '3086d221a7d46bcde86c90e49284eb15', b: '-e4437ed6010e88286f547fa90abfe4c3' }, { a: '114ca50f7a8e2f3f657c1108d9d44cfd8', b: '3086d221a7d46bcde86c90e49284eb15' } ], gRed: false, g: [ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', pre ] }); },{"../elliptic":300,"./precomputed/secp256k1":313,"hash.js":319}],307:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); var HmacDRBG = require('hmac-drbg'); var elliptic = require('../../elliptic'); var utils = elliptic.utils; var assert = utils.assert; var KeyPair = require('./key'); var Signature = require('./signature'); function EC(options) { if (!(this instanceof EC)) return new EC(options); // Shortcut `elliptic.ec(curve-name)` if (typeof options === 'string') { assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); options = elliptic.curves[options]; } // Shortcut for `elliptic.ec(elliptic.curves.curveName)` if (options instanceof elliptic.curves.PresetCurve) options = { curve: options }; this.curve = options.curve.curve; this.n = this.curve.n; this.nh = this.n.ushrn(1); this.g = this.curve.g; // Point on curve this.g = options.curve.g; this.g.precompute(options.curve.n.bitLength() + 1); // Hash for function for DRBG this.hash = options.hash || options.curve.hash; } module.exports = EC; EC.prototype.keyPair = function keyPair(options) { return new KeyPair(this, options); }; EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { return KeyPair.fromPrivate(this, priv, enc); }; EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { return KeyPair.fromPublic(this, pub, enc); }; EC.prototype.genKeyPair = function genKeyPair(options) { if (!options) options = {}; // Instantiate Hmac_DRBG var drbg = new HmacDRBG({ hash: this.hash, pers: options.pers, persEnc: options.persEnc || 'utf8', entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), entropyEnc: options.entropy && options.entropyEnc || 'utf8', nonce: this.n.toArray() }); var bytes = this.n.byteLength(); var ns2 = this.n.sub(new BN(2)); do { var priv = new BN(drbg.generate(bytes)); if (priv.cmp(ns2) > 0) continue; priv.iaddn(1); return this.keyFromPrivate(priv); } while (true); }; EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { var delta = msg.byteLength() * 8 - this.n.bitLength(); if (delta > 0) msg = msg.ushrn(delta); if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n); else return msg; }; EC.prototype.sign = function sign(msg, key, enc, options) { if (typeof enc === 'object') { options = enc; enc = null; } if (!options) options = {}; key = this.keyFromPrivate(key, enc); msg = this._truncateToN(new BN(msg, 16)); // Zero-extend key to provide enough entropy var bytes = this.n.byteLength(); var bkey = key.getPrivate().toArray('be', bytes); // Zero-extend nonce to have the same byte size as N var nonce = msg.toArray('be', bytes); // Instantiate Hmac_DRBG var drbg = new HmacDRBG({ hash: this.hash, entropy: bkey, nonce: nonce, pers: options.pers, persEnc: options.persEnc || 'utf8' }); // Number of bytes to generate var ns1 = this.n.sub(new BN(1)); for (var iter = 0; true; iter++) { var k = options.k ? options.k(iter) : new BN(drbg.generate(this.n.byteLength())); k = this._truncateToN(k, true); if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) continue; var kp = this.g.mul(k); if (kp.isInfinity()) continue; var kpX = kp.getX(); var r = kpX.umod(this.n); if (r.cmpn(0) === 0) continue; var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); s = s.umod(this.n); if (s.cmpn(0) === 0) continue; var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); // Use complement of `s`, if it is > `n / 2` if (options.canonical && s.cmp(this.nh) > 0) { s = this.n.sub(s); recoveryParam ^= 1; } return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); } }; EC.prototype.verify = function verify(msg, signature, key, enc) { msg = this._truncateToN(new BN(msg, 16)); key = this.keyFromPublic(key, enc); signature = new Signature(signature, 'hex'); // Perform primitive values validation var r = signature.r; var s = signature.s; if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) return false; if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return false; // Validate signature var sinv = s.invm(this.n); var u1 = sinv.mul(msg).umod(this.n); var u2 = sinv.mul(r).umod(this.n); if (!this.curve._maxwellTrick) { var p = this.g.mulAdd(u1, key.getPublic(), u2); if (p.isInfinity()) return false; return p.getX().umod(this.n).cmp(r) === 0; } // NOTE: Greg Maxwell's trick, inspired by: // https://git.io/vad3K var p = this.g.jmulAdd(u1, key.getPublic(), u2); if (p.isInfinity()) return false; // Compare `p.x` of Jacobian point with `r`, // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the // inverse of `p.z^2` return p.eqXToP(r); }; EC.prototype.recoverPubKey = function(msg, signature, j, enc) { assert((3 & j) === j, 'The recovery param is more than two bits'); signature = new Signature(signature, enc); var n = this.n; var e = new BN(msg); var r = signature.r; var s = signature.s; // A set LSB signifies that the y-coordinate is odd var isYOdd = j & 1; var isSecondKey = j >> 1; if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error('Unable to find sencond key candinate'); // 1.1. Let x = r + jn. if (isSecondKey) r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); else r = this.curve.pointFromX(r, isYOdd); var rInv = signature.r.invm(n); var s1 = n.sub(e).mul(rInv).umod(n); var s2 = s.mul(rInv).umod(n); // 1.6.1 Compute Q = r^-1 (sR - eG) // Q = r^-1 (sR + -eG) return this.g.mulAdd(s1, r, s2); }; EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { signature = new Signature(signature, enc); if (signature.recoveryParam !== null) return signature.recoveryParam; for (var i = 0; i < 4; i++) { var Qprime; try { Qprime = this.recoverPubKey(e, signature, i); } catch (e) { continue; } if (Qprime.eq(Q)) return i; } throw new Error('Unable to find valid recovery factor'); }; },{"../../elliptic":300,"./key":308,"./signature":309,"bn.js":91,"hmac-drbg":331}],308:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); var elliptic = require('../../elliptic'); var utils = elliptic.utils; var assert = utils.assert; function KeyPair(ec, options) { this.ec = ec; this.priv = null; this.pub = null; // KeyPair(ec, { priv: ..., pub: ... }) if (options.priv) this._importPrivate(options.priv, options.privEnc); if (options.pub) this._importPublic(options.pub, options.pubEnc); } module.exports = KeyPair; KeyPair.fromPublic = function fromPublic(ec, pub, enc) { if (pub instanceof KeyPair) return pub; return new KeyPair(ec, { pub: pub, pubEnc: enc }); }; KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { if (priv instanceof KeyPair) return priv; return new KeyPair(ec, { priv: priv, privEnc: enc }); }; KeyPair.prototype.validate = function validate() { var pub = this.getPublic(); if (pub.isInfinity()) return { result: false, reason: 'Invalid public key' }; if (!pub.validate()) return { result: false, reason: 'Public key is not a point' }; if (!pub.mul(this.ec.curve.n).isInfinity()) return { result: false, reason: 'Public key * N != O' }; return { result: true, reason: null }; }; KeyPair.prototype.getPublic = function getPublic(compact, enc) { // compact is optional argument if (typeof compact === 'string') { enc = compact; compact = null; } if (!this.pub) this.pub = this.ec.g.mul(this.priv); if (!enc) return this.pub; return this.pub.encode(enc, compact); }; KeyPair.prototype.getPrivate = function getPrivate(enc) { if (enc === 'hex') return this.priv.toString(16, 2); else return this.priv; }; KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { this.priv = new BN(key, enc || 16); // Ensure that the priv won't be bigger than n, otherwise we may fail // in fixed multiplication method this.priv = this.priv.umod(this.ec.curve.n); }; KeyPair.prototype._importPublic = function _importPublic(key, enc) { if (key.x || key.y) { // Montgomery points only have an `x` coordinate. // Weierstrass/Edwards points on the other hand have both `x` and // `y` coordinates. if (this.ec.curve.type === 'mont') { assert(key.x, 'Need x coordinate'); } else if (this.ec.curve.type === 'short' || this.ec.curve.type === 'edwards') { assert(key.x && key.y, 'Need both x and y coordinate'); } this.pub = this.ec.curve.point(key.x, key.y); return; } this.pub = this.ec.curve.decodePoint(key, enc); }; // ECDH KeyPair.prototype.derive = function derive(pub) { return pub.mul(this.priv).getX(); }; // ECDSA KeyPair.prototype.sign = function sign(msg, enc, options) { return this.ec.sign(msg, this, enc, options); }; KeyPair.prototype.verify = function verify(msg, signature) { return this.ec.verify(msg, signature, this); }; KeyPair.prototype.inspect = function inspect() { return ''; }; },{"../../elliptic":300,"bn.js":91}],309:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); var elliptic = require('../../elliptic'); var utils = elliptic.utils; var assert = utils.assert; function Signature(options, enc) { if (options instanceof Signature) return options; if (this._importDER(options, enc)) return; assert(options.r && options.s, 'Signature without r or s'); this.r = new BN(options.r, 16); this.s = new BN(options.s, 16); if (options.recoveryParam === undefined) this.recoveryParam = null; else this.recoveryParam = options.recoveryParam; } module.exports = Signature; function Position() { this.place = 0; } function getLength(buf, p) { var initial = buf[p.place++]; if (!(initial & 0x80)) { return initial; } var octetLen = initial & 0xf; var val = 0; for (var i = 0, off = p.place; i < octetLen; i++, off++) { val <<= 8; val |= buf[off]; } p.place = off; return val; } function rmPadding(buf) { var i = 0; var len = buf.length - 1; while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { i++; } if (i === 0) { return buf; } return buf.slice(i); } Signature.prototype._importDER = function _importDER(data, enc) { data = utils.toArray(data, enc); var p = new Position(); if (data[p.place++] !== 0x30) { return false; } var len = getLength(data, p); if ((len + p.place) !== data.length) { return false; } if (data[p.place++] !== 0x02) { return false; } var rlen = getLength(data, p); var r = data.slice(p.place, rlen + p.place); p.place += rlen; if (data[p.place++] !== 0x02) { return false; } var slen = getLength(data, p); if (data.length !== slen + p.place) { return false; } var s = data.slice(p.place, slen + p.place); if (r[0] === 0 && (r[1] & 0x80)) { r = r.slice(1); } if (s[0] === 0 && (s[1] & 0x80)) { s = s.slice(1); } this.r = new BN(r); this.s = new BN(s); this.recoveryParam = null; return true; }; function constructLength(arr, len) { if (len < 0x80) { arr.push(len); return; } var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); arr.push(octets | 0x80); while (--octets) { arr.push((len >>> (octets << 3)) & 0xff); } arr.push(len); } Signature.prototype.toDER = function toDER(enc) { var r = this.r.toArray(); var s = this.s.toArray(); // Pad values if (r[0] & 0x80) r = [ 0 ].concat(r); // Pad values if (s[0] & 0x80) s = [ 0 ].concat(s); r = rmPadding(r); s = rmPadding(s); while (!s[0] && !(s[1] & 0x80)) { s = s.slice(1); } var arr = [ 0x02 ]; constructLength(arr, r.length); arr = arr.concat(r); arr.push(0x02); constructLength(arr, s.length); var backHalf = arr.concat(s); var res = [ 0x30 ]; constructLength(res, backHalf.length); res = res.concat(backHalf); return utils.encode(res, enc); }; },{"../../elliptic":300,"bn.js":91}],310:[function(require,module,exports){ 'use strict'; var hash = require('hash.js'); var elliptic = require('../../elliptic'); var utils = elliptic.utils; var assert = utils.assert; var parseBytes = utils.parseBytes; var KeyPair = require('./key'); var Signature = require('./signature'); function EDDSA(curve) { assert(curve === 'ed25519', 'only tested with ed25519 so far'); if (!(this instanceof EDDSA)) return new EDDSA(curve); var curve = elliptic.curves[curve].curve; this.curve = curve; this.g = curve.g; this.g.precompute(curve.n.bitLength() + 1); this.pointClass = curve.point().constructor; this.encodingLength = Math.ceil(curve.n.bitLength() / 8); this.hash = hash.sha512; } module.exports = EDDSA; /** * @param {Array|String} message - message bytes * @param {Array|String|KeyPair} secret - secret bytes or a keypair * @returns {Signature} - signature */ EDDSA.prototype.sign = function sign(message, secret) { message = parseBytes(message); var key = this.keyFromSecret(secret); var r = this.hashInt(key.messagePrefix(), message); var R = this.g.mul(r); var Rencoded = this.encodePoint(R); var s_ = this.hashInt(Rencoded, key.pubBytes(), message) .mul(key.priv()); var S = r.add(s_).umod(this.curve.n); return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); }; /** * @param {Array} message - message bytes * @param {Array|String|Signature} sig - sig bytes * @param {Array|String|Point|KeyPair} pub - public key * @returns {Boolean} - true if public key matches sig of message */ EDDSA.prototype.verify = function verify(message, sig, pub) { message = parseBytes(message); sig = this.makeSignature(sig); var key = this.keyFromPublic(pub); var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); var SG = this.g.mul(sig.S()); var RplusAh = sig.R().add(key.pub().mul(h)); return RplusAh.eq(SG); }; EDDSA.prototype.hashInt = function hashInt() { var hash = this.hash(); for (var i = 0; i < arguments.length; i++) hash.update(arguments[i]); return utils.intFromLE(hash.digest()).umod(this.curve.n); }; EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { return KeyPair.fromPublic(this, pub); }; EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { return KeyPair.fromSecret(this, secret); }; EDDSA.prototype.makeSignature = function makeSignature(sig) { if (sig instanceof Signature) return sig; return new Signature(this, sig); }; /** * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 * * EDDSA defines methods for encoding and decoding points and integers. These are * helper convenience methods, that pass along to utility functions implied * parameters. * */ EDDSA.prototype.encodePoint = function encodePoint(point) { var enc = point.getY().toArray('le', this.encodingLength); enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; return enc; }; EDDSA.prototype.decodePoint = function decodePoint(bytes) { bytes = utils.parseBytes(bytes); var lastIx = bytes.length - 1; var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); var xIsOdd = (bytes[lastIx] & 0x80) !== 0; var y = utils.intFromLE(normed); return this.curve.pointFromY(y, xIsOdd); }; EDDSA.prototype.encodeInt = function encodeInt(num) { return num.toArray('le', this.encodingLength); }; EDDSA.prototype.decodeInt = function decodeInt(bytes) { return utils.intFromLE(bytes); }; EDDSA.prototype.isPoint = function isPoint(val) { return val instanceof this.pointClass; }; },{"../../elliptic":300,"./key":311,"./signature":312,"hash.js":319}],311:[function(require,module,exports){ 'use strict'; var elliptic = require('../../elliptic'); var utils = elliptic.utils; var assert = utils.assert; var parseBytes = utils.parseBytes; var cachedProperty = utils.cachedProperty; /** * @param {EDDSA} eddsa - instance * @param {Object} params - public/private key parameters * * @param {Array} [params.secret] - secret seed bytes * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) * @param {Array} [params.pub] - public key point encoded as bytes * */ function KeyPair(eddsa, params) { this.eddsa = eddsa; this._secret = parseBytes(params.secret); if (eddsa.isPoint(params.pub)) this._pub = params.pub; else this._pubBytes = parseBytes(params.pub); } KeyPair.fromPublic = function fromPublic(eddsa, pub) { if (pub instanceof KeyPair) return pub; return new KeyPair(eddsa, { pub: pub }); }; KeyPair.fromSecret = function fromSecret(eddsa, secret) { if (secret instanceof KeyPair) return secret; return new KeyPair(eddsa, { secret: secret }); }; KeyPair.prototype.secret = function secret() { return this._secret; }; cachedProperty(KeyPair, 'pubBytes', function pubBytes() { return this.eddsa.encodePoint(this.pub()); }); cachedProperty(KeyPair, 'pub', function pub() { if (this._pubBytes) return this.eddsa.decodePoint(this._pubBytes); return this.eddsa.g.mul(this.priv()); }); cachedProperty(KeyPair, 'privBytes', function privBytes() { var eddsa = this.eddsa; var hash = this.hash(); var lastIx = eddsa.encodingLength - 1; var a = hash.slice(0, eddsa.encodingLength); a[0] &= 248; a[lastIx] &= 127; a[lastIx] |= 64; return a; }); cachedProperty(KeyPair, 'priv', function priv() { return this.eddsa.decodeInt(this.privBytes()); }); cachedProperty(KeyPair, 'hash', function hash() { return this.eddsa.hash().update(this.secret()).digest(); }); cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { return this.hash().slice(this.eddsa.encodingLength); }); KeyPair.prototype.sign = function sign(message) { assert(this._secret, 'KeyPair can only verify'); return this.eddsa.sign(message, this); }; KeyPair.prototype.verify = function verify(message, sig) { return this.eddsa.verify(message, sig, this); }; KeyPair.prototype.getSecret = function getSecret(enc) { assert(this._secret, 'KeyPair is public only'); return utils.encode(this.secret(), enc); }; KeyPair.prototype.getPublic = function getPublic(enc) { return utils.encode(this.pubBytes(), enc); }; module.exports = KeyPair; },{"../../elliptic":300}],312:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); var elliptic = require('../../elliptic'); var utils = elliptic.utils; var assert = utils.assert; var cachedProperty = utils.cachedProperty; var parseBytes = utils.parseBytes; /** * @param {EDDSA} eddsa - eddsa instance * @param {Array|Object} sig - * @param {Array|Point} [sig.R] - R point as Point or bytes * @param {Array|bn} [sig.S] - S scalar as bn or bytes * @param {Array} [sig.Rencoded] - R point encoded * @param {Array} [sig.Sencoded] - S scalar encoded */ function Signature(eddsa, sig) { this.eddsa = eddsa; if (typeof sig !== 'object') sig = parseBytes(sig); if (Array.isArray(sig)) { sig = { R: sig.slice(0, eddsa.encodingLength), S: sig.slice(eddsa.encodingLength) }; } assert(sig.R && sig.S, 'Signature without R or S'); if (eddsa.isPoint(sig.R)) this._R = sig.R; if (sig.S instanceof BN) this._S = sig.S; this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; } cachedProperty(Signature, 'S', function S() { return this.eddsa.decodeInt(this.Sencoded()); }); cachedProperty(Signature, 'R', function R() { return this.eddsa.decodePoint(this.Rencoded()); }); cachedProperty(Signature, 'Rencoded', function Rencoded() { return this.eddsa.encodePoint(this.R()); }); cachedProperty(Signature, 'Sencoded', function Sencoded() { return this.eddsa.encodeInt(this.S()); }); Signature.prototype.toBytes = function toBytes() { return this.Rencoded().concat(this.Sencoded()); }; Signature.prototype.toHex = function toHex() { return utils.encode(this.toBytes(), 'hex').toUpperCase(); }; module.exports = Signature; },{"../../elliptic":300,"bn.js":91}],313:[function(require,module,exports){ module.exports = { doubles: { step: 4, points: [ [ 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' ], [ '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' ], [ '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' ], [ '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' ], [ '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' ], [ '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' ], [ 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' ], [ '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' ], [ 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' ], [ 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' ], [ 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' ], [ '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' ], [ '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' ], [ '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' ], [ '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' ], [ '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' ], [ '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' ], [ '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' ], [ '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' ], [ 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' ], [ 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' ], [ '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' ], [ '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' ], [ 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' ], [ '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' ], [ 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' ], [ 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' ], [ 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' ], [ 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' ], [ 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' ], [ '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' ], [ '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' ], [ 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' ], [ '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' ], [ 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' ], [ 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' ], [ 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' ], [ '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' ], [ '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' ], [ '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' ], [ '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' ], [ 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' ], [ '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' ], [ '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' ], [ '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' ], [ 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' ], [ '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' ], [ 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' ], [ 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' ], [ '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' ], [ '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' ], [ 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' ], [ 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' ], [ 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' ], [ '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' ], [ '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' ], [ 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' ], [ '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' ], [ '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' ], [ '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' ], [ 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' ], [ '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' ], [ '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' ], [ 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' ], [ 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' ] ] }, naf: { wnd: 7, points: [ [ 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' ], [ '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' ], [ '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' ], [ 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' ], [ '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' ], [ 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' ], [ 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' ], [ 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' ], [ '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' ], [ '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' ], [ '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' ], [ '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' ], [ 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' ], [ 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' ], [ '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' ], [ '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' ], [ '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' ], [ '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' ], [ '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' ], [ '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' ], [ 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' ], [ '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' ], [ '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' ], [ 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' ], [ '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' ], [ 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' ], [ 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' ], [ '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' ], [ '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' ], [ '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' ], [ 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' ], [ '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' ], [ 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' ], [ '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' ], [ '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' ], [ 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' ], [ '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' ], [ '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' ], [ 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' ], [ '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' ], [ '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' ], [ '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' ], [ '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' ], [ 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' ], [ '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' ], [ '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' ], [ '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' ], [ 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' ], [ 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' ], [ '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' ], [ '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' ], [ 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' ], [ 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' ], [ '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' ], [ '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' ], [ 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' ], [ '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' ], [ 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' ], [ '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' ], [ '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' ], [ 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' ], [ 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' ], [ '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' ], [ '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' ], [ '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' ], [ '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' ], [ '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' ], [ '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' ], [ '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' ], [ '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' ], [ 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' ], [ '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' ], [ 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' ], [ 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' ], [ 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' ], [ 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' ], [ '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' ], [ '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' ], [ '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' ], [ 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' ], [ 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' ], [ 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' ], [ 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' ], [ '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' ], [ 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' ], [ 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' ], [ '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' ], [ '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' ], [ 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' ], [ 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' ], [ 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' ], [ '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' ], [ 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' ], [ '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' ], [ 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' ], [ 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' ], [ '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' ], [ 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' ], [ 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' ], [ 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' ], [ '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' ], [ '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' ], [ 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' ], [ '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' ], [ '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' ], [ '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' ], [ 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' ], [ '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' ], [ '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' ], [ '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' ], [ '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' ], [ 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' ], [ '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' ], [ 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' ], [ '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' ], [ 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' ], [ 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' ], [ 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' ], [ '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' ], [ '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' ], [ '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' ], [ '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' ], [ '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' ], [ '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' ], [ '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' ], [ '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' ], [ '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' ] ] } }; },{}],314:[function(require,module,exports){ 'use strict'; var utils = exports; var BN = require('bn.js'); var minAssert = require('minimalistic-assert'); var minUtils = require('minimalistic-crypto-utils'); utils.assert = minAssert; utils.toArray = minUtils.toArray; utils.zero2 = minUtils.zero2; utils.toHex = minUtils.toHex; utils.encode = minUtils.encode; // Represent num in a w-NAF form function getNAF(num, w) { var naf = []; var ws = 1 << (w + 1); var k = num.clone(); while (k.cmpn(1) >= 0) { var z; if (k.isOdd()) { var mod = k.andln(ws - 1); if (mod > (ws >> 1) - 1) z = (ws >> 1) - mod; else z = mod; k.isubn(z); } else { z = 0; } naf.push(z); // Optimization, shift by word if possible var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; for (var i = 1; i < shift; i++) naf.push(0); k.iushrn(shift); } return naf; } utils.getNAF = getNAF; // Represent k1, k2 in a Joint Sparse Form function getJSF(k1, k2) { var jsf = [ [], [] ]; k1 = k1.clone(); k2 = k2.clone(); var d1 = 0; var d2 = 0; while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { // First phase var m14 = (k1.andln(3) + d1) & 3; var m24 = (k2.andln(3) + d2) & 3; if (m14 === 3) m14 = -1; if (m24 === 3) m24 = -1; var u1; if ((m14 & 1) === 0) { u1 = 0; } else { var m8 = (k1.andln(7) + d1) & 7; if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14; else u1 = m14; } jsf[0].push(u1); var u2; if ((m24 & 1) === 0) { u2 = 0; } else { var m8 = (k2.andln(7) + d2) & 7; if ((m8 === 3 || m8 === 5) && m14 === 2) u2 = -m24; else u2 = m24; } jsf[1].push(u2); // Second phase if (2 * d1 === u1 + 1) d1 = 1 - d1; if (2 * d2 === u2 + 1) d2 = 1 - d2; k1.iushrn(1); k2.iushrn(1); } return jsf; } utils.getJSF = getJSF; function cachedProperty(obj, name, computer) { var key = '_' + name; obj.prototype[name] = function cachedProperty() { return this[key] !== undefined ? this[key] : this[key] = computer.call(this); }; } utils.cachedProperty = cachedProperty; function parseBytes(bytes) { return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : bytes; } utils.parseBytes = parseBytes; function intFromLE(bytes) { return new BN(bytes, 'hex', 'le'); } utils.intFromLE = intFromLE; },{"bn.js":91,"minimalistic-assert":342,"minimalistic-crypto-utils":343}],315:[function(require,module,exports){ module.exports={ "name": "elliptic", "version": "6.4.0", "description": "EC cryptography", "main": "lib/elliptic.js", "files": [ "lib" ], "scripts": { "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", "lint": "npm run jscs && npm run jshint", "unit": "istanbul test _mocha --reporter=spec test/index.js", "test": "npm run lint && npm run unit", "version": "grunt dist && git add dist/" }, "repository": { "type": "git", "url": "git@github.com:indutny/elliptic" }, "keywords": [ "EC", "Elliptic", "curve", "Cryptography" ], "author": "Fedor Indutny ", "license": "MIT", "bugs": { "url": "https://github.com/indutny/elliptic/issues" }, "homepage": "https://github.com/indutny/elliptic", "devDependencies": { "brfs": "^1.4.3", "coveralls": "^2.11.3", "grunt": "^0.4.5", "grunt-browserify": "^5.0.0", "grunt-cli": "^1.2.0", "grunt-contrib-connect": "^1.0.0", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-uglify": "^1.0.1", "grunt-mocha-istanbul": "^3.0.1", "grunt-saucelabs": "^8.6.2", "istanbul": "^0.4.2", "jscs": "^2.9.0", "jshint": "^2.6.0", "mocha": "^2.1.0" }, "dependencies": { "bn.js": "^4.4.0", "brorand": "^1.0.1", "hash.js": "^1.0.0", "hmac-drbg": "^1.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0", "minimalistic-crypto-utils": "^1.0.0" } } },{}],316:[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; }; EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = []; else { evlistener = events[type]; if (!evlistener) ret = []; else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener]; else ret = unwrapListeners(evlistener); } return ret; }; 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); }; } },{}],317:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var MD5 = require('md5.js') /* eslint-disable camelcase */ function EVP_BytesToKey (password, salt, keyBits, ivLen) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') if (salt) { if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') } var keyLen = keyBits / 8 var key = Buffer.alloc(keyLen) var iv = Buffer.alloc(ivLen || 0) var tmp = Buffer.alloc(0) while (keyLen > 0 || ivLen > 0) { var hash = new MD5() hash.update(tmp) hash.update(password) if (salt) hash.update(salt) tmp = hash.digest() var used = 0 if (keyLen > 0) { var keyStart = key.length - keyLen used = Math.min(keyLen, tmp.length) tmp.copy(key, keyStart, 0, used) keyLen -= used } if (used < tmp.length && ivLen > 0) { var ivStart = iv.length - ivLen var length = Math.min(ivLen, tmp.length - used) tmp.copy(iv, ivStart, used, used + length) ivLen -= length } } tmp.fill(0) return { key: key, iv: iv } } module.exports = EVP_BytesToKey },{"md5.js":339,"safe-buffer":537}],318:[function(require,module,exports){ (function (Buffer){ 'use strict' var Transform = require('stream').Transform var inherits = require('inherits') function HashBase (blockSize) { Transform.call(this) this._block = new Buffer(blockSize) this._blockSize = blockSize this._blockOffset = 0 this._length = [0, 0, 0, 0] this._finalized = false } inherits(HashBase, Transform) HashBase.prototype._transform = function (chunk, encoding, callback) { var error = null try { if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding) this.update(chunk) } catch (err) { error = err } callback(error) } HashBase.prototype._flush = function (callback) { var error = null try { this.push(this._digest()) } catch (err) { error = err } callback(error) } HashBase.prototype.update = function (data, encoding) { if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') if (this._finalized) throw new Error('Digest already called') if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary') // consume data var block = this._block var offset = 0 while (this._blockOffset + data.length - offset >= this._blockSize) { for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] this._update() this._blockOffset = 0 } while (offset < data.length) block[this._blockOffset++] = data[offset++] // update length for (var j = 0, carry = data.length * 8; carry > 0; ++j) { this._length[j] += carry carry = (this._length[j] / 0x0100000000) | 0 if (carry > 0) this._length[j] -= 0x0100000000 * carry } return this } HashBase.prototype._update = function (data) { throw new Error('_update is not implemented') } HashBase.prototype.digest = function (encoding) { if (this._finalized) throw new Error('Digest already called') this._finalized = true var digest = this._digest() if (encoding !== undefined) digest = digest.toString(encoding) return digest } HashBase.prototype._digest = function () { throw new Error('_digest is not implemented') } module.exports = HashBase }).call(this,require("buffer").Buffer) },{"buffer":144,"inherits":334,"stream":548}],319:[function(require,module,exports){ var hash = exports; hash.utils = require('./hash/utils'); hash.common = require('./hash/common'); hash.sha = require('./hash/sha'); hash.ripemd = require('./hash/ripemd'); hash.hmac = require('./hash/hmac'); // Proxy hash functions to the main object hash.sha1 = hash.sha.sha1; hash.sha256 = hash.sha.sha256; hash.sha224 = hash.sha.sha224; hash.sha384 = hash.sha.sha384; hash.sha512 = hash.sha.sha512; hash.ripemd160 = hash.ripemd.ripemd160; },{"./hash/common":320,"./hash/hmac":321,"./hash/ripemd":322,"./hash/sha":323,"./hash/utils":330}],320:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var assert = require('minimalistic-assert'); function BlockHash() { this.pending = null; this.pendingTotal = 0; this.blockSize = this.constructor.blockSize; this.outSize = this.constructor.outSize; this.hmacStrength = this.constructor.hmacStrength; this.padLength = this.constructor.padLength / 8; this.endian = 'big'; this._delta8 = this.blockSize / 8; this._delta32 = this.blockSize / 32; } exports.BlockHash = BlockHash; BlockHash.prototype.update = function update(msg, enc) { // Convert message to array, pad it, and join into 32bit blocks msg = utils.toArray(msg, enc); if (!this.pending) this.pending = msg; else this.pending = this.pending.concat(msg); this.pendingTotal += msg.length; // Enough data, try updating if (this.pending.length >= this._delta8) { msg = this.pending; // Process pending data in blocks var r = msg.length % this._delta8; this.pending = msg.slice(msg.length - r, msg.length); if (this.pending.length === 0) this.pending = null; msg = utils.join32(msg, 0, msg.length - r, this.endian); for (var i = 0; i < msg.length; i += this._delta32) this._update(msg, i, i + this._delta32); } return this; }; BlockHash.prototype.digest = function digest(enc) { this.update(this._pad()); assert(this.pending === null); return this._digest(enc); }; BlockHash.prototype._pad = function pad() { var len = this.pendingTotal; var bytes = this._delta8; var k = bytes - ((len + this.padLength) % bytes); var res = new Array(k + this.padLength); res[0] = 0x80; for (var i = 1; i < k; i++) res[i] = 0; // Append length len <<= 3; if (this.endian === 'big') { for (var t = 8; t < this.padLength; t++) res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = (len >>> 24) & 0xff; res[i++] = (len >>> 16) & 0xff; res[i++] = (len >>> 8) & 0xff; res[i++] = len & 0xff; } else { res[i++] = len & 0xff; res[i++] = (len >>> 8) & 0xff; res[i++] = (len >>> 16) & 0xff; res[i++] = (len >>> 24) & 0xff; res[i++] = 0; res[i++] = 0; res[i++] = 0; res[i++] = 0; for (t = 8; t < this.padLength; t++) res[i++] = 0; } return res; }; },{"./utils":330,"minimalistic-assert":342}],321:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var assert = require('minimalistic-assert'); function Hmac(hash, key, enc) { if (!(this instanceof Hmac)) return new Hmac(hash, key, enc); this.Hash = hash; this.blockSize = hash.blockSize / 8; this.outSize = hash.outSize / 8; this.inner = null; this.outer = null; this._init(utils.toArray(key, enc)); } module.exports = Hmac; Hmac.prototype._init = function init(key) { // Shorten key, if needed if (key.length > this.blockSize) key = new this.Hash().update(key).digest(); assert(key.length <= this.blockSize); // Add padding to key for (var i = key.length; i < this.blockSize; i++) key.push(0); for (i = 0; i < key.length; i++) key[i] ^= 0x36; this.inner = new this.Hash().update(key); // 0x36 ^ 0x5c = 0x6a for (i = 0; i < key.length; i++) key[i] ^= 0x6a; this.outer = new this.Hash().update(key); }; Hmac.prototype.update = function update(msg, enc) { this.inner.update(msg, enc); return this; }; Hmac.prototype.digest = function digest(enc) { this.outer.update(this.inner.digest()); return this.outer.digest(enc); }; },{"./utils":330,"minimalistic-assert":342}],322:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var common = require('./common'); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_3 = utils.sum32_3; var sum32_4 = utils.sum32_4; var BlockHash = common.BlockHash; function RIPEMD160() { if (!(this instanceof RIPEMD160)) return new RIPEMD160(); BlockHash.call(this); this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; this.endian = 'little'; } utils.inherits(RIPEMD160, BlockHash); exports.ripemd160 = RIPEMD160; RIPEMD160.blockSize = 512; RIPEMD160.outSize = 160; RIPEMD160.hmacStrength = 192; RIPEMD160.padLength = 64; RIPEMD160.prototype._update = function update(msg, start) { var A = this.h[0]; var B = this.h[1]; var C = this.h[2]; var D = this.h[3]; var E = this.h[4]; var Ah = A; var Bh = B; var Ch = C; var Dh = D; var Eh = E; for (var j = 0; j < 80; j++) { var T = sum32( rotl32( sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), s[j]), E); A = E; E = D; D = rotl32(C, 10); C = B; B = T; T = sum32( rotl32( sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh); Ah = Eh; Eh = Dh; Dh = rotl32(Ch, 10); Ch = Bh; Bh = T; } T = sum32_3(this.h[1], C, Dh); this.h[1] = sum32_3(this.h[2], D, Eh); this.h[2] = sum32_3(this.h[3], E, Ah); this.h[3] = sum32_3(this.h[4], A, Bh); this.h[4] = sum32_3(this.h[0], B, Ch); this.h[0] = T; }; RIPEMD160.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'little'); else return utils.split32(this.h, 'little'); }; function f(j, x, y, z) { if (j <= 15) return x ^ y ^ z; else if (j <= 31) return (x & y) | ((~x) & z); else if (j <= 47) return (x | (~y)) ^ z; else if (j <= 63) return (x & z) | (y & (~z)); else return x ^ (y | (~z)); } function K(j) { if (j <= 15) return 0x00000000; else if (j <= 31) return 0x5a827999; else if (j <= 47) return 0x6ed9eba1; else if (j <= 63) return 0x8f1bbcdc; else return 0xa953fd4e; } function Kh(j) { if (j <= 15) return 0x50a28be6; else if (j <= 31) return 0x5c4dd124; else if (j <= 47) return 0x6d703ef3; else if (j <= 63) return 0x7a6d76e9; else return 0x00000000; } var r = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ]; var rh = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ]; var s = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]; var sh = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; },{"./common":320,"./utils":330}],323:[function(require,module,exports){ 'use strict'; exports.sha1 = require('./sha/1'); exports.sha224 = require('./sha/224'); exports.sha256 = require('./sha/256'); exports.sha384 = require('./sha/384'); exports.sha512 = require('./sha/512'); },{"./sha/1":324,"./sha/224":325,"./sha/256":326,"./sha/384":327,"./sha/512":328}],324:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var common = require('../common'); var shaCommon = require('./common'); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_5 = utils.sum32_5; var ft_1 = shaCommon.ft_1; var BlockHash = common.BlockHash; var sha1_K = [ 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 ]; function SHA1() { if (!(this instanceof SHA1)) return new SHA1(); BlockHash.call(this); this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; this.W = new Array(80); } utils.inherits(SHA1, BlockHash); module.exports = SHA1; SHA1.blockSize = 512; SHA1.outSize = 160; SHA1.hmacStrength = 80; SHA1.padLength = 64; SHA1.prototype._update = function _update(msg, start) { var W = this.W; for (var i = 0; i < 16; i++) W[i] = msg[start + i]; for(; i < W.length; i++) W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); var a = this.h[0]; var b = this.h[1]; var c = this.h[2]; var d = this.h[3]; var e = this.h[4]; for (i = 0; i < W.length; i++) { var s = ~~(i / 20); var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); e = d; d = c; c = rotl32(b, 30); b = a; a = t; } this.h[0] = sum32(this.h[0], a); this.h[1] = sum32(this.h[1], b); this.h[2] = sum32(this.h[2], c); this.h[3] = sum32(this.h[3], d); this.h[4] = sum32(this.h[4], e); }; SHA1.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big'); else return utils.split32(this.h, 'big'); }; },{"../common":320,"../utils":330,"./common":329}],325:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var SHA256 = require('./256'); function SHA224() { if (!(this instanceof SHA224)) return new SHA224(); SHA256.call(this); this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; } utils.inherits(SHA224, SHA256); module.exports = SHA224; SHA224.blockSize = 512; SHA224.outSize = 224; SHA224.hmacStrength = 192; SHA224.padLength = 64; SHA224.prototype._digest = function digest(enc) { // Just truncate output if (enc === 'hex') return utils.toHex32(this.h.slice(0, 7), 'big'); else return utils.split32(this.h.slice(0, 7), 'big'); }; },{"../utils":330,"./256":326}],326:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var common = require('../common'); var shaCommon = require('./common'); var assert = require('minimalistic-assert'); var sum32 = utils.sum32; var sum32_4 = utils.sum32_4; var sum32_5 = utils.sum32_5; var ch32 = shaCommon.ch32; var maj32 = shaCommon.maj32; var s0_256 = shaCommon.s0_256; var s1_256 = shaCommon.s1_256; var g0_256 = shaCommon.g0_256; var g1_256 = shaCommon.g1_256; var BlockHash = common.BlockHash; var sha256_K = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; function SHA256() { if (!(this instanceof SHA256)) return new SHA256(); BlockHash.call(this); this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; this.k = sha256_K; this.W = new Array(64); } utils.inherits(SHA256, BlockHash); module.exports = SHA256; SHA256.blockSize = 512; SHA256.outSize = 256; SHA256.hmacStrength = 192; SHA256.padLength = 64; SHA256.prototype._update = function _update(msg, start) { var W = this.W; for (var i = 0; i < 16; i++) W[i] = msg[start + i]; for (; i < W.length; i++) W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); var a = this.h[0]; var b = this.h[1]; var c = this.h[2]; var d = this.h[3]; var e = this.h[4]; var f = this.h[5]; var g = this.h[6]; var h = this.h[7]; assert(this.k.length === W.length); for (i = 0; i < W.length; i++) { var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); var T2 = sum32(s0_256(a), maj32(a, b, c)); h = g; g = f; f = e; e = sum32(d, T1); d = c; c = b; b = a; a = sum32(T1, T2); } this.h[0] = sum32(this.h[0], a); this.h[1] = sum32(this.h[1], b); this.h[2] = sum32(this.h[2], c); this.h[3] = sum32(this.h[3], d); this.h[4] = sum32(this.h[4], e); this.h[5] = sum32(this.h[5], f); this.h[6] = sum32(this.h[6], g); this.h[7] = sum32(this.h[7], h); }; SHA256.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big'); else return utils.split32(this.h, 'big'); }; },{"../common":320,"../utils":330,"./common":329,"minimalistic-assert":342}],327:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var SHA512 = require('./512'); function SHA384() { if (!(this instanceof SHA384)) return new SHA384(); SHA512.call(this); this.h = [ 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4 ]; } utils.inherits(SHA384, SHA512); module.exports = SHA384; SHA384.blockSize = 1024; SHA384.outSize = 384; SHA384.hmacStrength = 192; SHA384.padLength = 128; SHA384.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h.slice(0, 12), 'big'); else return utils.split32(this.h.slice(0, 12), 'big'); }; },{"../utils":330,"./512":328}],328:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var common = require('../common'); var assert = require('minimalistic-assert'); var rotr64_hi = utils.rotr64_hi; var rotr64_lo = utils.rotr64_lo; var shr64_hi = utils.shr64_hi; var shr64_lo = utils.shr64_lo; var sum64 = utils.sum64; var sum64_hi = utils.sum64_hi; var sum64_lo = utils.sum64_lo; var sum64_4_hi = utils.sum64_4_hi; var sum64_4_lo = utils.sum64_4_lo; var sum64_5_hi = utils.sum64_5_hi; var sum64_5_lo = utils.sum64_5_lo; var BlockHash = common.BlockHash; var sha512_K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; function SHA512() { if (!(this instanceof SHA512)) return new SHA512(); BlockHash.call(this); this.h = [ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179 ]; this.k = sha512_K; this.W = new Array(160); } utils.inherits(SHA512, BlockHash); module.exports = SHA512; SHA512.blockSize = 1024; SHA512.outSize = 512; SHA512.hmacStrength = 192; SHA512.padLength = 128; SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { var W = this.W; // 32 x 32bit words for (var i = 0; i < 32; i++) W[i] = msg[start + i]; for (; i < W.length; i += 2) { var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); var c1_hi = W[i - 14]; // i - 7 var c1_lo = W[i - 13]; var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); var c3_hi = W[i - 32]; // i - 16 var c3_lo = W[i - 31]; W[i] = sum64_4_hi( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); W[i + 1] = sum64_4_lo( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); } }; SHA512.prototype._update = function _update(msg, start) { this._prepareBlock(msg, start); var W = this.W; var ah = this.h[0]; var al = this.h[1]; var bh = this.h[2]; var bl = this.h[3]; var ch = this.h[4]; var cl = this.h[5]; var dh = this.h[6]; var dl = this.h[7]; var eh = this.h[8]; var el = this.h[9]; var fh = this.h[10]; var fl = this.h[11]; var gh = this.h[12]; var gl = this.h[13]; var hh = this.h[14]; var hl = this.h[15]; assert(this.k.length === W.length); for (var i = 0; i < W.length; i += 2) { var c0_hi = hh; var c0_lo = hl; var c1_hi = s1_512_hi(eh, el); var c1_lo = s1_512_lo(eh, el); var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); var c3_hi = this.k[i]; var c3_lo = this.k[i + 1]; var c4_hi = W[i]; var c4_lo = W[i + 1]; var T1_hi = sum64_5_hi( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); var T1_lo = sum64_5_lo( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); c0_hi = s0_512_hi(ah, al); c0_lo = s0_512_lo(ah, al); c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; eh = sum64_hi(dh, dl, T1_hi, T1_lo); el = sum64_lo(dl, dl, T1_hi, T1_lo); dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); } sum64(this.h, 0, ah, al); sum64(this.h, 2, bh, bl); sum64(this.h, 4, ch, cl); sum64(this.h, 6, dh, dl); sum64(this.h, 8, eh, el); sum64(this.h, 10, fh, fl); sum64(this.h, 12, gh, gl); sum64(this.h, 14, hh, hl); }; SHA512.prototype._digest = function digest(enc) { if (enc === 'hex') return utils.toHex32(this.h, 'big'); else return utils.split32(this.h, 'big'); }; function ch64_hi(xh, xl, yh, yl, zh) { var r = (xh & yh) ^ ((~xh) & zh); if (r < 0) r += 0x100000000; return r; } function ch64_lo(xh, xl, yh, yl, zh, zl) { var r = (xl & yl) ^ ((~xl) & zl); if (r < 0) r += 0x100000000; return r; } function maj64_hi(xh, xl, yh, yl, zh) { var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); if (r < 0) r += 0x100000000; return r; } function maj64_lo(xh, xl, yh, yl, zh, zl) { var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); if (r < 0) r += 0x100000000; return r; } function s0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 28); var c1_hi = rotr64_hi(xl, xh, 2); // 34 var c2_hi = rotr64_hi(xl, xh, 7); // 39 var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function s0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 28); var c1_lo = rotr64_lo(xl, xh, 2); // 34 var c2_lo = rotr64_lo(xl, xh, 7); // 39 var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function s1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 14); var c1_hi = rotr64_hi(xh, xl, 18); var c2_hi = rotr64_hi(xl, xh, 9); // 41 var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function s1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 14); var c1_lo = rotr64_lo(xh, xl, 18); var c2_lo = rotr64_lo(xl, xh, 9); // 41 var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function g0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 1); var c1_hi = rotr64_hi(xh, xl, 8); var c2_hi = shr64_hi(xh, xl, 7); var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function g0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 1); var c1_lo = rotr64_lo(xh, xl, 8); var c2_lo = shr64_lo(xh, xl, 7); var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } function g1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 19); var c1_hi = rotr64_hi(xl, xh, 29); // 61 var c2_hi = shr64_hi(xh, xl, 6); var r = c0_hi ^ c1_hi ^ c2_hi; if (r < 0) r += 0x100000000; return r; } function g1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 19); var c1_lo = rotr64_lo(xl, xh, 29); // 61 var c2_lo = shr64_lo(xh, xl, 6); var r = c0_lo ^ c1_lo ^ c2_lo; if (r < 0) r += 0x100000000; return r; } },{"../common":320,"../utils":330,"minimalistic-assert":342}],329:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); var rotr32 = utils.rotr32; function ft_1(s, x, y, z) { if (s === 0) return ch32(x, y, z); if (s === 1 || s === 3) return p32(x, y, z); if (s === 2) return maj32(x, y, z); } exports.ft_1 = ft_1; function ch32(x, y, z) { return (x & y) ^ ((~x) & z); } exports.ch32 = ch32; function maj32(x, y, z) { return (x & y) ^ (x & z) ^ (y & z); } exports.maj32 = maj32; function p32(x, y, z) { return x ^ y ^ z; } exports.p32 = p32; function s0_256(x) { return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); } exports.s0_256 = s0_256; function s1_256(x) { return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); } exports.s1_256 = s1_256; function g0_256(x) { return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); } exports.g0_256 = g0_256; function g1_256(x) { return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); } exports.g1_256 = g1_256; },{"../utils":330}],330:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); var inherits = require('inherits'); exports.inherits = inherits; function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg === 'string') { if (!enc) { for (var i = 0; i < msg.length; i++) { var c = msg.charCodeAt(i); var hi = c >> 8; var lo = c & 0xff; if (hi) res.push(hi, lo); else res.push(lo); } } else if (enc === 'hex') { msg = msg.replace(/[^a-z0-9]+/ig, ''); if (msg.length % 2 !== 0) msg = '0' + msg; for (i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16)); } } else { for (i = 0; i < msg.length; i++) res[i] = msg[i] | 0; } return res; } exports.toArray = toArray; function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); return res; } exports.toHex = toHex; function htonl(w) { var res = (w >>> 24) | ((w >>> 8) & 0xff00) | ((w << 8) & 0xff0000) | ((w & 0xff) << 24); return res >>> 0; } exports.htonl = htonl; function toHex32(msg, endian) { var res = ''; for (var i = 0; i < msg.length; i++) { var w = msg[i]; if (endian === 'little') w = htonl(w); res += zero8(w.toString(16)); } return res; } exports.toHex32 = toHex32; function zero2(word) { if (word.length === 1) return '0' + word; else return word; } exports.zero2 = zero2; function zero8(word) { if (word.length === 7) return '0' + word; else if (word.length === 6) return '00' + word; else if (word.length === 5) return '000' + word; else if (word.length === 4) return '0000' + word; else if (word.length === 3) return '00000' + word; else if (word.length === 2) return '000000' + word; else if (word.length === 1) return '0000000' + word; else return word; } exports.zero8 = zero8; function join32(msg, start, end, endian) { var len = end - start; assert(len % 4 === 0); var res = new Array(len / 4); for (var i = 0, k = start; i < res.length; i++, k += 4) { var w; if (endian === 'big') w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; else w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; res[i] = w >>> 0; } return res; } exports.join32 = join32; function split32(msg, endian) { var res = new Array(msg.length * 4); for (var i = 0, k = 0; i < msg.length; i++, k += 4) { var m = msg[i]; if (endian === 'big') { res[k] = m >>> 24; res[k + 1] = (m >>> 16) & 0xff; res[k + 2] = (m >>> 8) & 0xff; res[k + 3] = m & 0xff; } else { res[k + 3] = m >>> 24; res[k + 2] = (m >>> 16) & 0xff; res[k + 1] = (m >>> 8) & 0xff; res[k] = m & 0xff; } } return res; } exports.split32 = split32; function rotr32(w, b) { return (w >>> b) | (w << (32 - b)); } exports.rotr32 = rotr32; function rotl32(w, b) { return (w << b) | (w >>> (32 - b)); } exports.rotl32 = rotl32; function sum32(a, b) { return (a + b) >>> 0; } exports.sum32 = sum32; function sum32_3(a, b, c) { return (a + b + c) >>> 0; } exports.sum32_3 = sum32_3; function sum32_4(a, b, c, d) { return (a + b + c + d) >>> 0; } exports.sum32_4 = sum32_4; function sum32_5(a, b, c, d, e) { return (a + b + c + d + e) >>> 0; } exports.sum32_5 = sum32_5; function sum64(buf, pos, ah, al) { var bh = buf[pos]; var bl = buf[pos + 1]; var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; buf[pos] = hi >>> 0; buf[pos + 1] = lo; } exports.sum64 = sum64; function sum64_hi(ah, al, bh, bl) { var lo = (al + bl) >>> 0; var hi = (lo < al ? 1 : 0) + ah + bh; return hi >>> 0; } exports.sum64_hi = sum64_hi; function sum64_lo(ah, al, bh, bl) { var lo = al + bl; return lo >>> 0; } exports.sum64_lo = sum64_lo; function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { var carry = 0; var lo = al; lo = (lo + bl) >>> 0; carry += lo < al ? 1 : 0; lo = (lo + cl) >>> 0; carry += lo < cl ? 1 : 0; lo = (lo + dl) >>> 0; carry += lo < dl ? 1 : 0; var hi = ah + bh + ch + dh + carry; return hi >>> 0; } exports.sum64_4_hi = sum64_4_hi; function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { var lo = al + bl + cl + dl; return lo >>> 0; } exports.sum64_4_lo = sum64_4_lo; function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var carry = 0; var lo = al; lo = (lo + bl) >>> 0; carry += lo < al ? 1 : 0; lo = (lo + cl) >>> 0; carry += lo < cl ? 1 : 0; lo = (lo + dl) >>> 0; carry += lo < dl ? 1 : 0; lo = (lo + el) >>> 0; carry += lo < el ? 1 : 0; var hi = ah + bh + ch + dh + eh + carry; return hi >>> 0; } exports.sum64_5_hi = sum64_5_hi; function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var lo = al + bl + cl + dl + el; return lo >>> 0; } exports.sum64_5_lo = sum64_5_lo; function rotr64_hi(ah, al, num) { var r = (al << (32 - num)) | (ah >>> num); return r >>> 0; } exports.rotr64_hi = rotr64_hi; function rotr64_lo(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } exports.rotr64_lo = rotr64_lo; function shr64_hi(ah, al, num) { return ah >>> num; } exports.shr64_hi = shr64_hi; function shr64_lo(ah, al, num) { var r = (ah << (32 - num)) | (al >>> num); return r >>> 0; } exports.shr64_lo = shr64_lo; },{"inherits":334,"minimalistic-assert":342}],331:[function(require,module,exports){ 'use strict'; var hash = require('hash.js'); var utils = require('minimalistic-crypto-utils'); var assert = require('minimalistic-assert'); function HmacDRBG(options) { if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); this.hash = options.hash; this.predResist = !!options.predResist; this.outLen = this.hash.outSize; this.minEntropy = options.minEntropy || this.hash.hmacStrength; this._reseed = null; this.reseedInterval = null; this.K = null; this.V = null; var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); var pers = utils.toArray(options.pers, options.persEnc || 'hex'); assert(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._init(entropy, nonce, pers); } module.exports = HmacDRBG; HmacDRBG.prototype._init = function init(entropy, nonce, pers) { var seed = entropy.concat(nonce).concat(pers); this.K = new Array(this.outLen / 8); this.V = new Array(this.outLen / 8); for (var i = 0; i < this.V.length; i++) { this.K[i] = 0x00; this.V[i] = 0x01; } this._update(seed); this._reseed = 1; this.reseedInterval = 0x1000000000000; // 2^48 }; HmacDRBG.prototype._hmac = function hmac() { return new hash.hmac(this.hash, this.K); }; HmacDRBG.prototype._update = function update(seed) { var kmac = this._hmac() .update(this.V) .update([ 0x00 ]); if (seed) kmac = kmac.update(seed); this.K = kmac.digest(); this.V = this._hmac().update(this.V).digest(); if (!seed) return; this.K = this._hmac() .update(this.V) .update([ 0x01 ]) .update(seed) .digest(); this.V = this._hmac().update(this.V).digest(); }; HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { // Optional entropy enc if (typeof entropyEnc !== 'string') { addEnc = add; add = entropyEnc; entropyEnc = null; } entropy = utils.toArray(entropy, entropyEnc); add = utils.toArray(add, addEnc); assert(entropy.length >= (this.minEntropy / 8), 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); this._update(entropy.concat(add || [])); this._reseed = 1; }; HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { if (this._reseed > this.reseedInterval) throw new Error('Reseed is required'); // Optional encoding if (typeof enc !== 'string') { addEnc = add; add = enc; enc = null; } // Optional additional data if (add) { add = utils.toArray(add, addEnc || 'hex'); this._update(add); } var temp = []; while (temp.length < len) { this.V = this._hmac().update(this.V).digest(); temp = temp.concat(this.V); } var res = temp.slice(0, len); this._update(add); this._reseed++; return utils.encode(res, enc); }; },{"hash.js":319,"minimalistic-assert":342,"minimalistic-crypto-utils":343}],332:[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 } },{}],333:[function(require,module,exports){ var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],334:[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 } } },{}],335:[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)) } },{}],336:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],337:[function(require,module,exports){ (function (process){ 'use strict'; function Kareem() { this._pres = {}; this._posts = {}; } 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 error = null; let maybePromise = null; try { maybePromise = pre.fn.call(context); } catch (err) { error = 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(error); }); } } next(error); } } }; 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]; 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) { var posts = get(this._posts, name, []); var numPosts = posts.length; for (var i = 0; i < numPosts; ++i) { posts[i].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) { var lastArg = (args.length > 0 ? args[args.length - 1] : null); var argsWithoutCb = typeof lastArg === 'function' ? args.slice(0, args.length - 1) : args; var _this = this; options = options || {}; this.execPre(name, context, args, function(error) { if (error) { var numCallbackParams = options.numCallbackParams || 0; var errorArgs = options.contextParameter ? [context] : []; for (var i = errorArgs.length; i < numCallbackParams; ++i) { errorArgs.push(null); } return _handleWrapError(_this, error, name, context, errorArgs, options, lastArg); } var end = (typeof lastArg === 'function' ? args.length - 1 : args.length); fn.apply(context, args.slice(0, end).concat(_cb)); function _cb() { var args = arguments; var 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.createWrapper = function(name, fn, context, options) { var _this = this; if (this._pres[name] == null && this._posts[name] == null) { // Fast path: if there's no hooks for this function, just return the function return fn; } 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) { if (typeof arguments[1] !== 'boolean') { error = fn; fn = isAsync; isAsync = false; } this._pres[name] = get(this._pres, name, []); const pres = this._pres[name]; if (isAsync) { pres.numAsync = pres.numAsync || 0; ++pres.numAsync; } if (unshift) { pres.unshift({ fn: fn, isAsync: isAsync }); } else { pres.push({ fn: fn, isAsync: isAsync }); } return this; }; Kareem.prototype.post = function(name, fn, unshift) { this._posts[name] = get(this._posts, name, []); if (unshift) { this._posts[name].unshift(fn); } else { this._posts[name].push(fn); } return this; }; Kareem.prototype.clone = function() { const n = new Kareem(); for (let key of Object.keys(this._pres)) { n._pres[key] = this._pres[key].slice(); n._pres[key].numAsync = this._pres[key].numAsync; } for (let key of Object.keys(this._posts)) { n._posts[key] = this._posts[key].slice(); } return n; }; Kareem.prototype.merge = function(other) { var ret = this.clone(); for (let key of Object.keys(other._pres)) { const sourcePres = get(ret._pres, key, []); const deduplicated = other._pres[key]. // Deduplicate based on `fn` filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1); ret._pres[key] = sourcePres.concat(deduplicated); ret._pres[key].numAsync = get(ret._pres[key], 'numAsync', 0); ret._pres[key].numAsync += deduplicated.filter(p => p.isAsync).length; } for (let key of Object.keys(other._posts)) { const sourcePosts = get(ret._posts, key, []); const deduplicated = other._posts[key]. filter(p => sourcePosts.indexOf(p) === -1); ret._posts[key] = sourcePosts.concat(deduplicated); } return ret; }; function get(obj, key, def) { if (obj[key] != null) { return obj[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":507}],338:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]', symbolTag = '[object Symbol]'; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Symbol = root.Symbol, splice = arrayProto.splice; /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'), nativeCreate = getNative(Object, 'create'); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = isKey(path, object) ? [path] : castPath(path); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function castPath(value) { return isArray(value) ? value : stringToPath(value); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoize(function(string) { string = toString(string); var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],339:[function(require,module,exports){ (function (Buffer){ 'use strict' var inherits = require('inherits') var HashBase = require('hash-base') var ARRAY16 = new Array(16) function MD5 () { HashBase.call(this, 64) // state this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 } inherits(MD5, HashBase) MD5.prototype._update = function () { var M = ARRAY16 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) var a = this._a var b = this._b var c = this._c var d = this._d a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) c = fnF(c, d, a, b, M[2], 0x242070db, 17) b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) c = fnF(c, d, a, b, M[6], 0xa8304613, 17) b = fnF(b, c, d, a, M[7], 0xfd469501, 22) a = fnF(a, b, c, d, M[8], 0x698098d8, 7) d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) a = fnF(a, b, c, d, M[12], 0x6b901122, 7) d = fnF(d, a, b, c, M[13], 0xfd987193, 12) c = fnF(c, d, a, b, M[14], 0xa679438e, 17) b = fnF(b, c, d, a, M[15], 0x49b40821, 22) a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) d = fnG(d, a, b, c, M[6], 0xc040b340, 9) c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) d = fnG(d, a, b, c, M[10], 0x02441453, 9) c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) d = fnH(d, a, b, c, M[8], 0x8771f681, 11) c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) b = fnH(b, c, d, a, M[6], 0x04881d05, 23) a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) a = fnI(a, b, c, d, M[0], 0xf4292244, 6) d = fnI(d, a, b, c, M[7], 0x432aff97, 10) c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) c = fnI(c, d, a, b, M[6], 0xa3014314, 15) b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) this._a = (this._a + a) | 0 this._b = (this._b + b) | 0 this._c = (this._c + c) | 0 this._d = (this._d + d) | 0 } MD5.prototype._digest = function () { // create padding and handle blocks this._block[this._blockOffset++] = 0x80 if (this._blockOffset > 56) { this._block.fill(0, this._blockOffset, 64) this._update() this._blockOffset = 0 } this._block.fill(0, this._blockOffset, 56) this._block.writeUInt32LE(this._length[0], 56) this._block.writeUInt32LE(this._length[1], 60) this._update() // produce result var buffer = new Buffer(16) buffer.writeInt32LE(this._a, 0) buffer.writeInt32LE(this._b, 4) buffer.writeInt32LE(this._c, 8) buffer.writeInt32LE(this._d, 12) return buffer } function rotl (x, n) { return (x << n) | (x >>> (32 - n)) } function fnF (a, b, c, d, m, k, s) { return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 } function fnG (a, b, c, d, m, k, s) { return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 } function fnH (a, b, c, d, m, k, s) { return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 } function fnI (a, b, c, d, m, k, s) { return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 } module.exports = MD5 }).call(this,require("buffer").Buffer) },{"buffer":144,"hash-base":340,"inherits":334}],340:[function(require,module,exports){ 'use strict' var Buffer = require('safe-buffer').Buffer var Transform = require('stream').Transform var inherits = require('inherits') function throwIfNotStringOrBuffer (val, prefix) { if (!Buffer.isBuffer(val) && typeof val !== 'string') { throw new TypeError(prefix + ' must be a string or a buffer') } } function HashBase (blockSize) { Transform.call(this) this._block = Buffer.allocUnsafe(blockSize) this._blockSize = blockSize this._blockOffset = 0 this._length = [0, 0, 0, 0] this._finalized = false } inherits(HashBase, Transform) HashBase.prototype._transform = function (chunk, encoding, callback) { var error = null try { this.update(chunk, encoding) } catch (err) { error = err } callback(error) } HashBase.prototype._flush = function (callback) { var error = null try { this.push(this.digest()) } catch (err) { error = err } callback(error) } HashBase.prototype.update = function (data, encoding) { throwIfNotStringOrBuffer(data, 'Data') if (this._finalized) throw new Error('Digest already called') if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) // consume data var block = this._block var offset = 0 while (this._blockOffset + data.length - offset >= this._blockSize) { for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] this._update() this._blockOffset = 0 } while (offset < data.length) block[this._blockOffset++] = data[offset++] // update length for (var j = 0, carry = data.length * 8; carry > 0; ++j) { this._length[j] += carry carry = (this._length[j] / 0x0100000000) | 0 if (carry > 0) this._length[j] -= 0x0100000000 * carry } return this } HashBase.prototype._update = function () { throw new Error('_update is not implemented') } HashBase.prototype.digest = function (encoding) { if (this._finalized) throw new Error('Digest already called') this._finalized = true var digest = this._digest() if (encoding !== undefined) digest = digest.toString(encoding) // reset state this._block.fill(0) this._blockOffset = 0 for (var i = 0; i < 4; ++i) this._length[i] = 0 return digest } HashBase.prototype._digest = function () { throw new Error('_digest is not implemented') } module.exports = HashBase },{"inherits":334,"safe-buffer":537,"stream":548}],341:[function(require,module,exports){ var bn = require('bn.js'); var brorand = require('brorand'); function MillerRabin(rand) { this.rand = rand || new brorand.Rand(); } module.exports = MillerRabin; MillerRabin.create = function create(rand) { return new MillerRabin(rand); }; MillerRabin.prototype._randbelow = function _randbelow(n) { var len = n.bitLength(); var min_bytes = Math.ceil(len / 8); // Generage random bytes until a number less than n is found. // This ensures that 0..n-1 have an equal probability of being selected. do var a = new bn(this.rand.generate(min_bytes)); while (a.cmp(n) >= 0); return a; }; MillerRabin.prototype._randrange = function _randrange(start, stop) { // Generate a random number greater than or equal to start and less than stop. var size = stop.sub(start); return start.add(this._randbelow(size)); }; MillerRabin.prototype.test = function test(n, k, cb) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); var prime = true; for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); if (cb) cb(a); var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return false; if (x.cmp(rn1) === 0) break; } if (i === s) return false; } return prime; }; MillerRabin.prototype.getDivisor = function getDivisor(n, k) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); var g = n.gcd(a); if (g.cmpn(1) !== 0) return g; var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return x.fromRed().subn(1).gcd(n); if (x.cmp(rn1) === 0) break; } if (i === s) { x = x.redSqr(); return x.fromRed().subn(1).gcd(n); } } return false; }; },{"bn.js":91,"brorand":92}],342:[function(require,module,exports){ module.exports = assert; function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } assert.equal = function assertEqual(l, r, msg) { if (l != r) throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; },{}],343:[function(require,module,exports){ 'use strict'; var utils = exports; function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg !== 'string') { for (var i = 0; i < msg.length; i++) res[i] = msg[i] | 0; return res; } if (enc === 'hex') { msg = msg.replace(/[^a-z0-9]+/ig, ''); if (msg.length % 2 !== 0) msg = '0' + msg; for (var i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16)); } else { for (var i = 0; i < msg.length; i++) { var c = msg.charCodeAt(i); var hi = c >> 8; var lo = c & 0xff; if (hi) res.push(hi, lo); else res.push(lo); } } return res; } utils.toArray = toArray; function zero2(word) { if (word.length === 1) return '0' + word; else return word; } utils.zero2 = zero2; function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); return res; } utils.toHex = toHex; utils.encode = function encode(arr, enc) { if (enc === 'hex') return toHex(arr); else return arr; }; },{}],344:[function(require,module,exports){ //! moment.js ;(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 isObjectEmpty(obj) { if (Object.getOwnPropertyNames) { return (Object.getOwnPropertyNames(obj).length === 0); } else { var k; for (k in obj) { if (obj.hasOwnProperty(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 hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } 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, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso : false, parsedDateParts : [], 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); var len = t.length >>> 0; for (var 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); var parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }); var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !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 = []; 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; } var updateInProgress = false; // 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 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; } // 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; } 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 = []; var arg; for (var i = 0; i < arguments.length; i++) { arg = ''; if (typeof arguments[i] === 'object') { arg += '\n[' + i + '] '; for (var key in arguments[0]) { 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 input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; } function set (config) { var prop, i; for (i in config) { 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; } 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.replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); return this._longDateFormat[key]; } var defaultInvalidDate = 'Invalid date'; function invalidDate () { return this._invalidDate; } var defaultOrdinal = '%d'; var 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', 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 = []; for (var u in unitsObj) { units.push({unit: u, priority: priorities[u]}); } units.sort(function (a, b) { return a.priority - b.priority; }); return units; } 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?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; var formatFunctions = {}; var 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 match1 = /\d/; // 0 - 9 var match2 = /\d\d/; // 00 - 99 var match3 = /\d{3}/; // 000 - 999 var match4 = /\d{4}/; // 0000 - 9999 var match6 = /[+-]?\d{6}/; // -999999 - 999999 var match1to2 = /\d\d?/; // 0 - 99 var match3to4 = /\d\d\d\d?/; // 999 - 9999 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 var match1to3 = /\d{1,3}/; // 0 - 999 var match1to4 = /\d{1,4}/; // 0 - 9999 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 var matchUnsigned = /\d+/; // 0 - inf var matchSigned = /[+-]?\d+/; // -inf - inf var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z var 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 var 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; var 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; var MONTH = 1; var DATE = 2; var HOUR = 3; var MINUTE = 4; var SECOND = 5; var MILLISECOND = 6; var WEEK = 7; var WEEKDAY = 8; // FORMATTING addFormatToken('Y', 0, 0, function () { var y = this.year(); return y <= 9999 ? '' + y : '+' + 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; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } // 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 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) { 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); for (var 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; } 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 MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); 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()]; } var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); 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()); } var defaultMonthsShortRegex = matchWord; 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; } } var defaultMonthsRegex = matchWord; 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'); } function createDate (y, m, d, h, M, s, ms) { // can't just apply() to create a date: // https://stackoverflow.com/q/181348 var date = new Date(y, m, d, h, M, s, ms); // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { date.setFullYear(y); } return date; } function createUTCDate (y) { var date = new Date(Date.UTC.apply(null, arguments)); // the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } 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 1st 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 var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); function localeWeekdays (m, format) { if (!m) { return isArray(this._weekdays) ? this._weekdays : this._weekdays['standalone']; } return isArray(this._weekdays) ? this._weekdays[m.day()] : this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; } var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); function localeWeekdaysShort (m) { return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; } var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); function localeWeekdaysMin (m) { return (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; } } var defaultWeekdaysRegex = matchWord; 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; } } var defaultWeekdaysShortRegex = matchWord; 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; } } var defaultWeekdaysMinRegex = matchWord; 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 = this.weekdaysMin(mom, ''); shortp = this.weekdaysShort(mom, ''); longp = 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); for (i = 0; i < 7; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); mixedPieces[i] = regexEscape(mixedPieces[i]); } 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; var 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; var 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; function localeMeridiem (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } // MOMENTS // 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. var getSetHour = makeGetSet('Hours', true); 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 = {}; var localeFamilies = {}; var globalLocale; 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 && compareArrays(split, next, true) >= 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; // TODO: Find a better way to register and load all the locales in Node if (!locales[name] && (typeof module !== 'undefined') && module && module.exports) { try { oldLocale = globalLocale._abbr; var aliasedRequire = require; aliasedRequire('./locale/' + name); getSetGlobalLocale(oldLocale); } catch (e) {} } 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; // MERGE tmpLocale = loadLocale(name); if (tmpLocale != null) { parentConfig = tmpLocale._config; } config = mergeConfigs(parentConfig, config); 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; } 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; var 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; } // 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; 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; var 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 begining of week weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { // default to begining 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; } } // 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)?)?$/; var 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)?)?$/; var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; var 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}/], // YYYYMM is NOT allowed by the standard ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/] ]; // iso time formats and regexes var 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/] ]; var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // 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; } } // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 var 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}))$/; 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, ' ').trim(); } function checkWeekday(weekdayStr, parsedInput, config) { if (weekdayStr) { // TODO: Replace the vanilla JS Date object with an indepentent 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; } var 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 }; 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); var 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)); if (match) { var 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 iso format or fallback 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; } // 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' : '')); } ); // 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; 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]; // console.log('token', token, 'parsedInput', parsedInput, // 'regex', getParseRegexForToken(token, config)); 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); 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; 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; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // 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 (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i); config._a = map([i.year, i.month, i.day || i.date, 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 (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(); } } ); var 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) { for (var key in m) { if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { return false; } } var unitHasDecimal = false; for (var 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 || 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); } } // FORMATTING function offset (token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(); var 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); if (matches === null) { return null; } var chunk = matches[matches.length - 1] || []; var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; var 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() / 15) * 15; } // 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 = {}; copyConfig(c, this); c = prepareConfig(c); if (c._a) { var 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 var 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)) { 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 : (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; } 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 = {milliseconds: 0, months: 0}; 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; } val = typeof val === 'string' ? +val : val; 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'); var subtract = createAdder(-1, 'subtract'); 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) { // 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'; var 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(!isUndefined(units) ? 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(!isUndefined(units) ? 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) { inclusivity = inclusivity || '()'; return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, 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) { // 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; var 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'; var zone = ''; if (!this.isLocal()) { func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; zone = 'Z'; } var prefix = '[' + func + '("]'; var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; var datetime = '-MM-DD[T]HH:mm:ss.SSS'; var 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; } function startOf (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': case 'date': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); } // weeks are a special case if (units === 'week') { this.weekday(0); } if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; } function endOf (units) { units = normalizeUnits(units); if (units === undefined || units === 'millisecond') { return this; } // 'date' is an alias for 'day', so it should be considered as such. if (units === 'date') { units = 'day'; } return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); } 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 }; } // 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 getWeeksInYear () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), 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'); // PRIOROITY 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; 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); } // MOMENTS var 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; proto.toJSON = toJSON; proto.toString = toString; proto.unix = unix; proto.valueOf = valueOf; proto.creationData = creationData; 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.isoWeeksInYear = getISOWeeksInYear; 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.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(); var 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; var 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; if (index != null) { return get$1(format, (index + shift) % 7, field, 'day'); } var i; var out = []; 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', { 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; var days = this._days; var months = this._months; var data = this._data; var 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; var months; var milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToMonths(days); return units === 'month' ? months : 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'); var asSeconds = makeAs('s'); var asMinutes = makeAs('m'); var asHours = makeAs('h'); var asDays = makeAs('d'); var asWeeks = makeAs('w'); var asMonths = makeAs('M'); var 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'); var seconds = makeGetter('seconds'); var minutes = makeGetter('minutes'); var hours = makeGetter('hours'); var days = makeGetter('days'); var months = makeGetter('months'); var years = makeGetter('years'); function weeks () { return absFloor(this.days() / 7); } var round = Math.round; var 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 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, locale) { var duration = createDuration(posNegDuration).abs(); var seconds = round(duration.as('s')); var minutes = round(duration.as('m')); var hours = round(duration.as('h')); var days = round(duration.as('d')); var months = round(duration.as('M')); var years = round(duration.as('y')); var 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] || 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 (withSuffix) { if (!this.isValid()) { return this.localeData().invalidDate(); } var locale = this.localeData(); var output = relativeTime$1(this, !withSuffix, 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; var days = abs$1(this._days); var months = abs$1(this._months); var minutes, hours, years; // 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 var Y = years; var M = months; var D = days; var h = hours; var m = minutes; var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; var total = this.asSeconds(); if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } var totalSign = total < 0 ? '-' : ''; var ymSign = sign(this._months) !== sign(total) ? '-' : ''; var daysSign = sign(this._days) !== sign(total) ? '-' : ''; var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; return totalSign + 'P' + (Y ? ymSign + Y + 'Y' : '') + (M ? ymSign + M + 'M' : '') + (D ? daysSign + D + 'D' : '') + ((h || m || s) ? 'T' : '') + (h ? hmsSign + h + 'H' : '') + (m ? hmsSign + m + 'M' : '') + (s ? 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.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; // Side effect imports // 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, 10) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); // Side effect imports hooks.version = '2.22.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: 'YYYY-[W]WW', // MONTH: 'YYYY-MM' // }; return hooks; }))); },{}],345:[function(require,module,exports){ 'use strict'; var BSON = require('bson'); var require_optional = require('require_optional'); try { // Attempt to grab the native BSON parser var BSONNative = require_optional('bson-ext'); // If we got the native parser, use it instead of the // Javascript one if (BSONNative) { BSON = BSONNative; } } catch (err) {} // eslint-disable-line module.exports = { MongoError: require('./lib/error').MongoError, MongoNetworkError: require('./lib/error').MongoNetworkError, Connection: require('./lib/connection/connection'), Server: require('./lib/topologies/server'), ReplSet: require('./lib/topologies/replset'), Mongos: require('./lib/topologies/mongos'), Logger: require('./lib/connection/logger'), Cursor: require('./lib/cursor'), ReadPreference: require('./lib/topologies/read_preference'), Sessions: require('./lib/sessions'), BSON: BSON, // Raw operations Query: require('./lib/connection/commands').Query, // Auth mechanisms MongoCR: require('./lib/auth/mongocr'), X509: require('./lib/auth/x509'), Plain: require('./lib/auth/plain'), GSSAPI: require('./lib/auth/gssapi'), ScramSHA1: require('./lib/auth/scram'), // Utilities parseConnectionString: require('./lib/uri_parser') }; },{"./lib/auth/gssapi":346,"./lib/auth/mongocr":347,"./lib/auth/plain":348,"./lib/auth/scram":349,"./lib/auth/x509":351,"./lib/connection/commands":353,"./lib/connection/connection":354,"./lib/connection/logger":355,"./lib/cursor":358,"./lib/error":359,"./lib/sessions":360,"./lib/topologies/mongos":361,"./lib/topologies/read_preference":362,"./lib/topologies/replset":363,"./lib/topologies/server":365,"./lib/uri_parser":367,"bson":125,"require_optional":534}],346:[function(require,module,exports){ (function (process){ 'use strict'; var f = require('util').format, require_optional = require('require_optional'), Query = require('../connection/commands').Query, MongoError = require('../error').MongoError; var AuthSession = function(db, username, password, options) { this.db = db; this.username = username; this.password = password; this.options = options; }; AuthSession.prototype.equal = function(session) { return ( session.db === this.db && session.username === this.username && session.password === this.password ); }; // Kerberos class var Kerberos = null; var MongoAuthProcess = null; // Try to grab the Kerberos class try { Kerberos = require_optional('kerberos').Kerberos; // Authentication process for Mongo MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess; } catch (err) {} // eslint-disable-line /** * Creates a new GSSAPI authentication mechanism * @class * @return {GSSAPI} A cursor instance */ var GSSAPI = function(bson) { this.bson = bson; this.authStore = []; }; /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ GSSAPI.prototype.auth = function(server, connections, db, username, password, options, callback) { var self = this; // We don't have the Kerberos library if (Kerberos == null) return callback(new Error('Kerberos library is not installed')); var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; // Total connections var count = connections.length; if (count === 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var errorObject = null; // For each connection we need to authenticate while (connections.length > 0) { // Execute MongoCR var execute = function(connection) { // Start Auth process for a connection GSSAPIInitialize( self, db, username, password, db, gssapiServiceName, server, connection, options, function(err, r) { // Adjust count count = count - 1; // If we have an error if (err) { errorObject = err; } else if (r.result['$err']) { errorObject = r.result; } else if (r.result['errmsg']) { errorObject = r.result; } else { numberOfValidConnections = numberOfValidConnections + 1; } // We have authenticated all connections if (count === 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password, options)); // Return correct authentication callback(null, true); } else if (count === 0) { if (errorObject == null) errorObject = new MongoError(f('failed to authenticate using mongocr')); callback(errorObject, false); } } ); }; var _execute = function(_connection) { process.nextTick(function() { execute(_connection); }); }; _execute(connections.shift()); } }; // // Initialize step var GSSAPIInitialize = function( self, db, username, password, authdb, gssapiServiceName, server, connection, options, callback ) { // Create authenticator var mongo_auth_process = new MongoAuthProcess( connection.host, connection.port, gssapiServiceName, options ); // Perform initialization mongo_auth_process.init(username, password, function(err) { if (err) return callback(err, false); // Perform the first step mongo_auth_process.transition('', function(err, payload) { if (err) return callback(err, false); // Call the next db step MongoDBGSSAPIFirstStep( self, mongo_auth_process, payload, db, username, password, authdb, server, connection, callback ); }); }); }; // // Perform first step against mongodb var MongoDBGSSAPIFirstStep = function( self, mongo_auth_process, payload, db, username, password, authdb, server, connection, callback ) { // Build the sasl start command var command = { saslStart: 1, mechanism: 'GSSAPI', payload: payload, autoAuthorize: 1 }; // Write the commmand on the connection server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (err) return callback(err, false); var doc = r.result; // Execute mongodb transition mongo_auth_process.transition(r.result.payload, function(err, payload) { if (err) return callback(err, false); // MongoDB API Second Step MongoDBGSSAPISecondStep( self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback ); }); } ); }; // // Perform first step against mongodb var MongoDBGSSAPISecondStep = function( self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback ) { // Build Authentication command to send to MongoDB var command = { saslContinue: 1, conversationId: doc.conversationId, payload: payload }; // Execute the command // Write the commmand on the connection server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (err) return callback(err, false); var doc = r.result; // Call next transition for kerberos mongo_auth_process.transition(doc.payload, function(err, payload) { if (err) return callback(err, false); // Call the last and third step MongoDBGSSAPIThirdStep( self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback ); }); } ); }; var MongoDBGSSAPIThirdStep = function( self, mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback ) { // Build final command var command = { saslContinue: 1, conversationId: doc.conversationId, payload: payload }; // Execute the command server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (err) return callback(err, false); mongo_auth_process.transition(null, function(err) { if (err) return callback(err, null); callback(null, r); }); } ); }; // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for (var i = 0; i < authStore.length; i++) { if (authStore[i].equal(session)) { found = true; break; } } if (!found) authStore.push(session); }; /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ GSSAPI.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db !== dbName; }); }; /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ GSSAPI.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var count = authStore.length; if (count === 0) return callback(null, null); // Iterate over all the auth details stored for (var i = 0; i < authStore.length; i++) { this.auth( server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err) { count = count - 1; // Done re-authenticating if (count === 0) { callback(err, null); } } ); } }; /** * This is a result from a authentication strategy * * @callback authResultCallback * @param {error} error An error object. Set to null if no error present * @param {boolean} result The result of the authentication process */ module.exports = GSSAPI; }).call(this,require('_process')) },{"../connection/commands":353,"../error":359,"_process":507,"require_optional":534,"util":563}],347:[function(require,module,exports){ (function (process){ 'use strict'; var f = require('util').format, crypto = require('crypto'), Query = require('../connection/commands').Query, MongoError = require('../error').MongoError; var AuthSession = function(db, username, password) { this.db = db; this.username = username; this.password = password; }; AuthSession.prototype.equal = function(session) { return ( session.db === this.db && session.username === this.username && session.password === this.password ); }; /** * Creates a new MongoCR authentication mechanism * @class * @return {MongoCR} A cursor instance */ var MongoCR = function(bson) { this.bson = bson; this.authStore = []; }; // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for (var i = 0; i < authStore.length; i++) { if (authStore[i].equal(session)) { found = true; break; } } if (!found) authStore.push(session); }; /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { var self = this; // Total connections var count = connections.length; if (count === 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var errorObject = null; // For each connection we need to authenticate while (connections.length > 0) { // Execute MongoCR var executeMongoCR = function(connection) { // Write the commmand on the connection server( connection, new Query( self.bson, f('%s.$cmd', db), { getnonce: 1 }, { numberToSkip: 0, numberToReturn: 1 } ), function(err, r) { var nonce = null; var key = null; // Adjust the number of connections left // Get nonce if (err == null) { nonce = r.result.nonce; // Use node md5 generator var md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ':mongo:' + password, 'utf8'); var hash_password = md5.digest('hex'); // Final key md5 = crypto.createHash('md5'); md5.update(nonce + username + hash_password, 'utf8'); key = md5.digest('hex'); } // Execute command // Write the commmand on the connection server( connection, new Query( self.bson, f('%s.$cmd', db), { authenticate: 1, user: username, nonce: nonce, key: key }, { numberToSkip: 0, numberToReturn: 1 } ), function(err, r) { count = count - 1; // If we have an error if (err) { errorObject = err; } else if (r.result['$err']) { errorObject = r.result; } else if (r.result['errmsg']) { errorObject = r.result; } else { numberOfValidConnections = numberOfValidConnections + 1; } // We have authenticated all connections if (count === 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password)); // Return correct authentication callback(null, true); } else if (count === 0) { if (errorObject == null) errorObject = new MongoError(f('failed to authenticate using mongocr')); callback(errorObject, false); } } ); } ); }; var _execute = function(_connection) { process.nextTick(function() { executeMongoCR(_connection); }); }; _execute(connections.shift()); } }; /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ MongoCR.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db !== dbName; }); }; /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ MongoCR.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var count = authStore.length; if (count === 0) return callback(null, null); // Iterate over all the auth details stored for (var i = 0; i < authStore.length; i++) { this.auth( server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { count = count - 1; // Done re-authenticating if (count === 0) { callback(err, null); } } ); } }; /** * This is a result from a authentication strategy * * @callback authResultCallback * @param {error} error An error object. Set to null if no error present * @param {boolean} result The result of the authentication process */ module.exports = MongoCR; }).call(this,require('_process')) },{"../connection/commands":353,"../error":359,"_process":507,"crypto":287,"util":563}],348:[function(require,module,exports){ (function (process){ 'use strict'; var f = require('util').format, retrieveBSON = require('../connection/utils').retrieveBSON, Query = require('../connection/commands').Query, MongoError = require('../error').MongoError; var BSON = retrieveBSON(), Binary = BSON.Binary; var AuthSession = function(db, username, password) { this.db = db; this.username = username; this.password = password; }; AuthSession.prototype.equal = function(session) { return ( session.db === this.db && session.username === this.username && session.password === this.password ); }; /** * Creates a new Plain authentication mechanism * @class * @return {Plain} A cursor instance */ var Plain = function(bson) { this.bson = bson; this.authStore = []; }; /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ Plain.prototype.auth = function(server, connections, db, username, password, callback) { var self = this; // Total connections var count = connections.length; if (count === 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var errorObject = null; // For each connection we need to authenticate while (connections.length > 0) { // Execute MongoCR var execute = function(connection) { // Create payload var payload = new Binary(f('\x00%s\x00%s', username, password)); // Let's start the sasl process var command = { saslStart: 1, mechanism: 'PLAIN', payload: payload, autoAuthorize: 1 }; // Let's start the process server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { // Adjust count count = count - 1; // If we have an error if (err) { errorObject = err; } else if (r.result['$err']) { errorObject = r.result; } else if (r.result['errmsg']) { errorObject = r.result; } else { numberOfValidConnections = numberOfValidConnections + 1; } // We have authenticated all connections if (count === 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password)); // Return correct authentication callback(null, true); } else if (count === 0) { if (errorObject == null) errorObject = new MongoError(f('failed to authenticate using mongocr')); callback(errorObject, false); } } ); }; var _execute = function(_connection) { process.nextTick(function() { execute(_connection); }); }; _execute(connections.shift()); } }; // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for (var i = 0; i < authStore.length; i++) { if (authStore[i].equal(session)) { found = true; break; } } if (!found) authStore.push(session); }; /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ Plain.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db !== dbName; }); }; /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ Plain.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var count = authStore.length; if (count === 0) return callback(null, null); // Iterate over all the auth details stored for (var i = 0; i < authStore.length; i++) { this.auth( server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { count = count - 1; // Done re-authenticating if (count === 0) { callback(err, null); } } ); } }; /** * This is a result from a authentication strategy * * @callback authResultCallback * @param {error} error An error object. Set to null if no error present * @param {boolean} result The result of the authentication process */ module.exports = Plain; }).call(this,require('_process')) },{"../connection/commands":353,"../connection/utils":357,"../error":359,"_process":507,"util":563}],349:[function(require,module,exports){ (function (process,Buffer){ 'use strict'; var f = require('util').format, crypto = require('crypto'), retrieveBSON = require('../connection/utils').retrieveBSON, Query = require('../connection/commands').Query, MongoError = require('../error').MongoError; var BSON = retrieveBSON(), Binary = BSON.Binary; var AuthSession = function(db, username, password) { this.db = db; this.username = username; this.password = password; }; AuthSession.prototype.equal = function(session) { return ( session.db === this.db && session.username === this.username && session.password === this.password ); }; var id = 0; /** * Creates a new ScramSHA1 authentication mechanism * @class * @return {ScramSHA1} A cursor instance */ var ScramSHA1 = function(bson) { this.bson = bson; this.authStore = []; this.id = id++; }; var parsePayload = function(payload) { var dict = {}; var parts = payload.split(','); for (var i = 0; i < parts.length; i++) { var valueParts = parts[i].split('='); dict[valueParts[0]] = valueParts[1]; } return dict; }; var passwordDigest = function(username, password) { if (typeof username !== 'string') throw new MongoError('username must be a string'); if (typeof password !== 'string') throw new MongoError('password must be a string'); if (password.length === 0) throw new MongoError('password cannot be empty'); // Use node md5 generator var md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ':mongo:' + password, 'utf8'); return md5.digest('hex'); }; // XOR two buffers var xor = function(a, b) { if (!Buffer.isBuffer(a)) a = new Buffer(a); if (!Buffer.isBuffer(b)) b = new Buffer(b); var res = []; if (a.length > b.length) { for (var i = 0; i < b.length; i++) { res.push(a[i] ^ b[i]); } } else { for (i = 0; i < a.length; i++) { res.push(a[i] ^ b[i]); } } return new Buffer(res); }; var _hiCache = {}; var _hiCacheCount = 0; var _hiCachePurge = function() { _hiCache = {}; _hiCacheCount = 0; }; var hi = function(data, salt, iterations) { // omit the work if already generated var key = [data, salt.toString('base64'), iterations].join('_'); if (_hiCache[key] !== undefined) { return _hiCache[key]; } // generate the salt var saltedData = crypto.pbkdf2Sync(data, salt, iterations, 20, 'sha1'); // cache a copy to speed up the next lookup, but prevent unbounded cache growth if (_hiCacheCount >= 200) { _hiCachePurge(); } _hiCache[key] = saltedData; _hiCacheCount += 1; return saltedData; }; /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ ScramSHA1.prototype.auth = function(server, connections, db, username, password, callback) { var self = this; // Total connections var count = connections.length; if (count === 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var errorObject = null; // Execute MongoCR var executeScram = function(connection) { // Clean up the user username = username.replace('=', '=3D').replace(',', '=2C'); // Create a random nonce var nonce = crypto.randomBytes(24).toString('base64'); // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' var firstBare = f('n=%s,r=%s', username, nonce); // Build command structure var cmd = { saslStart: 1, mechanism: 'SCRAM-SHA-1', payload: new Binary(f('n,,%s', firstBare)), autoAuthorize: 1 }; // Handle the error var handleError = function(err, r) { if (err) { numberOfValidConnections = numberOfValidConnections - 1; errorObject = err; return false; } else if (r.result['$err']) { errorObject = r.result; return false; } else if (r.result['errmsg']) { errorObject = r.result; return false; } else { numberOfValidConnections = numberOfValidConnections + 1; } return true; }; // Finish up var finish = function(_count, _numberOfValidConnections) { if (_count === 0 && _numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password)); // Return correct authentication return callback(null, true); } else if (_count === 0) { if (errorObject == null) errorObject = new MongoError(f('failed to authenticate using scram')); return callback(errorObject, false); } }; var handleEnd = function(_err, _r) { // Handle any error handleError(_err, _r); // Adjust the number of connections count = count - 1; // Execute the finish finish(count, numberOfValidConnections); }; // Write the commmand on the connection server( connection, new Query(self.bson, f('%s.$cmd', db), cmd, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { // Do we have an error, handle it if (handleError(err, r) === false) { count = count - 1; if (count === 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password)); // Return correct authentication return callback(null, true); } else if (count === 0) { if (errorObject == null) errorObject = new MongoError(f('failed to authenticate using scram')); return callback(errorObject, false); } return; } // Get the dictionary var dict = parsePayload(r.result.payload.value()); // Unpack dictionary var iterations = parseInt(dict.i, 10); var salt = dict.s; var rnonce = dict.r; // Set up start of proof var withoutProof = f('c=biws,r=%s', rnonce); var passwordDig = passwordDigest(username, password); var saltedPassword = hi(passwordDig, new Buffer(salt, 'base64'), iterations); // Create the client key var hmac = crypto.createHmac('sha1', saltedPassword); hmac.update(new Buffer('Client Key')); var clientKey = new Buffer(hmac.digest('base64'), 'base64'); // Create the stored key var hash = crypto.createHash('sha1'); hash.update(clientKey); var storedKey = new Buffer(hash.digest('base64'), 'base64'); // Create the authentication message var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join( ',' ); // Create client signature hmac = crypto.createHmac('sha1', storedKey); hmac.update(new Buffer(authMsg)); var clientSig = new Buffer(hmac.digest('base64'), 'base64'); // Create client proof var clientProof = f('p=%s', new Buffer(xor(clientKey, clientSig)).toString('base64')); // Create client final var clientFinal = [withoutProof, clientProof].join(','); // // Create continue message var cmd = { saslContinue: 1, conversationId: r.result.conversationId, payload: new Binary(new Buffer(clientFinal)) }; // // Execute sasl continue // Write the commmand on the connection server( connection, new Query(self.bson, f('%s.$cmd', db), cmd, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (r && r.result.done === false) { var cmd = { saslContinue: 1, conversationId: r.result.conversationId, payload: new Buffer(0) }; // Write the commmand on the connection server( connection, new Query(self.bson, f('%s.$cmd', db), cmd, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { handleEnd(err, r); } ); } else { handleEnd(err, r); } } ); } ); }; var _execute = function(_connection) { process.nextTick(function() { executeScram(_connection); }); }; // For each connection we need to authenticate while (connections.length > 0) { _execute(connections.shift()); } }; // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for (var i = 0; i < authStore.length; i++) { if (authStore[i].equal(session)) { found = true; break; } } if (!found) authStore.push(session); }; /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ ScramSHA1.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db !== dbName; }); }; /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ ScramSHA1.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var count = authStore.length; // No connections if (count === 0) return callback(null, null); // Iterate over all the auth details stored for (var i = 0; i < authStore.length; i++) { this.auth( server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { count = count - 1; // Done re-authenticating if (count === 0) { callback(err, null); } } ); } }; module.exports = ScramSHA1; }).call(this,require('_process'),require("buffer").Buffer) },{"../connection/commands":353,"../connection/utils":357,"../error":359,"_process":507,"buffer":144,"crypto":287,"util":563}],350:[function(require,module,exports){ (function (process){ 'use strict'; var f = require('util').format, require_optional = require('require_optional'), Query = require('../connection/commands').Query, MongoError = require('../error').MongoError; var AuthSession = function(db, username, password, options) { this.db = db; this.username = username; this.password = password; this.options = options; }; AuthSession.prototype.equal = function(session) { return ( session.db === this.db && session.username === this.username && session.password === this.password ); }; // Kerberos class var Kerberos = null; var MongoAuthProcess = null; // Try to grab the Kerberos class try { Kerberos = require_optional('kerberos').Kerberos; // Authentication process for Mongo MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess; } catch (err) {} // eslint-disable-line /** * Creates a new SSPI authentication mechanism * @class * @return {SSPI} A cursor instance */ var SSPI = function(bson) { this.bson = bson; this.authStore = []; }; /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ SSPI.prototype.auth = function(server, connections, db, username, password, options, callback) { var self = this; // We don't have the Kerberos library if (Kerberos == null) return callback(new Error('Kerberos library is not installed')); var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; // Total connections var count = connections.length; if (count === 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var errorObject = null; // For each connection we need to authenticate while (connections.length > 0) { // Execute MongoCR var execute = function(connection) { // Start Auth process for a connection SSIPAuthenticate( self, username, password, gssapiServiceName, server, connection, options, function(err, r) { // Adjust count count = count - 1; // If we have an error if (err) { errorObject = err; } else if (r && typeof r === 'object' && r.result['$err']) { errorObject = r.result; } else if (r && typeof r === 'object' && r.result['errmsg']) { errorObject = r.result; } else { numberOfValidConnections = numberOfValidConnections + 1; } // We have authenticated all connections if (count === 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password, options)); // Return correct authentication callback(null, true); } else if (count === 0) { if (errorObject == null) errorObject = new MongoError(f('failed to authenticate using mongocr')); callback(errorObject, false); } } ); }; var _execute = function(_connection) { process.nextTick(function() { execute(_connection); }); }; _execute(connections.shift()); } }; var SSIPAuthenticate = function( self, username, password, gssapiServiceName, server, connection, options, callback ) { // Build Authentication command to send to MongoDB var command = { saslStart: 1, mechanism: 'GSSAPI', payload: '', autoAuthorize: 1 }; // Create authenticator var mongo_auth_process = new MongoAuthProcess( connection.host, connection.port, gssapiServiceName, options ); // Execute first sasl step server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (err) return callback(err, false); var doc = r.result; mongo_auth_process.init(username, password, function(err) { if (err) return callback(err); mongo_auth_process.transition(doc.payload, function(err, payload) { if (err) return callback(err); // Perform the next step against mongod var command = { saslContinue: 1, conversationId: doc.conversationId, payload: payload }; // Execute the command server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (err) return callback(err, false); var doc = r.result; mongo_auth_process.transition(doc.payload, function(err, payload) { if (err) return callback(err); // Perform the next step against mongod var command = { saslContinue: 1, conversationId: doc.conversationId, payload: payload }; // Execute the command server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (err) return callback(err, false); var doc = r.result; mongo_auth_process.transition(doc.payload, function(err, payload) { // Perform the next step against mongod var command = { saslContinue: 1, conversationId: doc.conversationId, payload: payload }; // Execute the command server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { if (err) return callback(err, false); var doc = r.result; if (doc.done) return callback(null, true); callback(new Error('Authentication failed'), false); } ); }); } ); }); } ); }); }); } ); }; // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for (var i = 0; i < authStore.length; i++) { if (authStore[i].equal(session)) { found = true; break; } } if (!found) authStore.push(session); }; /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ SSPI.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db !== dbName; }); }; /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ SSPI.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var count = authStore.length; if (count === 0) return callback(null, null); // Iterate over all the auth details stored for (var i = 0; i < authStore.length; i++) { this.auth( server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err) { count = count - 1; // Done re-authenticating if (count === 0) { callback(err, null); } } ); } }; /** * This is a result from a authentication strategy * * @callback authResultCallback * @param {error} error An error object. Set to null if no error present * @param {boolean} result The result of the authentication process */ module.exports = SSPI; }).call(this,require('_process')) },{"../connection/commands":353,"../error":359,"_process":507,"require_optional":534,"util":563}],351:[function(require,module,exports){ (function (process){ 'use strict'; var f = require('util').format, Query = require('../connection/commands').Query, MongoError = require('../error').MongoError; var AuthSession = function(db, username, password) { this.db = db; this.username = username; this.password = password; }; AuthSession.prototype.equal = function(session) { return ( session.db === this.db && session.username === this.username && session.password === this.password ); }; /** * Creates a new X509 authentication mechanism * @class * @return {X509} A cursor instance */ var X509 = function(bson) { this.bson = bson; this.authStore = []; }; /** * Authenticate * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {string} db Name of the database * @param {string} username Username * @param {string} password Password * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ X509.prototype.auth = function(server, connections, db, username, password, callback) { var self = this; // Total connections var count = connections.length; if (count === 0) return callback(null, null); // Valid connections var numberOfValidConnections = 0; var errorObject = null; // For each connection we need to authenticate while (connections.length > 0) { // Execute MongoCR var execute = function(connection) { // Let's start the sasl process var command = { authenticate: 1, mechanism: 'MONGODB-X509' }; // Add username if specified if (username) { command.user = username; } // Let's start the process server( connection, new Query(self.bson, '$external.$cmd', command, { numberToSkip: 0, numberToReturn: 1 }), function(err, r) { // Adjust count count = count - 1; // If we have an error if (err) { errorObject = err; } else if (r.result['$err']) { errorObject = r.result; } else if (r.result['errmsg']) { errorObject = r.result; } else { numberOfValidConnections = numberOfValidConnections + 1; } // We have authenticated all connections if (count === 0 && numberOfValidConnections > 0) { // Store the auth details addAuthSession(self.authStore, new AuthSession(db, username, password)); // Return correct authentication callback(null, true); } else if (count === 0) { if (errorObject == null) errorObject = new MongoError(f('failed to authenticate using mongocr')); callback(errorObject, false); } } ); }; var _execute = function(_connection) { process.nextTick(function() { execute(_connection); }); }; _execute(connections.shift()); } }; // Add to store only if it does not exist var addAuthSession = function(authStore, session) { var found = false; for (var i = 0; i < authStore.length; i++) { if (authStore[i].equal(session)) { found = true; break; } } if (!found) authStore.push(session); }; /** * Remove authStore credentials * @method * @param {string} db Name of database we are removing authStore details about * @return {object} */ X509.prototype.logout = function(dbName) { this.authStore = this.authStore.filter(function(x) { return x.db !== dbName; }); }; /** * Re authenticate pool * @method * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on * @param {[]Connections} connections Connections to authenticate using this authenticator * @param {authResultCallback} callback The callback to return the result from the authentication * @return {object} */ X509.prototype.reauthenticate = function(server, connections, callback) { var authStore = this.authStore.slice(0); var count = authStore.length; if (count === 0) return callback(null, null); // Iterate over all the auth details stored for (var i = 0; i < authStore.length; i++) { this.auth( server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) { count = count - 1; // Done re-authenticating if (count === 0) { callback(err, null); } } ); } }; /** * This is a result from a authentication strategy * * @callback authResultCallback * @param {error} error An error object. Set to null if no error present * @param {boolean} result The result of the authentication process */ module.exports = X509; }).call(this,require('_process')) },{"../connection/commands":353,"../error":359,"_process":507,"util":563}],352:[function(require,module,exports){ 'use strict'; /** * Creates a new CommandResult instance * @class * @param {object} result CommandResult object * @param {Connection} connection A connection instance associated with this result * @return {CommandResult} A cursor instance */ var CommandResult = function(result, connection, message) { this.result = result; this.connection = connection; this.message = message; }; /** * Convert CommandResult to JSON * @method * @return {object} */ CommandResult.prototype.toJSON = function() { return this.result; }; /** * Convert CommandResult to String representation * @method * @return {string} */ CommandResult.prototype.toString = function() { return JSON.stringify(this.toJSON()); }; module.exports = CommandResult; },{}],353:[function(require,module,exports){ (function (Buffer){ 'use strict'; var retrieveBSON = require('./utils').retrieveBSON; var BSON = retrieveBSON(); var Long = BSON.Long; // Incrementing request id var _requestId = 0; // Wire command operation ids var opcodes = require('../wireprotocol/shared').opcodes; // Query flags var OPTS_TAILABLE_CURSOR = 2; var OPTS_SLAVE = 4; var OPTS_OPLOG_REPLAY = 8; var OPTS_NO_CURSOR_TIMEOUT = 16; var OPTS_AWAIT_DATA = 32; var OPTS_EXHAUST = 64; var OPTS_PARTIAL = 128; // Response flags var CURSOR_NOT_FOUND = 0; var QUERY_FAILURE = 2; var SHARD_CONFIG_STALE = 4; var AWAIT_CAPABLE = 8; /************************************************************** * QUERY **************************************************************/ var Query = function(bson, ns, query, options) { var self = this; // Basic options needed to be passed in if (ns == null) throw new Error('ns must be specified for query'); if (query == null) throw new Error('query must be specified for query'); // Validate that we are not passing 0x00 in the collection name if (ns.indexOf('\x00') !== -1) { throw new Error('namespace cannot contain a null character'); } // Basic options this.bson = bson; this.ns = ns; this.query = query; // Ensure empty options this.options = options || {}; // Additional options this.numberToSkip = options.numberToSkip || 0; this.numberToReturn = options.numberToReturn || 0; this.returnFieldSelector = options.returnFieldSelector || null; this.requestId = Query.getRequestId(); // Serialization option this.serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; this.ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; this.batchSize = self.numberToReturn; // Flags this.tailable = false; this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; this.oplogReplay = false; this.noCursorTimeout = false; this.awaitData = false; this.exhaust = false; this.partial = false; }; // // Assign a new request Id Query.prototype.incRequestId = function() { this.requestId = _requestId++; }; // // Assign a new request Id Query.nextRequestId = function() { return _requestId + 1; }; // // Uses a single allocated buffer for the process, avoiding multiple memory allocations Query.prototype.toBin = function() { var self = this; var buffers = []; var projection = null; // Set up the flags var flags = 0; if (this.tailable) { flags |= OPTS_TAILABLE_CURSOR; } if (this.slaveOk) { flags |= OPTS_SLAVE; } if (this.oplogReplay) { flags |= OPTS_OPLOG_REPLAY; } if (this.noCursorTimeout) { flags |= OPTS_NO_CURSOR_TIMEOUT; } if (this.awaitData) { flags |= OPTS_AWAIT_DATA; } if (this.exhaust) { flags |= OPTS_EXHAUST; } if (this.partial) { flags |= OPTS_PARTIAL; } // If batchSize is different to self.numberToReturn if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; // Allocate write protocol header buffer var header = new Buffer( 4 * 4 + // Header 4 + // Flags Buffer.byteLength(self.ns) + 1 + // namespace 4 + // numberToSkip 4 // numberToReturn ); // Add header to buffers buffers.push(header); // Serialize the query var query = self.bson.serialize(this.query, { checkKeys: this.checkKeys, serializeFunctions: this.serializeFunctions, ignoreUndefined: this.ignoreUndefined }); // Add query document buffers.push(query); if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { // Serialize the projection document projection = self.bson.serialize(this.returnFieldSelector, { checkKeys: this.checkKeys, serializeFunctions: this.serializeFunctions, ignoreUndefined: this.ignoreUndefined }); // Add projection document buffers.push(projection); } // Total message size var totalLength = header.length + query.length + (projection ? projection.length : 0); // Set up the index var index = 4; // Write total document length header[3] = (totalLength >> 24) & 0xff; header[2] = (totalLength >> 16) & 0xff; header[1] = (totalLength >> 8) & 0xff; header[0] = totalLength & 0xff; // Write header information requestId header[index + 3] = (this.requestId >> 24) & 0xff; header[index + 2] = (this.requestId >> 16) & 0xff; header[index + 1] = (this.requestId >> 8) & 0xff; header[index] = this.requestId & 0xff; index = index + 4; // Write header information responseTo header[index + 3] = (0 >> 24) & 0xff; header[index + 2] = (0 >> 16) & 0xff; header[index + 1] = (0 >> 8) & 0xff; header[index] = 0 & 0xff; index = index + 4; // Write header information OP_QUERY header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; header[index] = opcodes.OP_QUERY & 0xff; index = index + 4; // Write header information flags header[index + 3] = (flags >> 24) & 0xff; header[index + 2] = (flags >> 16) & 0xff; header[index + 1] = (flags >> 8) & 0xff; header[index] = flags & 0xff; index = index + 4; // Write collection name index = index + header.write(this.ns, index, 'utf8') + 1; header[index - 1] = 0; // Write header information flags numberToSkip header[index + 3] = (this.numberToSkip >> 24) & 0xff; header[index + 2] = (this.numberToSkip >> 16) & 0xff; header[index + 1] = (this.numberToSkip >> 8) & 0xff; header[index] = this.numberToSkip & 0xff; index = index + 4; // Write header information flags numberToReturn header[index + 3] = (this.numberToReturn >> 24) & 0xff; header[index + 2] = (this.numberToReturn >> 16) & 0xff; header[index + 1] = (this.numberToReturn >> 8) & 0xff; header[index] = this.numberToReturn & 0xff; index = index + 4; // Return the buffers return buffers; }; Query.getRequestId = function() { return ++_requestId; }; /************************************************************** * GETMORE **************************************************************/ var GetMore = function(bson, ns, cursorId, opts) { opts = opts || {}; this.numberToReturn = opts.numberToReturn || 0; this.requestId = _requestId++; this.bson = bson; this.ns = ns; this.cursorId = cursorId; }; // // Uses a single allocated buffer for the process, avoiding multiple memory allocations GetMore.prototype.toBin = function() { var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; // Create command buffer var index = 0; // Allocate buffer var _buffer = new Buffer(length); // Write header information // index = write32bit(index, _buffer, length); _buffer[index + 3] = (length >> 24) & 0xff; _buffer[index + 2] = (length >> 16) & 0xff; _buffer[index + 1] = (length >> 8) & 0xff; _buffer[index] = length & 0xff; index = index + 4; // index = write32bit(index, _buffer, requestId); _buffer[index + 3] = (this.requestId >> 24) & 0xff; _buffer[index + 2] = (this.requestId >> 16) & 0xff; _buffer[index + 1] = (this.requestId >> 8) & 0xff; _buffer[index] = this.requestId & 0xff; index = index + 4; // index = write32bit(index, _buffer, 0); _buffer[index + 3] = (0 >> 24) & 0xff; _buffer[index + 2] = (0 >> 16) & 0xff; _buffer[index + 1] = (0 >> 8) & 0xff; _buffer[index] = 0 & 0xff; index = index + 4; // index = write32bit(index, _buffer, OP_GETMORE); _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; _buffer[index] = opcodes.OP_GETMORE & 0xff; index = index + 4; // index = write32bit(index, _buffer, 0); _buffer[index + 3] = (0 >> 24) & 0xff; _buffer[index + 2] = (0 >> 16) & 0xff; _buffer[index + 1] = (0 >> 8) & 0xff; _buffer[index] = 0 & 0xff; index = index + 4; // Write collection name index = index + _buffer.write(this.ns, index, 'utf8') + 1; _buffer[index - 1] = 0; // Write batch size // index = write32bit(index, _buffer, numberToReturn); _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; _buffer[index] = this.numberToReturn & 0xff; index = index + 4; // Write cursor id // index = write32bit(index, _buffer, cursorId.getLowBits()); _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; _buffer[index] = this.cursorId.getLowBits() & 0xff; index = index + 4; // index = write32bit(index, _buffer, cursorId.getHighBits()); _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; _buffer[index] = this.cursorId.getHighBits() & 0xff; index = index + 4; // Return buffer return _buffer; }; /************************************************************** * KILLCURSOR **************************************************************/ var KillCursor = function(bson, cursorIds) { this.requestId = _requestId++; this.cursorIds = cursorIds; }; // // Uses a single allocated buffer for the process, avoiding multiple memory allocations KillCursor.prototype.toBin = function() { var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; // Create command buffer var index = 0; var _buffer = new Buffer(length); // Write header information // index = write32bit(index, _buffer, length); _buffer[index + 3] = (length >> 24) & 0xff; _buffer[index + 2] = (length >> 16) & 0xff; _buffer[index + 1] = (length >> 8) & 0xff; _buffer[index] = length & 0xff; index = index + 4; // index = write32bit(index, _buffer, requestId); _buffer[index + 3] = (this.requestId >> 24) & 0xff; _buffer[index + 2] = (this.requestId >> 16) & 0xff; _buffer[index + 1] = (this.requestId >> 8) & 0xff; _buffer[index] = this.requestId & 0xff; index = index + 4; // index = write32bit(index, _buffer, 0); _buffer[index + 3] = (0 >> 24) & 0xff; _buffer[index + 2] = (0 >> 16) & 0xff; _buffer[index + 1] = (0 >> 8) & 0xff; _buffer[index] = 0 & 0xff; index = index + 4; // index = write32bit(index, _buffer, OP_KILL_CURSORS); _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; index = index + 4; // index = write32bit(index, _buffer, 0); _buffer[index + 3] = (0 >> 24) & 0xff; _buffer[index + 2] = (0 >> 16) & 0xff; _buffer[index + 1] = (0 >> 8) & 0xff; _buffer[index] = 0 & 0xff; index = index + 4; // Write batch size // index = write32bit(index, _buffer, this.cursorIds.length); _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; _buffer[index] = this.cursorIds.length & 0xff; index = index + 4; // Write all the cursor ids into the array for (var i = 0; i < this.cursorIds.length; i++) { // Write cursor id // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; index = index + 4; // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; index = index + 4; } // Return buffer return _buffer; }; var Response = function(bson, message, msgHeader, msgBody, opts) { opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; this.parsed = false; this.raw = message; this.data = msgBody; this.bson = bson; this.opts = opts; // Read the message header this.length = msgHeader.length; this.requestId = msgHeader.requestId; this.responseTo = msgHeader.responseTo; this.opCode = msgHeader.opCode; this.fromCompressed = msgHeader.fromCompressed; // Read the message body this.responseFlags = msgBody.readInt32LE(0); this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); this.startingFrom = msgBody.readInt32LE(12); this.numberReturned = msgBody.readInt32LE(16); // Preallocate document array this.documents = new Array(this.numberReturned); // Flag values this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; }; Response.prototype.isParsed = function() { return this.parsed; }; Response.prototype.parse = function(options) { // Don't parse again if not needed if (this.parsed) return; options = options || {}; // Allow the return of raw documents instead of parsing var raw = options.raw || false; var documentsReturnedIn = options.documentsReturnedIn || null; var promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; var promoteValues = typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; var promoteBuffers = typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; var bsonSize, _options; // Set up the options _options = { promoteLongs: promoteLongs, promoteValues: promoteValues, promoteBuffers: promoteBuffers }; // Position within OP_REPLY at which documents start // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) this.index = 20; // // Single document and documentsReturnedIn set // if (this.numberReturned === 1 && documentsReturnedIn != null && raw) { // Calculate the bson size bsonSize = this.data[this.index] | (this.data[this.index + 1] << 8) | (this.data[this.index + 2] << 16) | (this.data[this.index + 3] << 24); // Slice out the buffer containing the command result document var document = this.data.slice(this.index, this.index + bsonSize); // Set up field we wish to keep as raw var fieldsAsRaw = {}; fieldsAsRaw[documentsReturnedIn] = true; _options.fieldsAsRaw = fieldsAsRaw; // Deserialize but keep the array of documents in non-parsed form var doc = this.bson.deserialize(document, _options); // Get the documents this.documents = doc.cursor[documentsReturnedIn]; this.numberReturned = this.documents.length; // Ensure we have a Long valie cursor id this.cursorId = typeof doc.cursor.id === 'number' ? Long.fromNumber(doc.cursor.id) : doc.cursor.id; // Adjust the index this.index = this.index + bsonSize; // Set as parsed this.parsed = true; return; } // // Parse Body // for (var i = 0; i < this.numberReturned; i++) { bsonSize = this.data[this.index] | (this.data[this.index + 1] << 8) | (this.data[this.index + 2] << 16) | (this.data[this.index + 3] << 24); // If we have raw results specified slice the return document if (raw) { this.documents[i] = this.data.slice(this.index, this.index + bsonSize); } else { this.documents[i] = this.bson.deserialize( this.data.slice(this.index, this.index + bsonSize), _options ); } // Adjust the index this.index = this.index + bsonSize; } // Set parsed this.parsed = true; }; module.exports = { Query: Query, GetMore: GetMore, Response: Response, KillCursor: KillCursor }; }).call(this,require("buffer").Buffer) },{"../wireprotocol/shared":372,"./utils":357,"buffer":144}],354:[function(require,module,exports){ (function (Buffer){ 'use strict'; var inherits = require('util').inherits, EventEmitter = require('events').EventEmitter, net = require('net'), tls = require('tls'), crypto = require('crypto'), f = require('util').format, debugOptions = require('./utils').debugOptions, parseHeader = require('../wireprotocol/shared').parseHeader, decompress = require('../wireprotocol/compression').decompress, Response = require('./commands').Response, MongoNetworkError = require('../error').MongoNetworkError, Logger = require('./logger'), OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED, MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; var _id = 0; var debugFields = [ 'host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'crl', 'cert', 'rejectUnauthorized', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'checkServerIdentity' ]; var connectionAccountingSpy = undefined; var connectionAccounting = false; var connections = {}; /** * Creates a new Connection instance * @class * @param {string} options.host The server host * @param {number} options.port The server port * @param {number} [options.family=null] IP version for DNS lookup, passed down to Node's [`dns.lookup()` function](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). If set to `6`, will only look for ipv6 addresses. * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed * @param {boolean} [options.ssl=false] Use SSL for connection * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {Buffer} [options.ca] SSL Certificate store binary buffer * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer * @param {Buffer} [options.cert] SSL Certificate binary buffer * @param {Buffer} [options.key] SSL Key file binary buffer * @param {string} [options.passphrase] SSL Certificate pass phrase * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @fires Connection#connect * @fires Connection#close * @fires Connection#error * @fires Connection#timeout * @fires Connection#parseError * @return {Connection} A cursor instance */ var Connection = function(messageHandler, options) { // Add event listener EventEmitter.call(this); // Set empty if no options passed this.options = options || {}; // Identification information this.id = _id++; // Logger instance this.logger = Logger('Connection', options); // No bson parser passed in if (!options.bson) throw new Error('must pass in valid bson parser'); // Get bson parser this.bson = options.bson; // Grouping tag used for debugging purposes this.tag = options.tag; // Message handler this.messageHandler = messageHandler; // Max BSON message size this.maxBsonMessageSize = options.maxBsonMessageSize || 1024 * 1024 * 16 * 4; // Debug information if (this.logger.isDebug()) this.logger.debug( f( 'creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)) ) ); // Default options this.port = options.port || 27017; this.host = options.host || 'localhost'; this.family = typeof options.family === 'number' ? options.family : void 0; this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; this.keepAliveInitialDelay = typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; this.noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; this.connectionTimeout = typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; // Is the keepAliveInitialDelay > socketTimeout set it to half of socketTimeout if (this.keepAliveInitialDelay > this.socketTimeout) { this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); } // If connection was destroyed this.destroyed = false; // Check if we have a domain socket this.domainSocket = this.host.indexOf('/') !== -1; // Serialize commands using function this.singleBufferSerializtion = typeof options.singleBufferSerializtion === 'boolean' ? options.singleBufferSerializtion : true; this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; // SSL options this.ca = options.ca || null; this.crl = options.crl || null; this.cert = options.cert || null; this.key = options.key || null; this.passphrase = options.passphrase || null; this.ciphers = options.ciphers || null; this.ecdhCurve = options.ecdhCurve || null; this.ssl = typeof options.ssl === 'boolean' ? options.ssl : false; this.rejectUnauthorized = typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; this.checkServerIdentity = typeof options.checkServerIdentity === 'boolean' || typeof options.checkServerIdentity === 'function' ? options.checkServerIdentity : true; // If ssl not enabled if (!this.ssl) this.rejectUnauthorized = false; // Response options this.responseOptions = { promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false }; // Flushing this.flushing = false; this.queue = []; // Internal state this.connection = null; this.writeStream = null; // Create hash method var hash = crypto.createHash('sha1'); hash.update(f('%s:%s', this.host, this.port)); // Create a hash name this.hashedName = hash.digest('hex'); // All operations in flight on the connection this.workItems = []; }; inherits(Connection, EventEmitter); Connection.prototype.setSocketTimeout = function(value) { if (this.connection) { this.connection.setTimeout(value); } }; Connection.prototype.resetSocketTimeout = function() { if (this.connection) { this.connection.setTimeout(this.socketTimeout); } }; Connection.enableConnectionAccounting = function(spy) { if (spy) { connectionAccountingSpy = spy; } connectionAccounting = true; connections = {}; }; Connection.disableConnectionAccounting = function() { connectionAccounting = false; connectionAccountingSpy = undefined; }; Connection.connections = function() { return connections; }; function deleteConnection(id) { // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) delete connections[id]; if (connectionAccountingSpy) { connectionAccountingSpy.deleteConnection(id); } } function addConnection(id, connection) { // console.log("=== added connection " + id + " :: " + connection.port) connections[id] = connection; if (connectionAccountingSpy) { connectionAccountingSpy.addConnection(id, connection); } } // // Connection handlers var errorHandler = function(self) { return function(err) { if (connectionAccounting) deleteConnection(self.id); // Debug information if (self.logger.isDebug()) self.logger.debug( f( 'connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err) ) ); // Emit the error if (self.listeners('error').length > 0) self.emit('error', new MongoNetworkError(err), self); }; }; var timeoutHandler = function(self) { return function() { if (connectionAccounting) deleteConnection(self.id); // Debug information if (self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); // Emit timeout error self.emit( 'timeout', new MongoNetworkError(f('connection %s to %s:%s timed out', self.id, self.host, self.port)), self ); }; }; var closeHandler = function(self) { return function(hadError) { if (connectionAccounting) deleteConnection(self.id); // Debug information if (self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); // Emit close event if (!hadError) { self.emit( 'close', new MongoNetworkError(f('connection %s to %s:%s closed', self.id, self.host, self.port)), self ); } }; }; // Handle a message once it is recieved var emitMessageHandler = function(self, message) { var msgHeader = parseHeader(message); if (msgHeader.opCode === OP_COMPRESSED) { msgHeader.fromCompressed = true; var index = MESSAGE_HEADER_SIZE; msgHeader.opCode = message.readInt32LE(index); index += 4; msgHeader.length = message.readInt32LE(index); index += 4; var compressorID = message[index]; index++; decompress(compressorID, message.slice(index), function(err, decompressedMsgBody) { if (err) { throw err; } if (decompressedMsgBody.length !== msgHeader.length) { throw new Error( 'Decompressing a compressed message from the server failed. The message is corrupt.' ); } self.messageHandler( new Response(self.bson, message, msgHeader, decompressedMsgBody, self.responseOptions), self ); }); } else { self.messageHandler( new Response( self.bson, message, msgHeader, message.slice(MESSAGE_HEADER_SIZE), self.responseOptions ), self ); } }; var dataHandler = function(self) { return function(data) { // Parse until we are done with the data while (data.length > 0) { // If we still have bytes to read on the current message if (self.bytesRead > 0 && self.sizeOfMessage > 0) { // Calculate the amount of remaining bytes var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; // Check if the current chunk contains the rest of the message if (remainingBytesToRead > data.length) { // Copy the new data into the exiting buffer (should have been allocated when we know the message size) data.copy(self.buffer, self.bytesRead); // Adjust the number of bytes read so it point to the correct index in the buffer self.bytesRead = self.bytesRead + data.length; // Reset state of buffer data = new Buffer(0); } else { // Copy the missing part of the data into our current buffer data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); // Slice the overflow into a new buffer that we will then re-parse data = data.slice(remainingBytesToRead); // Emit current complete message try { var emitBuffer = self.buffer; // Reset state of buffer self.buffer = null; self.sizeOfMessage = 0; self.bytesRead = 0; self.stubBuffer = null; emitMessageHandler(self, emitBuffer); } catch (err) { var errorObject = { err: 'socketHandler', trace: err, bin: self.buffer, parseState: { sizeOfMessage: self.sizeOfMessage, bytesRead: self.bytesRead, stubBuffer: self.stubBuffer } }; // We got a parse Error fire it off then keep going self.emit('parseError', errorObject, self); } } } else { // Stub buffer is kept in case we don't get enough bytes to determine the // size of the message (< 4 bytes) if (self.stubBuffer != null && self.stubBuffer.length > 0) { // If we have enough bytes to determine the message size let's do it if (self.stubBuffer.length + data.length > 4) { // Prepad the data var newData = new Buffer(self.stubBuffer.length + data.length); self.stubBuffer.copy(newData, 0); data.copy(newData, self.stubBuffer.length); // Reassign for parsing data = newData; // Reset state of buffer self.buffer = null; self.sizeOfMessage = 0; self.bytesRead = 0; self.stubBuffer = null; } else { // Add the the bytes to the stub buffer var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); // Copy existing stub buffer self.stubBuffer.copy(newStubBuffer, 0); // Copy missing part of the data data.copy(newStubBuffer, self.stubBuffer.length); // Exit parsing loop data = new Buffer(0); } } else { if (data.length > 4) { // Retrieve the message size // var sizeOfMessage = data.readUInt32LE(0); var sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); // If we have a negative sizeOfMessage emit error and return if (sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { errorObject = { err: 'socketHandler', trace: '', bin: self.buffer, parseState: { sizeOfMessage: sizeOfMessage, bytesRead: self.bytesRead, stubBuffer: self.stubBuffer } }; // We got a parse Error fire it off then keep going self.emit('parseError', errorObject, self); return; } // Ensure that the size of message is larger than 0 and less than the max allowed if ( sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length ) { self.buffer = new Buffer(sizeOfMessage); // Copy all the data into the buffer data.copy(self.buffer, 0); // Update bytes read self.bytesRead = data.length; // Update sizeOfMessage self.sizeOfMessage = sizeOfMessage; // Ensure stub buffer is null self.stubBuffer = null; // Exit parsing loop data = new Buffer(0); } else if ( sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage === data.length ) { try { emitBuffer = data; // Reset state of buffer self.buffer = null; self.sizeOfMessage = 0; self.bytesRead = 0; self.stubBuffer = null; // Exit parsing loop data = new Buffer(0); // Emit the message emitMessageHandler(self, emitBuffer); } catch (err) { self.emit('parseError', err, self); } } else if (sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { errorObject = { err: 'socketHandler', trace: null, bin: data, parseState: { sizeOfMessage: sizeOfMessage, bytesRead: 0, buffer: null, stubBuffer: null } }; // We got a parse Error fire it off then keep going self.emit('parseError', errorObject, self); // Clear out the state of the parser self.buffer = null; self.sizeOfMessage = 0; self.bytesRead = 0; self.stubBuffer = null; // Exit parsing loop data = new Buffer(0); } else { emitBuffer = data.slice(0, sizeOfMessage); // Reset state of buffer self.buffer = null; self.sizeOfMessage = 0; self.bytesRead = 0; self.stubBuffer = null; // Copy rest of message data = data.slice(sizeOfMessage); // Emit the message emitMessageHandler(self, emitBuffer); } } else { // Create a buffer that contains the space for the non-complete message self.stubBuffer = new Buffer(data.length); // Copy the data to the stub buffer data.copy(self.stubBuffer, 0); // Exit parsing loop data = new Buffer(0); } } } } }; }; // List of socket level valid ssl options var legalSslSocketOptions = [ 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', 'NPNProtocols', 'ALPNProtocols', 'servername', 'ecdhCurve', 'secureProtocol', 'secureContext', 'session', 'minDHSize' ]; function merge(options1, options2) { // Merge in any allowed ssl options for (var name in options2) { if (options2[name] != null && legalSslSocketOptions.indexOf(name) !== -1) { options1[name] = options2[name]; } } } function makeSSLConnection(self, _options) { let sslOptions = { socket: self.connection, rejectUnauthorized: self.rejectUnauthorized }; // Merge in options merge(sslOptions, self.options); merge(sslOptions, _options); // Set options for ssl if (self.ca) sslOptions.ca = self.ca; if (self.crl) sslOptions.crl = self.crl; if (self.cert) sslOptions.cert = self.cert; if (self.key) sslOptions.key = self.key; if (self.passphrase) sslOptions.passphrase = self.passphrase; // Override checkServerIdentity behavior if (self.checkServerIdentity === false) { // Skip the identiy check by retuning undefined as per node documents // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback sslOptions.checkServerIdentity = function() { return undefined; }; } else if (typeof self.checkServerIdentity === 'function') { sslOptions.checkServerIdentity = self.checkServerIdentity; } // Set default sni servername to be the same as host if (sslOptions.servername == null) { sslOptions.servername = self.host; } // Attempt SSL connection const connection = tls.connect(self.port, self.host, sslOptions, function() { // Error on auth or skip if (connection.authorizationError && self.rejectUnauthorized) { return self.emit('error', connection.authorizationError, self, { ssl: true }); } // Set socket timeout instead of connection timeout connection.setTimeout(self.socketTimeout); // We are done emit connect self.emit('connect', self); }); connection.setTimeout(self.connectionTimeout); return connection; } function makeUnsecureConnection(self, family) { // Create new connection instance let connection_options; if (self.domainSocket) { connection_options = { path: self.host }; } else { connection_options = { port: self.port, host: self.host }; connection_options.family = family; } const connection = net.createConnection(connection_options); // Set the options for the connection connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); connection.setTimeout(self.connectionTimeout); connection.setNoDelay(self.noDelay); connection.once('connect', function() { // Set socket timeout instead of connection timeout connection.setTimeout(self.socketTimeout); // Emit connect event self.emit('connect', self); }); return connection; } function doConnect(self, family, _options, _errorHandler) { self.connection = self.ssl ? makeSSLConnection(self, _options) : makeUnsecureConnection(self, family); // Add handlers for events self.connection.once('error', _errorHandler); self.connection.once('timeout', timeoutHandler(self)); self.connection.once('close', closeHandler(self)); self.connection.on('data', dataHandler(self)); } /** * Connect * @method */ Connection.prototype.connect = function(_options) { _options = _options || {}; // Set the connections if (connectionAccounting) addConnection(this.id, this); // Check if we are overriding the promoteLongs if (typeof _options.promoteLongs === 'boolean') { this.responseOptions.promoteLongs = _options.promoteLongs; this.responseOptions.promoteValues = _options.promoteValues; this.responseOptions.promoteBuffers = _options.promoteBuffers; } const _errorHandler = errorHandler(this); if (this.family !== void 0) { return doConnect(this, this.family, _options, _errorHandler); } return doConnect(this, 6, _options, err => { if (this.logger.isDebug()) { this.logger.debug( f( 'connection %s for [%s:%s] errored out with [%s]', this.id, this.host, this.port, JSON.stringify(err) ) ); } // clean up existing event handlers this.connection.removeAllListeners('error'); this.connection.removeAllListeners('timeout'); this.connection.removeAllListeners('close'); this.connection.removeAllListeners('data'); this.connection = undefined; return doConnect(this, 4, _options, _errorHandler); }); }; /** * Unref this connection * @method * @return {boolean} */ Connection.prototype.unref = function() { if (this.connection) this.connection.unref(); else { var self = this; this.once('connect', function() { self.connection.unref(); }); } }; /** * Destroy connection * @method */ Connection.prototype.destroy = function() { // Set the connections if (connectionAccounting) deleteConnection(this.id); if (this.connection) { // Catch posssible exception thrown by node 0.10.x try { this.connection.end(); } catch (err) {} // eslint-disable-line // Destroy connection this.connection.destroy(); } this.destroyed = true; }; /** * Write to connection * @method * @param {Command} command Command to write out need to implement toBin and toBinUnified */ Connection.prototype.write = function(buffer) { var i; // Debug Log if (this.logger.isDebug()) { if (!Array.isArray(buffer)) { this.logger.debug( f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port) ); } else { for (i = 0; i < buffer.length; i++) this.logger.debug( f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port) ); } } // Double check that the connection is not destroyed if (this.connection.destroyed === false) { // Write out the command if (!Array.isArray(buffer)) { this.connection.write(buffer, 'binary'); return true; } // Iterate over all buffers and write them in order to the socket for (i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); return true; } // Connection is destroyed return write failed return false; }; /** * Return id of connection as a string * @method * @return {string} */ Connection.prototype.toString = function() { return '' + this.id; }; /** * Return json object of connection * @method * @return {object} */ Connection.prototype.toJSON = function() { return { id: this.id, host: this.host, port: this.port }; }; /** * Is the connection connected * @method * @return {boolean} */ Connection.prototype.isConnected = function() { if (this.destroyed) return false; return !this.connection.destroyed && this.connection.writable; }; /** * A server connect event, used to verify that the connection is up and running * * @event Connection#connect * @type {Connection} */ /** * The server connection closed, all pool connections closed * * @event Connection#close * @type {Connection} */ /** * The server connection caused an error, all pool connections closed * * @event Connection#error * @type {Connection} */ /** * The server connection timed out, all pool connections closed * * @event Connection#timeout * @type {Connection} */ /** * The driver experienced an invalid message, all pool connections closed * * @event Connection#parseError * @type {Connection} */ module.exports = Connection; }).call(this,require("buffer").Buffer) },{"../error":359,"../wireprotocol/compression":371,"../wireprotocol/shared":372,"./commands":353,"./logger":355,"./utils":357,"buffer":144,"crypto":287,"events":316,"net":123,"tls":123,"util":563}],355:[function(require,module,exports){ (function (process){ 'use strict'; var f = require('util').format, MongoError = require('../error').MongoError; // Filters for classes var classFilters = {}; var filteredClasses = {}; var level = null; // Save the process id var pid = process.pid; // current logger var currentLogger = null; /** * Creates a new Logger instance * @class * @param {string} className The Class name associated with the logging instance * @param {object} [options=null] Optional settings. * @param {Function} [options.logger=null] Custom logger function; * @param {string} [options.loggerLevel=error] Override default global log level. * @return {Logger} a Logger instance. */ var Logger = function(className, options) { if (!(this instanceof Logger)) return new Logger(className, options); options = options || {}; // Current reference this.className = className; // Current logger if (options.logger) { currentLogger = options.logger; } else if (currentLogger == null) { currentLogger = console.log; } // Set level of logging, default is error if (options.loggerLevel) { level = options.loggerLevel || 'error'; } // Add all class names if (filteredClasses[this.className] == null) classFilters[this.className] = true; }; /** * Log a message at the debug level * @method * @param {string} message The message to log * @param {object} object additional meta data to log * @return {null} */ Logger.prototype.debug = function(message, object) { if ( this.isDebug() && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) ) { var dateTime = new Date().getTime(); var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); var state = { type: 'debug', message: message, className: this.className, pid: pid, date: dateTime }; if (object) state.meta = object; currentLogger(msg, state); } }; /** * Log a message at the warn level * @method * @param {string} message The message to log * @param {object} object additional meta data to log * @return {null} */ (Logger.prototype.warn = function(message, object) { if ( this.isWarn() && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) ) { var dateTime = new Date().getTime(); var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); var state = { type: 'warn', message: message, className: this.className, pid: pid, date: dateTime }; if (object) state.meta = object; currentLogger(msg, state); } }), /** * Log a message at the info level * @method * @param {string} message The message to log * @param {object} object additional meta data to log * @return {null} */ (Logger.prototype.info = function(message, object) { if ( this.isInfo() && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) ) { var dateTime = new Date().getTime(); var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); var state = { type: 'info', message: message, className: this.className, pid: pid, date: dateTime }; if (object) state.meta = object; currentLogger(msg, state); } }), /** * Log a message at the error level * @method * @param {string} message The message to log * @param {object} object additional meta data to log * @return {null} */ (Logger.prototype.error = function(message, object) { if ( this.isError() && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) ) { var dateTime = new Date().getTime(); var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); var state = { type: 'error', message: message, className: this.className, pid: pid, date: dateTime }; if (object) state.meta = object; currentLogger(msg, state); } }), /** * Is the logger set at info level * @method * @return {boolean} */ (Logger.prototype.isInfo = function() { return level === 'info' || level === 'debug'; }), /** * Is the logger set at error level * @method * @return {boolean} */ (Logger.prototype.isError = function() { return level === 'error' || level === 'info' || level === 'debug'; }), /** * Is the logger set at error level * @method * @return {boolean} */ (Logger.prototype.isWarn = function() { return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; }), /** * Is the logger set at debug level * @method * @return {boolean} */ (Logger.prototype.isDebug = function() { return level === 'debug'; }); /** * Resets the logger to default settings, error and no filtered classes * @method * @return {null} */ Logger.reset = function() { level = 'error'; filteredClasses = {}; }; /** * Get the current logger function * @method * @return {function} */ Logger.currentLogger = function() { return currentLogger; }; /** * Set the current logger function * @method * @param {function} logger Logger function. * @return {null} */ Logger.setCurrentLogger = function(logger) { if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); currentLogger = logger; }; /** * Set what classes to log. * @method * @param {string} type The type of filter (currently only class) * @param {string[]} values The filters to apply * @return {null} */ Logger.filter = function(type, values) { if (type === 'class' && Array.isArray(values)) { filteredClasses = {}; values.forEach(function(x) { filteredClasses[x] = true; }); } }; /** * Set the current log level * @method * @param {string} level Set current log level (debug, info, error) * @return {null} */ Logger.setLevel = function(_level) { if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { throw new Error(f('%s is an illegal logging level', _level)); } level = _level; }; module.exports = Logger; }).call(this,require('_process')) },{"../error":359,"_process":507,"util":563}],356:[function(require,module,exports){ (function (process,Buffer){ 'use strict'; var inherits = require('util').inherits, EventEmitter = require('events').EventEmitter, Connection = require('./connection'), MongoError = require('../error').MongoError, MongoNetworkError = require('../error').MongoNetworkError, Logger = require('./logger'), f = require('util').format, Query = require('./commands').Query, CommandResult = require('./command_result'), MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE, opcodes = require('../wireprotocol/shared').opcodes, compress = require('../wireprotocol/compression').compress, compressorIDs = require('../wireprotocol/compression').compressorIDs, uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands, resolveClusterTime = require('../topologies/shared').resolveClusterTime; var MongoCR = require('../auth/mongocr'), X509 = require('../auth/x509'), Plain = require('../auth/plain'), GSSAPI = require('../auth/gssapi'), SSPI = require('../auth/sspi'), ScramSHA1 = require('../auth/scram'); var DISCONNECTED = 'disconnected'; var CONNECTING = 'connecting'; var CONNECTED = 'connected'; var DESTROYING = 'destroying'; var DESTROYED = 'destroyed'; var _id = 0; function hasSessionSupport(topology) { if (topology == null) return false; return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; } /** * Creates a new Pool instance * @class * @param {string} options.host The server host * @param {number} options.port The server port * @param {number} [options.size=5] Max server connection pool size * @param {number} [options.minSize=0] Minimum server connection pool size * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket * @param {boolean} [options.ssl=false] Use SSL for connection * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {Buffer} [options.ca] SSL Certificate store binary buffer * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer * @param {Buffer} [options.cert] SSL Certificate binary buffer * @param {Buffer} [options.key] SSL Key file binary buffer * @param {string} [options.passPhrase] SSL Certificate pass phrase * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @fires Pool#connect * @fires Pool#close * @fires Pool#error * @fires Pool#timeout * @fires Pool#parseError * @return {Pool} A cursor instance */ var Pool = function(topology, options) { // Add event listener EventEmitter.call(this); // Store topology for later use this.topology = topology; // Add the options this.options = Object.assign( { // Host and port settings host: 'localhost', port: 27017, // Pool default max size size: 5, // Pool default min size minSize: 0, // socket settings connectionTimeout: 30000, socketTimeout: 360000, keepAlive: true, keepAliveInitialDelay: 300000, noDelay: true, // SSL Settings ssl: false, checkServerIdentity: true, ca: null, crl: null, cert: null, key: null, passPhrase: null, rejectUnauthorized: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, // Reconnection options reconnect: true, reconnectInterval: 1000, reconnectTries: 30, // Enable domains domainsEnabled: false }, options ); // Identification information this.id = _id++; // Current reconnect retries this.retriesLeft = this.options.reconnectTries; this.reconnectId = null; // No bson parser passed in if ( !options.bson || (options.bson && (typeof options.bson.serialize !== 'function' || typeof options.bson.deserialize !== 'function')) ) { throw new Error('must pass in valid bson parser'); } // Logger instance this.logger = Logger('Pool', options); // Pool state this.state = DISCONNECTED; // Connections this.availableConnections = []; this.inUseConnections = []; this.connectingConnections = []; // Currently executing this.executing = false; // Operation work queue this.queue = []; // All the authProviders this.authProviders = options.authProviders || { mongocr: new MongoCR(options.bson), x509: new X509(options.bson), plain: new Plain(options.bson), gssapi: new GSSAPI(options.bson), sspi: new SSPI(options.bson), 'scram-sha-1': new ScramSHA1(options.bson) }; // Contains the reconnect connection this.reconnectConnection = null; // Are we currently authenticating this.authenticating = false; this.loggingout = false; this.nonAuthenticatedConnections = []; this.authenticatingTimestamp = null; // Number of consecutive timeouts caught this.numberOfConsecutiveTimeouts = 0; // Current pool Index this.connectionIndex = 0; }; inherits(Pool, EventEmitter); Object.defineProperty(Pool.prototype, 'size', { enumerable: true, get: function() { return this.options.size; } }); Object.defineProperty(Pool.prototype, 'minSize', { enumerable: true, get: function() { return this.options.minSize; } }); Object.defineProperty(Pool.prototype, 'connectionTimeout', { enumerable: true, get: function() { return this.options.connectionTimeout; } }); Object.defineProperty(Pool.prototype, 'socketTimeout', { enumerable: true, get: function() { return this.options.socketTimeout; } }); function stateTransition(self, newState) { var legalTransitions = { disconnected: [CONNECTING, DESTROYING, DISCONNECTED], connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], connected: [CONNECTED, DISCONNECTED, DESTROYING], destroying: [DESTROYING, DESTROYED], destroyed: [DESTROYED] }; // Get current state var legalStates = legalTransitions[self.state]; if (legalStates && legalStates.indexOf(newState) !== -1) { self.state = newState; } else { self.logger.error( f( 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', self.id, self.state, newState, legalStates ) ); } } function authenticate(pool, auth, connection, cb) { if (auth[0] === undefined) return cb(null); // We need to authenticate the server var mechanism = auth[0]; var db = auth[1]; // Validate if the mechanism exists if (!pool.authProviders[mechanism]) { throw new MongoError(f('authMechanism %s not supported', mechanism)); } // Get the provider var provider = pool.authProviders[mechanism]; // Authenticate using the provided mechanism provider.auth.apply(provider, [write(pool), [connection], db].concat(auth.slice(2)).concat([cb])); } // The write function used by the authentication mechanism (bypasses external) function write(self) { return function(connection, command, callback) { // Get the raw buffer // Ensure we stop auth if pool was destroyed if (self.state === DESTROYED || self.state === DESTROYING) { return callback(new MongoError('pool destroyed')); } // Set the connection workItem callback connection.workItems.push({ cb: callback, command: true, requestId: command.requestId }); // Write the buffer out to the connection connection.write(command.toBin()); }; } function reauthenticate(pool, connection, cb) { // Authenticate function authenticateAgainstProvider(pool, connection, providers, cb) { // Finished re-authenticating against providers if (providers.length === 0) return cb(); // Get the provider name var provider = pool.authProviders[providers.pop()]; // Auth provider provider.reauthenticate(write(pool), [connection], function(err) { // We got an error return immediately if (err) return cb(err); // Continue authenticating the connection authenticateAgainstProvider(pool, connection, providers, cb); }); } // Start re-authenticating process authenticateAgainstProvider(pool, connection, Object.keys(pool.authProviders), cb); } function connectionFailureHandler(self, event) { return function(err) { if (this._connectionFailHandled) return; this._connectionFailHandled = true; // Destroy the connection this.destroy(); // Remove the connection removeConnection(self, this); // Flush all work Items on this connection while (this.workItems.length > 0) { var workItem = this.workItems.shift(); if (workItem.cb) workItem.cb(err); } // Did we catch a timeout, increment the numberOfConsecutiveTimeouts if (event === 'timeout') { self.numberOfConsecutiveTimeouts = self.numberOfConsecutiveTimeouts + 1; // Have we timed out more than reconnectTries in a row ? // Force close the pool as we are trying to connect to tcp sink hole if (self.numberOfConsecutiveTimeouts > self.options.reconnectTries) { self.numberOfConsecutiveTimeouts = 0; // Destroy all connections and pool self.destroy(true); // Emit close event return self.emit('close', self); } } // No more socket available propegate the event if (self.socketCount() === 0) { if (self.state !== DESTROYED && self.state !== DESTROYING) { stateTransition(self, DISCONNECTED); } // Do not emit error events, they are always close events // do not trigger the low level error handler in node event = event === 'error' ? 'close' : event; self.emit(event, err); } // Start reconnection attempts if (!self.reconnectId && self.options.reconnect) { self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); } // Do we need to do anything to maintain the minimum pool size const totalConnections = self.availableConnections.length + self.connectingConnections.length + self.inUseConnections.length; if (totalConnections < self.minSize) { _createConnection(self); } }; } function attemptReconnect(self) { return function() { self.emit('attemptReconnect', self); if (self.state === DESTROYED || self.state === DESTROYING) return; // We are connected do not try again if (self.isConnected()) { self.reconnectId = null; return; } // If we have failure schedule a retry function _connectionFailureHandler(self) { return function() { if (this._connectionFailHandled) return; this._connectionFailHandled = true; // Destroy the connection this.destroy(); // Count down the number of reconnects self.retriesLeft = self.retriesLeft - 1; // How many retries are left if (self.retriesLeft === 0) { // Destroy the instance self.destroy(); // Emit close event self.emit( 'reconnectFailed', new MongoNetworkError( f( 'failed to reconnect after %s attempts with interval %s ms', self.options.reconnectTries, self.options.reconnectInterval ) ) ); } else { self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); } }; } // Got a connect handler function _connectHandler(self) { return function() { // Assign var connection = this; // Pool destroyed stop the connection if (self.state === DESTROYED || self.state === DESTROYING) { return connection.destroy(); } // Clear out all handlers handlers.forEach(function(event) { connection.removeAllListeners(event); }); // Reset reconnect id self.reconnectId = null; // Apply pool connection handlers connection.on('error', connectionFailureHandler(self, 'error')); connection.on('close', connectionFailureHandler(self, 'close')); connection.on('timeout', connectionFailureHandler(self, 'timeout')); connection.on('parseError', connectionFailureHandler(self, 'parseError')); // Apply any auth to the connection reauthenticate(self, this, function() { // Reset retries self.retriesLeft = self.options.reconnectTries; // Push to available connections self.availableConnections.push(connection); // Set the reconnectConnection to null self.reconnectConnection = null; // Emit reconnect event self.emit('reconnect', self); // Trigger execute to start everything up again _execute(self)(); }); }; } // Create a connection self.reconnectConnection = new Connection(messageHandler(self), self.options); // Add handlers self.reconnectConnection.on('close', _connectionFailureHandler(self, 'close')); self.reconnectConnection.on('error', _connectionFailureHandler(self, 'error')); self.reconnectConnection.on('timeout', _connectionFailureHandler(self, 'timeout')); self.reconnectConnection.on('parseError', _connectionFailureHandler(self, 'parseError')); // On connection self.reconnectConnection.on('connect', _connectHandler(self)); // Attempt connection self.reconnectConnection.connect(); }; } function moveConnectionBetween(connection, from, to) { var index = from.indexOf(connection); // Move the connection from connecting to available if (index !== -1) { from.splice(index, 1); to.push(connection); } } function messageHandler(self) { return function(message, connection) { // workItem to execute var workItem = null; // Locate the workItem for (var i = 0; i < connection.workItems.length; i++) { if (connection.workItems[i].requestId === message.responseTo) { // Get the callback workItem = connection.workItems[i]; // Remove from list of workItems connection.workItems.splice(i, 1); } } // Reset timeout counter self.numberOfConsecutiveTimeouts = 0; // Reset the connection timeout if we modified it for // this operation if (workItem && workItem.socketTimeout) { connection.resetSocketTimeout(); } // Log if debug enabled if (self.logger.isDebug()) { self.logger.debug( f( 'message [%s] received from %s:%s', message.raw.toString('hex'), self.options.host, self.options.port ) ); } // Authenticate any straggler connections function authenticateStragglers(self, connection, callback) { // Get any non authenticated connections var connections = self.nonAuthenticatedConnections.slice(0); var nonAuthenticatedConnections = self.nonAuthenticatedConnections; self.nonAuthenticatedConnections = []; // Establish if the connection need to be authenticated // Add to authentication list if // 1. we were in an authentication process when the operation was executed // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened if ( connection.workItems.length === 1 && (connection.workItems[0].authenticating === true || (typeof connection.workItems[0].authenticatingTimestamp === 'number' && connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp)) ) { // Add connection to the list connections.push(connection); } // No connections need to be re-authenticated if (connections.length === 0) { // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Finish return callback(); } // Apply re-authentication to all connections before releasing back to pool var connectionCount = connections.length; // Authenticate all connections for (var i = 0; i < connectionCount; i++) { reauthenticate(self, connections[i], function() { connectionCount = connectionCount - 1; if (connectionCount === 0) { // Put non authenticated connections in available connections self.availableConnections = self.availableConnections.concat( nonAuthenticatedConnections ); // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Return callback(); } }); } } function handleOperationCallback(self, cb, err, result) { // No domain enabled if (!self.options.domainsEnabled) { return process.nextTick(function() { return cb(err, result); }); } // Domain enabled just call the callback cb(err, result); } authenticateStragglers(self, connection, function() { // Keep executing, ensure current message handler does not stop execution if (!self.executing) { process.nextTick(function() { _execute(self)(); }); } // Time to dispatch the message if we have a callback if (workItem && !workItem.immediateRelease) { try { // Parse the message according to the provided options message.parse(workItem); } catch (err) { return handleOperationCallback(self, workItem.cb, new MongoError(err)); } // Look for clusterTime, and operationTime and update them if necessary if (message.documents[0]) { if (message.documents[0].$clusterTime) { const $clusterTime = message.documents[0].$clusterTime; self.topology.clusterTime = $clusterTime; if (workItem.session != null) { resolveClusterTime(workItem.session, $clusterTime); } } if ( message.documents[0].operationTime && workItem.session && workItem.session.supports.causalConsistency ) { workItem.session.advanceOperationTime(message.documents[0].operationTime); } } // Establish if we have an error if ( workItem.command && message.documents[0] && (message.documents[0].ok === 0 || message.documents[0]['$err'] || message.documents[0]['errmsg'] || message.documents[0]['code']) ) { return handleOperationCallback(self, workItem.cb, new MongoError(message.documents[0])); } // Add the connection details message.hashedName = connection.hashedName; // Return the documents handleOperationCallback( self, workItem.cb, null, new CommandResult( workItem.fullResult ? message : message.documents[0], connection, message ) ); } }); }; } /** * Return the total socket count in the pool. * @method * @return {Number} The number of socket available. */ Pool.prototype.socketCount = function() { return this.availableConnections.length + this.inUseConnections.length; // + this.connectingConnections.length; }; /** * Return all pool connections * @method * @return {Connection[]} The pool connections */ Pool.prototype.allConnections = function() { return this.availableConnections.concat(this.inUseConnections).concat(this.connectingConnections); }; /** * Get a pool connection (round-robin) * @method * @return {Connection} */ Pool.prototype.get = function() { return this.allConnections()[0]; }; /** * Is the pool connected * @method * @return {boolean} */ Pool.prototype.isConnected = function() { // We are in a destroyed state if (this.state === DESTROYED || this.state === DESTROYING) { return false; } // Get connections var connections = this.availableConnections.concat(this.inUseConnections); // Check if we have any connected connections for (var i = 0; i < connections.length; i++) { if (connections[i].isConnected()) return true; } // Might be authenticating, but we are still connected if (connections.length === 0 && this.authenticating) { return true; } // Not connected return false; }; /** * Was the pool destroyed * @method * @return {boolean} */ Pool.prototype.isDestroyed = function() { return this.state === DESTROYED || this.state === DESTROYING; }; /** * Is the pool in a disconnected state * @method * @return {boolean} */ Pool.prototype.isDisconnected = function() { return this.state === DISCONNECTED; }; /** * Connect pool * @method */ Pool.prototype.connect = function() { if (this.state !== DISCONNECTED) { throw new MongoError('connection in unlawful state ' + this.state); } var self = this; // Transition to connecting state stateTransition(this, CONNECTING); // Create an array of the arguments var args = Array.prototype.slice.call(arguments, 0); // Create a connection var connection = new Connection(messageHandler(self), this.options); // Add to list of connections this.connectingConnections.push(connection); // Add listeners to the connection connection.once('connect', function(connection) { if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); // If we are in a topology, delegate the auth to it // This is to avoid issues where we would auth against an // arbiter if (self.options.inTopology) { // Set connected mode stateTransition(self, CONNECTED); // Move the active connection moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); // Emit the connect event return self.emit('connect', self); } // Apply any store credentials reauthenticate(self, connection, function(err) { if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); // We have an error emit it if (err) { // Destroy the pool self.destroy(); // Emit the error return self.emit('error', err); } // Authenticate authenticate(self, args, connection, function(err) { if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); // We have an error emit it if (err) { // Destroy the pool self.destroy(); // Emit the error return self.emit('error', err); } // Set connected mode stateTransition(self, CONNECTED); // Move the active connection moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); // if we have a minPoolSize, create a connection if (self.minSize) { for (let i = 0; i < self.minSize; i++) _createConnection(self); } // Emit the connect event self.emit('connect', self); }); }); }); // Add error handlers connection.once('error', connectionFailureHandler(this, 'error')); connection.once('close', connectionFailureHandler(this, 'close')); connection.once('timeout', connectionFailureHandler(this, 'timeout')); connection.once('parseError', connectionFailureHandler(this, 'parseError')); try { connection.connect(); } catch (err) { // SSL or something threw on connect process.nextTick(function() { self.emit('error', err); }); } }; /** * Authenticate using a specified mechanism * @method * @param {string} mechanism The Auth mechanism we are invoking * @param {string} db The db we are invoking the mechanism against * @param {...object} param Parameters for the specific mechanism * @param {authResultCallback} callback A callback function */ Pool.prototype.auth = function(mechanism) { var self = this; var args = Array.prototype.slice.call(arguments, 0); var callback = args.pop(); // If we don't have the mechanism fail if (self.authProviders[mechanism] == null && mechanism !== 'default') { throw new MongoError(f('auth provider %s does not exist', mechanism)); } // Signal that we are authenticating a new set of credentials this.authenticating = true; this.authenticatingTimestamp = new Date().getTime(); // Authenticate all live connections function authenticateLiveConnections(self, args, cb) { // Get the current viable connections var connections = self.allConnections(); // Allow nothing else to use the connections while we authenticate them self.availableConnections = []; self.inUseConnections = []; self.connectingConnections = []; var connectionsCount = connections.length; var error = null; // No connections available, return if (connectionsCount === 0) { self.authenticating = false; return callback(null); } // Authenticate the connections for (var i = 0; i < connections.length; i++) { authenticate(self, args, connections[i], function(err) { connectionsCount = connectionsCount - 1; // Store the error if (err) error = err; // Processed all connections if (connectionsCount === 0) { // Auth finished self.authenticating = false; // Add the connections back to available connections self.availableConnections = self.availableConnections.concat(connections); // We had an error, return it if (error) { // Log the error if (self.logger.isError()) { self.logger.error( f( '[%s] failed to authenticate against server %s:%s', self.id, self.options.host, self.options.port ) ); } return cb(error); } cb(null); } }); } } // Wait for a logout in process to happen function waitForLogout(self, cb) { if (!self.loggingout) return cb(); setTimeout(function() { waitForLogout(self, cb); }, 1); } // Wait for loggout to finish waitForLogout(self, function() { // Authenticate all live connections authenticateLiveConnections(self, args, function(err) { // Credentials correctly stored in auth provider if successful // Any new connections will now reauthenticate correctly self.authenticating = false; // Return after authentication connections callback(err); }); }); }; /** * Logout all users against a database * @method * @param {string} dbName The database name * @param {authResultCallback} callback A callback function */ Pool.prototype.logout = function(dbName, callback) { var self = this; if (typeof dbName !== 'string') { throw new MongoError('logout method requires a db name as first argument'); } if (typeof callback !== 'function') { throw new MongoError('logout method requires a callback'); } // Indicate logout in process this.loggingout = true; // Get all relevant connections var connections = self.availableConnections.concat(self.inUseConnections); var count = connections.length; // Store any error var error = null; // Send logout command over all the connections for (var i = 0; i < connections.length; i++) { write(self)( connections[i], new Query( this.options.bson, f('%s.$cmd', dbName), { logout: 1 }, { numberToSkip: 0, numberToReturn: 1 } ), function(err) { count = count - 1; if (err) error = err; if (count === 0) { self.loggingout = false; callback(error); } } ); } }; /** * Unref the pool * @method */ Pool.prototype.unref = function() { // Get all the known connections var connections = this.availableConnections .concat(this.inUseConnections) .concat(this.connectingConnections); connections.forEach(function(c) { c.unref(); }); }; // Events var events = ['error', 'close', 'timeout', 'parseError', 'connect']; // Destroy the connections function destroy(self, connections) { // Destroy all connections connections.forEach(function(c) { // Remove all listeners for (var i = 0; i < events.length; i++) { c.removeAllListeners(events[i]); } // Destroy connection c.destroy(); }); // Zero out all connections self.inUseConnections = []; self.availableConnections = []; self.nonAuthenticatedConnections = []; self.connectingConnections = []; // Set state to destroyed stateTransition(self, DESTROYED); } /** * Destroy pool * @method */ Pool.prototype.destroy = function(force) { var self = this; // Do not try again if the pool is already dead if (this.state === DESTROYED || self.state === DESTROYING) return; // Set state to destroyed stateTransition(this, DESTROYING); // Are we force closing if (force) { // Get all the known connections var connections = self.availableConnections .concat(self.inUseConnections) .concat(self.nonAuthenticatedConnections) .concat(self.connectingConnections); // Flush any remaining work items with // an error while (self.queue.length > 0) { var workItem = self.queue.shift(); if (typeof workItem.cb === 'function') { workItem.cb(new MongoError('Pool was force destroyed')); } } // Destroy the topology return destroy(self, connections); } // Clear out the reconnect if set if (this.reconnectId) { clearTimeout(this.reconnectId); } // If we have a reconnect connection running, close // immediately if (this.reconnectConnection) { this.reconnectConnection.destroy(); } // Wait for the operations to drain before we close the pool function checkStatus() { flushMonitoringOperations(self.queue); if (self.queue.length === 0) { // Get all the known connections var connections = self.availableConnections .concat(self.inUseConnections) .concat(self.nonAuthenticatedConnections) .concat(self.connectingConnections); // Check if we have any in flight operations for (var i = 0; i < connections.length; i++) { // There is an operation still in flight, reschedule a // check waiting for it to drain if (connections[i].workItems.length > 0) { return setTimeout(checkStatus, 1); } } destroy(self, connections); // } else if (self.queue.length > 0 && !this.reconnectId) { } else { // Ensure we empty the queue _execute(self)(); // Set timeout setTimeout(checkStatus, 1); } } // Initiate drain of operations checkStatus(); }; // Prepare the buffer that Pool.prototype.write() uses to send to the server var serializeCommands = function(self, commands, result, callback) { // Base case when there are no more commands to serialize if (commands.length === 0) return callback(null, result); // Pop off the zeroth command and serialize it var thisCommand = commands.shift(); var originalCommandBuffer = thisCommand.toBin(); // Check whether we and the server have agreed to use a compressor if (self.options.agreedCompressor && !hasUncompressibleCommands(thisCommand)) { // Transform originalCommandBuffer into OP_COMPRESSED var concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); var messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); // Extract information needed for OP_COMPRESSED from the uncompressed message var originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); // Compress the message body compress(self, messageToBeCompressed, function(err, compressedMessage) { if (err) return callback(err, null); // Create the msgHeader of OP_COMPRESSED var msgHeader = new Buffer(MESSAGE_HEADER_SIZE); msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + 9 + compressedMessage.length, 0); // messageLength msgHeader.writeInt32LE(thisCommand.requestId, 4); // requestID msgHeader.writeInt32LE(0, 8); // responseTo (zero) msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode // Create the compression details of OP_COMPRESSED var compressionDetails = new Buffer(9); compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID // Push the concatenation of the OP_COMPRESSED message onto results result.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); // Continue recursing through the commands array serializeCommands(self, commands, result, callback); }); } else { // Push the serialization of the command onto results result.push(originalCommandBuffer); // Continue recursing through the commands array serializeCommands(self, commands, result, callback); } }; /** * Write a message to MongoDB * @method * @return {Connection} */ Pool.prototype.write = function(commands, options, cb) { var self = this; // Ensure we have a callback if (typeof options === 'function') { cb = options; } // Always have options options = options || {}; // We need to have a callback function unless the message returns no response if (!(typeof cb === 'function') && !options.noResponse) { throw new MongoError('write method must provide a callback'); } // Pool was destroyed error out if (this.state === DESTROYED || this.state === DESTROYING) { // Callback with an error if (cb) { try { cb(new MongoError('pool destroyed')); } catch (err) { process.nextTick(function() { throw err; }); } } return; } if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { // if we have a domain bind to it var oldCb = cb; cb = process.domain.bind(function() { // v8 - argumentsToArray one-liner var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } // bounce off event loop so domain switch takes place process.nextTick(function() { oldCb.apply(null, args); }); }); } // Do we have an operation var operation = { cb: cb, raw: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, fullResult: false }; // Set the options for the parsing operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; operation.promoteValues = typeof options.promoteValues === 'boolean' ? options.promoteValues : true; operation.promoteBuffers = typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; operation.raw = typeof options.raw === 'boolean' ? options.raw : false; operation.immediateRelease = typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; operation.documentsReturnedIn = options.documentsReturnedIn; operation.command = typeof options.command === 'boolean' ? options.command : false; operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; operation.session = options.session || null; // Optional per operation socketTimeout operation.socketTimeout = options.socketTimeout; operation.monitoring = options.monitoring; // Custom socket Timeout if (options.socketTimeout) { operation.socketTimeout = options.socketTimeout; } // Ensure commands is an array if (!Array.isArray(commands)) { commands = [commands]; } // Get the requestId operation.requestId = commands[commands.length - 1].requestId; if (hasSessionSupport(this.topology)) { let sessionOptions = {}; if (this.topology.clusterTime) { sessionOptions = { $clusterTime: this.topology.clusterTime }; } if (operation.session) { // TODO: reenable when sessions development is complete // if (operation.session.topology !== this.topology) { // return cb( // new MongoError('Sessions may only be used with the client they were created from') // ); // } if (operation.session.hasEnded) { return cb(new MongoError('Use of expired sessions is not permitted')); } if ( operation.session.clusterTime && operation.session.clusterTime.clusterTime.greaterThan( sessionOptions.$clusterTime.clusterTime ) ) { sessionOptions.$clusterTime = operation.session.clusterTime; } sessionOptions.lsid = operation.session.id; // update the `lastUse` of the acquired ServerSession operation.session.serverSession.lastUse = Date.now(); } // decorate the commands with session-specific details commands.forEach(command => { if (command instanceof Query) { Object.assign(command.query, sessionOptions); } else { Object.assign(command, sessionOptions); } }); } // Prepare the operation buffer serializeCommands(self, commands, [], function(err, serializedCommands) { if (err) throw err; // Set the operation's buffer to the serialization of the commands operation.buffer = serializedCommands; // If we have a monitoring operation schedule as the very first operation // Otherwise add to back of queue if (options.monitoring) { self.queue.unshift(operation); } else { self.queue.push(operation); } // Attempt to execute the operation if (!self.executing) { process.nextTick(function() { _execute(self)(); }); } }); }; // Return whether a command contains an uncompressible command term // Will return true if command contains no uncompressible command terms var hasUncompressibleCommands = function(command) { return uncompressibleCommands.some(function(cmd) { return command.query.hasOwnProperty(cmd); }); }; // Remove connection method function remove(connection, connections) { for (var i = 0; i < connections.length; i++) { if (connections[i] === connection) { connections.splice(i, 1); return true; } } } function removeConnection(self, connection) { if (remove(connection, self.availableConnections)) return; if (remove(connection, self.inUseConnections)) return; if (remove(connection, self.connectingConnections)) return; if (remove(connection, self.nonAuthenticatedConnections)) return; } // All event handlers var handlers = ['close', 'message', 'error', 'timeout', 'parseError', 'connect']; function _createConnection(self) { if (self.state === DESTROYED || self.state === DESTROYING) { return; } var connection = new Connection(messageHandler(self), self.options); // Push the connection self.connectingConnections.push(connection); // Handle any errors var tempErrorHandler = function(_connection) { return function() { // Destroy the connection _connection.destroy(); // Remove the connection from the connectingConnections list removeConnection(self, _connection); // Start reconnection attempts if (!self.reconnectId && self.options.reconnect) { self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); } }; }; // Handle successful connection var tempConnectHandler = function(_connection) { return function() { // Destroyed state return if (self.state === DESTROYED || self.state === DESTROYING) { // Remove the connection from the list removeConnection(self, _connection); return _connection.destroy(); } // Destroy all event emitters handlers.forEach(function(e) { _connection.removeAllListeners(e); }); // Add the final handlers _connection.once('close', connectionFailureHandler(self, 'close')); _connection.once('error', connectionFailureHandler(self, 'error')); _connection.once('timeout', connectionFailureHandler(self, 'timeout')); _connection.once('parseError', connectionFailureHandler(self, 'parseError')); // Signal reauthenticate(self, _connection, function(err) { if (self.state === DESTROYED || self.state === DESTROYING) { return _connection.destroy(); } // Remove the connection from the connectingConnections list removeConnection(self, _connection); // Handle error if (err) { return _connection.destroy(); } // If we are c at the moment // Do not automatially put in available connections // As we need to apply the credentials first if (self.authenticating) { self.nonAuthenticatedConnections.push(_connection); } else { // Push to available self.availableConnections.push(_connection); // Execute any work waiting _execute(self)(); } }); }; }; // Add all handlers connection.once('close', tempErrorHandler(connection)); connection.once('error', tempErrorHandler(connection)); connection.once('timeout', tempErrorHandler(connection)); connection.once('parseError', tempErrorHandler(connection)); connection.once('connect', tempConnectHandler(connection)); // Start connection connection.connect(); } function flushMonitoringOperations(queue) { for (var i = 0; i < queue.length; i++) { if (queue[i].monitoring) { var workItem = queue[i]; queue.splice(i, 1); workItem.cb( new MongoError({ message: 'no connection available for monitoring', driver: true }) ); } } } function _execute(self) { return function() { if (self.state === DESTROYED) return; // Already executing, skip if (self.executing) return; // Set pool as executing self.executing = true; // Wait for auth to clear before continuing function waitForAuth(cb) { if (!self.authenticating) return cb(); // Wait for a milisecond and try again setTimeout(function() { waitForAuth(cb); }, 1); } // Block on any auth in process waitForAuth(function() { // New pool connections are in progress, wait them to finish // before executing any more operation to ensure distribution of // operations if (self.connectingConnections.length > 0) { return; } // As long as we have available connections // eslint-disable-next-line while (true) { // Total availble connections var totalConnections = self.availableConnections.length + self.connectingConnections.length + self.inUseConnections.length; // No available connections available, flush any monitoring ops if (self.availableConnections.length === 0) { // Flush any monitoring operations flushMonitoringOperations(self.queue); break; } // No queue break if (self.queue.length === 0) { break; } // Get a connection var connection = null; // Locate all connections that have no work var connections = []; // Get a list of all connections for (var i = 0; i < self.availableConnections.length; i++) { if (self.availableConnections[i].workItems.length === 0) { connections.push(self.availableConnections[i]); } } // No connection found that has no work on it, just pick one for pipelining if (connections.length === 0) { connection = self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; } else { connection = connections[self.connectionIndex++ % connections.length]; } // Is the connection connected if (connection.isConnected()) { // Get the next work item var workItem = self.queue.shift(); // If we are monitoring we need to use a connection that is not // running another operation to avoid socket timeout changes // affecting an existing operation if (workItem.monitoring) { var foundValidConnection = false; for (i = 0; i < self.availableConnections.length; i++) { // If the connection is connected // And there are no pending workItems on it // Then we can safely use it for monitoring. if ( self.availableConnections[i].isConnected() && self.availableConnections[i].workItems.length === 0 ) { foundValidConnection = true; connection = self.availableConnections[i]; break; } } // No safe connection found, attempt to grow the connections // if possible and break from the loop if (!foundValidConnection) { // Put workItem back on the queue self.queue.unshift(workItem); // Attempt to grow the pool if it's not yet maxsize if (totalConnections < self.options.size && self.queue.length > 0) { // Create a new connection _createConnection(self); } // Re-execute the operation setTimeout(function() { _execute(self)(); }, 10); break; } } // Don't execute operation until we have a full pool if (totalConnections < self.options.size) { // Connection has work items, then put it back on the queue // and create a new connection if (connection.workItems.length > 0) { // Lets put the workItem back on the list self.queue.unshift(workItem); // Create a new connection _createConnection(self); // Break from the loop break; } } // Get actual binary commands var buffer = workItem.buffer; // Set current status of authentication process workItem.authenticating = self.authenticating; workItem.authenticatingTimestamp = self.authenticatingTimestamp; // If we are monitoring take the connection of the availableConnections if (workItem.monitoring) { moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); } // Track the executing commands on the mongo server // as long as there is an expected response if (!workItem.noResponse) { connection.workItems.push(workItem); } // We have a custom socketTimeout if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { connection.setSocketTimeout(workItem.socketTimeout); } // Capture if write was successful var writeSuccessful = true; // Put operation on the wire if (Array.isArray(buffer)) { for (i = 0; i < buffer.length; i++) { writeSuccessful = connection.write(buffer[i]); } } else { writeSuccessful = connection.write(buffer); } if (writeSuccessful && workItem.immediateRelease && self.authenticating) { removeConnection(self, connection); self.nonAuthenticatedConnections.push(connection); } else if (writeSuccessful === false) { // If write not successful put back on queue self.queue.unshift(workItem); // Remove the disconnected connection removeConnection(self, connection); // Flush any monitoring operations in the queue, failing fast flushMonitoringOperations(self.queue); } } else { // Remove the disconnected connection removeConnection(self, connection); // Flush any monitoring operations in the queue, failing fast flushMonitoringOperations(self.queue); } } }); self.executing = false; }; } // Make execution loop available for testing Pool._execute = _execute; /** * A server connect event, used to verify that the connection is up and running * * @event Pool#connect * @type {Pool} */ /** * A server reconnect event, used to verify that pool reconnected. * * @event Pool#reconnect * @type {Pool} */ /** * The server connection closed, all pool connections closed * * @event Pool#close * @type {Pool} */ /** * The server connection caused an error, all pool connections closed * * @event Pool#error * @type {Pool} */ /** * The server connection timed out, all pool connections closed * * @event Pool#timeout * @type {Pool} */ /** * The driver experienced an invalid message, all pool connections closed * * @event Pool#parseError * @type {Pool} */ /** * The driver attempted to reconnect * * @event Pool#attemptReconnect * @type {Pool} */ /** * The driver exhausted all reconnect attempts * * @event Pool#reconnectFailed * @type {Pool} */ module.exports = Pool; }).call(this,require('_process'),require("buffer").Buffer) },{"../auth/gssapi":346,"../auth/mongocr":347,"../auth/plain":348,"../auth/scram":349,"../auth/sspi":350,"../auth/x509":351,"../error":359,"../topologies/shared":366,"../wireprotocol/compression":371,"../wireprotocol/shared":372,"./command_result":352,"./commands":353,"./connection":354,"./logger":355,"_process":507,"buffer":144,"events":316,"util":563}],357:[function(require,module,exports){ 'use strict'; var f = require('util').format, require_optional = require('require_optional'); // Set property function var setProperty = function(obj, prop, flag, values) { Object.defineProperty(obj, prop.name, { enumerable: true, set: function(value) { if (typeof value !== 'boolean') throw new Error(f('%s required a boolean', prop.name)); // Flip the bit to 1 if (value === true) values.flags |= flag; // Flip the bit to 0 if it's set, otherwise ignore if (value === false && (values.flags & flag) === flag) values.flags ^= flag; prop.value = value; }, get: function() { return prop.value; } }); }; // Set property function var getProperty = function(obj, propName, fieldName, values, func) { Object.defineProperty(obj, propName, { enumerable: true, get: function() { // Not parsed yet, parse it if (values[fieldName] == null && obj.isParsed && !obj.isParsed()) { obj.parse(); } // Do we have a post processing function if (typeof func === 'function') return func(values[fieldName]); // Return raw value return values[fieldName]; } }); }; // Set simple property var getSingleProperty = function(obj, name, value) { Object.defineProperty(obj, name, { enumerable: true, get: function() { return value; } }); }; // Shallow copy var copy = function(fObj, tObj) { tObj = tObj || {}; for (var name in fObj) tObj[name] = fObj[name]; return tObj; }; var debugOptions = function(debugFields, options) { var finaloptions = {}; debugFields.forEach(function(n) { finaloptions[n] = options[n]; }); return finaloptions; }; var retrieveBSON = function() { var BSON = require('bson'); BSON.native = false; try { var optionalBSON = require_optional('bson-ext'); if (optionalBSON) { optionalBSON.native = true; return optionalBSON; } } catch (err) {} // eslint-disable-line return BSON; }; // Throw an error if an attempt to use Snappy is made when Snappy is not installed var noSnappyWarning = function() { throw new Error( 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' ); }; // Facilitate loading Snappy optionally var retrieveSnappy = function() { var snappy = null; try { snappy = require_optional('snappy'); } catch (error) {} // eslint-disable-line if (!snappy) { snappy = { compress: noSnappyWarning, uncompress: noSnappyWarning, compressSync: noSnappyWarning, uncompressSync: noSnappyWarning }; } return snappy; }; exports.setProperty = setProperty; exports.getProperty = getProperty; exports.getSingleProperty = getSingleProperty; exports.copy = copy; exports.debugOptions = debugOptions; exports.retrieveBSON = retrieveBSON; exports.retrieveSnappy = retrieveSnappy; },{"bson":125,"require_optional":534,"util":563}],358:[function(require,module,exports){ (function (process){ 'use strict'; var Logger = require('./connection/logger'), retrieveBSON = require('./connection/utils').retrieveBSON, MongoError = require('./error').MongoError, MongoNetworkError = require('./error').MongoNetworkError, f = require('util').format; var BSON = retrieveBSON(), Long = BSON.Long; /** * This is a cursor results callback * * @callback resultCallback * @param {error} error An error object. Set to null if no error present * @param {object} document */ /** * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB * allowing for iteration over the results returned from the underlying query. * * **CURSORS Cannot directly be instantiated** * @example * var Server = require('mongodb-core').Server * , ReadPreference = require('mongodb-core').ReadPreference * , assert = require('assert'); * * var server = new Server({host: 'localhost', port: 27017}); * // Wait for the connection event * server.on('connect', function(server) { * assert.equal(null, err); * * // Execute the write * var cursor = _server.cursor('integration_tests.inserts_example4', { * find: 'integration_tests.example4' * , query: {a:1} * }, { * readPreference: new ReadPreference('secondary'); * }); * * // Get the first document * cursor.next(function(err, doc) { * assert.equal(null, err); * server.destroy(); * }); * }); * * // Start connecting * server.connect(); */ /** * Creates a new Cursor, not to be used directly * @class * @param {object} bson An instance of the BSON parser * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {{object}|Long} cmd The selector (can be a command or a cursorId) * @param {object} [options=null] Optional settings. * @param {object} [options.batchSize=1000] Batchsize for the operation * @param {array} [options.documents=[]] Initial documents list for cursor * @param {object} [options.transforms=null] Transform methods for the cursor results * @param {function} [options.transforms.query] Transform the value returned from the initial query * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next * @param {object} topology The server topology instance. * @param {object} topologyOptions The server topology options. * @return {Cursor} A cursor instance * @property {number} cursorBatchSize The current cursorBatchSize for the cursor * @property {number} cursorLimit The current cursorLimit for the cursor * @property {number} cursorSkip The current cursorSkip for the cursor */ var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { options = options || {}; // Cursor pool this.pool = null; // Cursor server this.server = null; // Do we have a not connected handler this.disconnectHandler = options.disconnectHandler; // Set local values this.bson = bson; this.ns = ns; this.cmd = cmd; this.options = options; this.topology = topology; // All internal state this.cursorState = { cursorId: null, cmd: cmd, documents: options.documents || [], cursorIndex: 0, dead: false, killed: false, init: false, notified: false, limit: options.limit || cmd.limit || 0, skip: options.skip || cmd.skip || 0, batchSize: options.batchSize || cmd.batchSize || 1000, currentLimit: 0, // Result field name if not a cursor (contains the array of results) transforms: options.transforms }; // Add promoteLong to cursor state if (typeof topologyOptions.promoteLongs === 'boolean') { this.cursorState.promoteLongs = topologyOptions.promoteLongs; } else if (typeof options.promoteLongs === 'boolean') { this.cursorState.promoteLongs = options.promoteLongs; } else if (typeof options.session === 'object') { this.cursorState.session = options.session; } // Add promoteValues to cursor state if (typeof topologyOptions.promoteValues === 'boolean') { this.cursorState.promoteValues = topologyOptions.promoteValues; } else if (typeof options.promoteValues === 'boolean') { this.cursorState.promoteValues = options.promoteValues; } // Add promoteBuffers to cursor state if (typeof topologyOptions.promoteBuffers === 'boolean') { this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; } else if (typeof options.promoteBuffers === 'boolean') { this.cursorState.promoteBuffers = options.promoteBuffers; } if (topologyOptions.reconnect) { this.cursorState.reconnect = topologyOptions.reconnect; } // Logger this.logger = Logger('Cursor', topologyOptions); // // Did we pass in a cursor id if (typeof cmd === 'number') { this.cursorState.cursorId = Long.fromNumber(cmd); this.cursorState.lastCursorId = this.cursorState.cursorId; } else if (cmd instanceof Long) { this.cursorState.cursorId = cmd; this.cursorState.lastCursorId = cmd; } }; Cursor.prototype.setCursorBatchSize = function(value) { this.cursorState.batchSize = value; }; Cursor.prototype.cursorBatchSize = function() { return this.cursorState.batchSize; }; Cursor.prototype.setCursorLimit = function(value) { this.cursorState.limit = value; }; Cursor.prototype.cursorLimit = function() { return this.cursorState.limit; }; Cursor.prototype.setCursorSkip = function(value) { this.cursorState.skip = value; }; Cursor.prototype.cursorSkip = function() { return this.cursorState.skip; }; // // Handle callback (including any exceptions thrown) var handleCallback = function(callback, err, result) { try { callback(err, result); } catch (err) { process.nextTick(function() { throw err; }); } }; // Internal methods Cursor.prototype._find = function(callback) { var self = this; if (self.logger.isDebug()) { self.logger.debug( f( 'issue initial query [%s] with flags [%s]', JSON.stringify(self.cmd), JSON.stringify(self.query) ) ); } var queryCallback = function(err, r) { if (err) return callback(err); // Get the raw message var result = r.message; // Query failure bit set if (result.queryFailure) { return callback(new MongoError(result.documents[0]), null); } // Check if we have a command cursor if ( Array.isArray(result.documents) && result.documents.length === 1 && (!self.cmd.find || (self.cmd.find && self.cmd.virtual === false)) && (result.documents[0].cursor !== 'string' || result.documents[0]['$err'] || result.documents[0]['errmsg'] || Array.isArray(result.documents[0].result)) ) { // We have a an error document return the error if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { return callback(new MongoError(result.documents[0]), null); } // We have a cursor document if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { var id = result.documents[0].cursor.id; // If we have a namespace change set the new namespace for getmores if (result.documents[0].cursor.ns) { self.ns = result.documents[0].cursor.ns; } // Promote id to long if needed self.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; self.cursorState.lastCursorId = self.cursorState.cursorId; // If we have a firstBatch set it if (Array.isArray(result.documents[0].cursor.firstBatch)) { self.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); } // Return after processing command cursor return callback(null, result); } if (Array.isArray(result.documents[0].result)) { self.cursorState.documents = result.documents[0].result; self.cursorState.cursorId = Long.ZERO; return callback(null, result); } } // Otherwise fall back to regular find path self.cursorState.cursorId = result.cursorId; self.cursorState.documents = result.documents; self.cursorState.lastCursorId = result.cursorId; // Transform the results with passed in transformation method if provided if (self.cursorState.transforms && typeof self.cursorState.transforms.query === 'function') { self.cursorState.documents = self.cursorState.transforms.query(result); } // Return callback callback(null, result); }; // Options passed to the pool var queryOptions = {}; // If we have a raw query decorate the function if (self.options.raw || self.cmd.raw) { // queryCallback.raw = self.options.raw || self.cmd.raw; queryOptions.raw = self.options.raw || self.cmd.raw; } // Do we have documentsReturnedIn set on the query if (typeof self.query.documentsReturnedIn === 'string') { // queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; queryOptions.documentsReturnedIn = self.query.documentsReturnedIn; } // Add promote Long value if defined if (typeof self.cursorState.promoteLongs === 'boolean') { queryOptions.promoteLongs = self.cursorState.promoteLongs; } // Add promote values if defined if (typeof self.cursorState.promoteValues === 'boolean') { queryOptions.promoteValues = self.cursorState.promoteValues; } // Add promote values if defined if (typeof self.cursorState.promoteBuffers === 'boolean') { queryOptions.promoteBuffers = self.cursorState.promoteBuffers; } if (typeof self.cursorState.session === 'object') { queryOptions.session = self.cursorState.session; } // Write the initial command out self.server.s.pool.write(self.query, queryOptions, queryCallback); }; Cursor.prototype._getmore = function(callback) { if (this.logger.isDebug()) this.logger.debug(f('schedule getMore call for query [%s]', JSON.stringify(this.query))); // Determine if it's a raw query var raw = this.options.raw || this.cmd.raw; // Set the current batchSize var batchSize = this.cursorState.batchSize; if ( this.cursorState.limit > 0 && this.cursorState.currentLimit + batchSize > this.cursorState.limit ) { batchSize = this.cursorState.limit - this.cursorState.currentLimit; } // Default pool var pool = this.server.s.pool; // We have a wire protocol handler this.server.wireProtocolHandler.getMore( this.bson, this.ns, this.cursorState, batchSize, raw, pool, this.options, callback ); }; Cursor.prototype._killcursor = function(callback) { // Set cursor to dead this.cursorState.dead = true; this.cursorState.killed = true; // Remove documents this.cursorState.documents = []; // If no cursor id just return if ( this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init === false ) { if (callback) callback(null, null); return; } // Default pool var pool = this.server.s.pool; // Execute command this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState, pool, callback); }; /** * Clone the cursor * @method * @return {Cursor} */ Cursor.prototype.clone = function() { return this.topology.cursor(this.ns, this.cmd, this.options); }; /** * Checks if the cursor is dead * @method * @return {boolean} A boolean signifying if the cursor is dead or not */ Cursor.prototype.isDead = function() { return this.cursorState.dead === true; }; /** * Checks if the cursor was killed by the application * @method * @return {boolean} A boolean signifying if the cursor was killed by the application */ Cursor.prototype.isKilled = function() { return this.cursorState.killed === true; }; /** * Checks if the cursor notified it's caller about it's death * @method * @return {boolean} A boolean signifying if the cursor notified the callback */ Cursor.prototype.isNotified = function() { return this.cursorState.notified === true; }; /** * Returns current buffered documents length * @method * @return {number} The number of items in the buffered documents */ Cursor.prototype.bufferedCount = function() { return this.cursorState.documents.length - this.cursorState.cursorIndex; }; /** * Returns current buffered documents * @method * @return {Array} An array of buffered documents */ Cursor.prototype.readBufferedDocuments = function(number) { var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; var elements = this.cursorState.documents.slice( this.cursorState.cursorIndex, this.cursorState.cursorIndex + length ); // Transform the doc with passed in transformation method if provided if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { // Transform all the elements for (var i = 0; i < elements.length; i++) { elements[i] = this.cursorState.transforms.doc(elements[i]); } } // Ensure we do not return any more documents than the limit imposed // Just return the number of elements up to the limit if ( this.cursorState.limit > 0 && this.cursorState.currentLimit + elements.length > this.cursorState.limit ) { elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); this.kill(); } // Adjust current limit this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; // Return elements return elements; }; /** * Kill the cursor * @method * @param {resultCallback} callback A callback function */ Cursor.prototype.kill = function(callback) { this._killcursor(callback); }; /** * Resets the cursor * @method * @return {null} */ Cursor.prototype.rewind = function() { if (this.cursorState.init) { if (!this.cursorState.dead) { this.kill(); } this.cursorState.currentLimit = 0; this.cursorState.init = false; this.cursorState.dead = false; this.cursorState.killed = false; this.cursorState.notified = false; this.cursorState.documents = []; this.cursorState.cursorId = null; this.cursorState.cursorIndex = 0; } }; /** * Validate if the pool is dead and return error */ var isConnectionDead = function(self, callback) { if (self.pool && self.pool.isDestroyed()) { self.cursorState.notified = true; self.cursorState.killed = true; self.cursorState.documents = []; self.cursorState.cursorIndex = 0; callback( new MongoNetworkError( f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port) ) ); return true; } return false; }; /** * Validate if the cursor is dead but was not explicitly killed by user */ var isCursorDeadButNotkilled = function(self, callback) { // Cursor is dead but not marked killed, return null if (self.cursorState.dead && !self.cursorState.killed) { self.cursorState.notified = true; self.cursorState.killed = true; self.cursorState.documents = []; self.cursorState.cursorIndex = 0; handleCallback(callback, null, null); return true; } return false; }; /** * Validate if the cursor is dead and was killed by user */ var isCursorDeadAndKilled = function(self, callback) { if (self.cursorState.dead && self.cursorState.killed) { handleCallback(callback, new MongoError('cursor is dead')); return true; } return false; }; /** * Validate if the cursor was killed by the user */ var isCursorKilled = function(self, callback) { if (self.cursorState.killed) { self.cursorState.notified = true; self.cursorState.documents = []; self.cursorState.cursorIndex = 0; handleCallback(callback, null, null); return true; } return false; }; /** * Mark cursor as being dead and notified */ var setCursorDeadAndNotified = function(self, callback) { self.cursorState.dead = true; self.cursorState.notified = true; self.cursorState.documents = []; self.cursorState.cursorIndex = 0; handleCallback(callback, null, null); }; /** * Mark cursor as being notified */ var setCursorNotified = function(self, callback) { self.cursorState.notified = true; self.cursorState.documents = []; self.cursorState.cursorIndex = 0; handleCallback(callback, null, null); }; var nextFunction = function(self, callback) { // We have notified about it if (self.cursorState.notified) { return callback(new Error('cursor is exhausted')); } // Cursor is killed return null if (isCursorKilled(self, callback)) return; // Cursor is dead but not marked killed, return null if (isCursorDeadButNotkilled(self, callback)) return; // We have a dead and killed cursor, attempting to call next should error if (isCursorDeadAndKilled(self, callback)) return; // We have just started the cursor if (!self.cursorState.init) { // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if (!self.topology.isConnected(self.options)) { // Only need this for single server, because repl sets and mongos // will always continue trying to reconnect if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { // Reconnect is disabled, so we'll never reconnect return callback(new MongoError('no connection available')); } if (self.disconnectHandler != null) { if (self.topology.isDestroyed()) { // Topology was destroyed, so don't try to wait for it to reconnect return callback(new MongoError('Topology was destroyed')); } return self.disconnectHandler.addObjectAndMethod( 'cursor', self, 'next', [callback], callback ); } } try { self.server = self.topology.getServer(self.options); } catch (err) { // Handle the error and add object to next method call if (self.disconnectHandler != null) { return self.disconnectHandler.addObjectAndMethod( 'cursor', self, 'next', [callback], callback ); } // Otherwise return the error return callback(err); } // Set as init self.cursorState.init = true; // Server does not support server if (self.cmd && self.cmd.collation && self.server.ismaster.maxWireVersion < 5) { return callback(new MongoError(f('server %s does not support collation', self.server.name))); } try { self.query = self.server.wireProtocolHandler.command( self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options ); } catch (err) { return callback(err); } } // If we don't have a cursorId execute the first query if (self.cursorState.cursorId == null) { // Check if pool is dead and return if not possible to // execute the query against the db if (isConnectionDead(self, callback)) return; // Check if topology is destroyed if (self.topology.isDestroyed()) return callback( new MongoNetworkError('connection destroyed, not possible to instantiate cursor') ); // query, cmd, options, cursorState, callback self._find(function(err) { if (err) return handleCallback(callback, err, null); if ( self.cursorState.documents.length === 0 && self.cursorState.cursorId && self.cursorState.cursorId.isZero() && !self.cmd.tailable && !self.cmd.awaitData ) { return setCursorNotified(self, callback); } nextFunction(self, callback); }); } else if ( self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit ) { // Ensure we kill the cursor on the server self.kill(); // Set cursor in dead and notified state return setCursorDeadAndNotified(self, callback); } else if ( self.cursorState.cursorIndex === self.cursorState.documents.length && !Long.ZERO.equals(self.cursorState.cursorId) ) { // Ensure an empty cursor state self.cursorState.documents = []; self.cursorState.cursorIndex = 0; // Check if topology is destroyed if (self.topology.isDestroyed()) return callback( new MongoNetworkError('connection destroyed, not possible to instantiate cursor') ); // Check if connection is dead and return if not possible to // execute a getmore on this connection if (isConnectionDead(self, callback)) return; // Execute the next get more self._getmore(function(err, doc, connection) { if (err) return handleCallback(callback, err); // Save the returned connection to ensure all getMore's fire over the same connection self.connection = connection; // Tailable cursor getMore result, notify owner about it // No attempt is made here to retry, this is left to the user of the // core module to handle to keep core simple if ( self.cursorState.documents.length === 0 && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId) ) { // No more documents in the tailed cursor return handleCallback( callback, new MongoError({ message: 'No more documents in tailed cursor', tailable: self.cmd.tailable, awaitData: self.cmd.awaitData }) ); } else if ( self.cursorState.documents.length === 0 && self.cmd.tailable && !Long.ZERO.equals(self.cursorState.cursorId) ) { return nextFunction(self, callback); } if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { return setCursorDeadAndNotified(self, callback); } nextFunction(self, callback); }); } else if ( self.cursorState.documents.length === self.cursorState.cursorIndex && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId) ) { return handleCallback( callback, new MongoError({ message: 'No more documents in tailed cursor', tailable: self.cmd.tailable, awaitData: self.cmd.awaitData }) ); } else if ( self.cursorState.documents.length === self.cursorState.cursorIndex && Long.ZERO.equals(self.cursorState.cursorId) ) { setCursorDeadAndNotified(self, callback); } else { if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { // Ensure we kill the cursor on the server self.kill(); // Set cursor in dead and notified state return setCursorDeadAndNotified(self, callback); } // Increment the current cursor limit self.cursorState.currentLimit += 1; // Get the document var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; // Doc overflow if (!doc || doc.$err) { // Ensure we kill the cursor on the server self.kill(); // Set cursor in dead and notified state return setCursorDeadAndNotified(self, function() { handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); }); } // Transform the doc with passed in transformation method if provided if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { doc = self.cursorState.transforms.doc(doc); } // Return the document handleCallback(callback, null, doc); } }; /** * Retrieve the next document from the cursor * @method * @param {resultCallback} callback A callback function */ Cursor.prototype.next = function(callback) { nextFunction(this, callback); }; module.exports = Cursor; }).call(this,require('_process')) },{"./connection/logger":355,"./connection/utils":357,"./error":359,"_process":507,"util":563}],359:[function(require,module,exports){ 'use strict'; var util = require('util'); /** * Creates a new MongoError * @class * @augments Error * @param {Error|string|object} message The error message * @property {string} message The error message * @property {string} stack The error call stack * @return {MongoError} A MongoError instance */ function MongoError(message) { var tmp = Error.apply(this, arguments); tmp.name = this.name = 'MongoError'; if (message instanceof Error) { this.message = message.message; this.stack = message.stack; } else { if (typeof message === 'string') { this.message = message; } else { this.message = message.message || message.errmsg || message.$err || 'n/a'; for (var name in message) { this[name] = message[name]; } } if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } } util.inherits(MongoError, Error); /** * Creates a new MongoError object * @method * @param {Error|string|object} options The options used to create the error. * @return {MongoError} A MongoError instance * @deprecated Use `new MongoError()` instead. */ MongoError.create = function(options) { return new MongoError(options); }; /** * Creates a new MongoNetworkError * @class * @param {Error|string|object} message The error message * @property {string} message The error message * @property {string} stack The error call stack * @return {MongoNetworkError} A MongoNetworkError instance * @extends {MongoError} */ var MongoNetworkError = function(message) { MongoError.call(this, message); this.name = 'MongoNetworkError'; }; util.inherits(MongoNetworkError, MongoError); /** * An error used when attempting to parse a value (like a connection string) * * @class * @param {Error|string|object} message The error message * @property {string} message The error message * @return {MongoParseError} A MongoNetworkError instance * @extends {MongoError} */ const MongoParseError = function(message) { MongoError.call(this, message); this.name = 'MongoParseError'; }; util.inherits(MongoParseError, MongoError); module.exports = { MongoError: MongoError, MongoNetworkError: MongoNetworkError, MongoParseError: MongoParseError }; },{"util":563}],360:[function(require,module,exports){ 'use strict'; const retrieveBSON = require('./connection/utils').retrieveBSON, EventEmitter = require('events'), BSON = retrieveBSON(), Binary = BSON.Binary, uuidV4 = require('./utils').uuidV4; /** * */ class ClientSession extends EventEmitter { constructor(topology, sessionPool, options) { super(); if (topology == null) { throw new Error('ClientSession requires a topology'); } if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { throw new Error('ClientSession requires a ServerSessionPool'); } options = options || {}; this.topology = topology; this.sessionPool = sessionPool; this.hasEnded = false; this.serverSession = sessionPool.acquire(); this.supports = { causalConsistency: !!options.causalConsistency }; options = options || {}; if (typeof options.initialClusterTime !== 'undefined') { this.clusterTime = options.initialClusterTime; } else { this.clusterTime = null; } this.operationTime = null; } /** * */ endSession(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; if (this.hasEnded) { if (typeof callback === 'function') callback(null, null); return; } if (!options.skipCommand) { // send the `endSessions` command this.topology.endSessions(this.id); } // mark the session as ended, and emit a signal this.hasEnded = true; this.emit('ended', this); // release the server session back to the pool this.sessionPool.release(this.serverSession); // spec indicates that we should ignore all errors for `endSessions` if (typeof callback === 'function') callback(null, null); } /** * Advances the operationTime for a ClientSession. * * @param {object} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to */ advanceOperationTime(operationTime) { if (this.operationTime == null) { this.operationTime = operationTime; return; } if (operationTime.greaterThan(this.operationTime)) { this.operationTime = operationTime; } } /** * Used to determine if this session equals another */ equals(session) { if (!(session instanceof ClientSession)) { return false; } return this.id.id.buffer.equals(session.id.id.buffer); } } Object.defineProperty(ClientSession.prototype, 'id', { get: function() { return this.serverSession.id; } }); /** * */ class ServerSession { constructor() { this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; this.lastUse = Date.now(); this.txnNumber = 0; } /** * * @param {*} sessionTimeoutMinutes */ hasTimedOut(sessionTimeoutMinutes) { // Take the difference of the lastUse timestamp and now, which will result in a value in // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` const idleTimeMinutes = Math.round( (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 ); return idleTimeMinutes > sessionTimeoutMinutes - 1; } } /** * */ class ServerSessionPool { constructor(topology) { if (topology == null) { throw new Error('ServerSessionPool requires a topology'); } this.topology = topology; this.sessions = []; } /** * @returns {ServerSession} */ acquire() { const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; while (this.sessions.length) { const session = this.sessions.shift(); if (!session.hasTimedOut(sessionTimeoutMinutes)) { return session; } } return new ServerSession(); } /** * * @param {*} session */ release(session) { const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; while (this.sessions.length) { const session = this.sessions[this.sessions.length - 1]; if (session.hasTimedOut(sessionTimeoutMinutes)) { this.sessions.pop(); } else { break; } } if (!session.hasTimedOut(sessionTimeoutMinutes)) { this.sessions.unshift(session); } } } module.exports = { ClientSession: ClientSession, ServerSession: ServerSession, ServerSessionPool: ServerSessionPool }; },{"./connection/utils":357,"./utils":368,"events":316}],361:[function(require,module,exports){ 'use strict'; const inherits = require('util').inherits, f = require('util').format, EventEmitter = require('events').EventEmitter, BasicCursor = require('../cursor'), Logger = require('../connection/logger'), retrieveBSON = require('../connection/utils').retrieveBSON, MongoError = require('../error').MongoError, errors = require('../error'), Server = require('./server'), clone = require('./shared').clone, diff = require('./shared').diff, cloneOptions = require('./shared').cloneOptions, createClientInfo = require('./shared').createClientInfo, SessionMixins = require('./shared').SessionMixins, isRetryableWritesSupported = require('./shared').isRetryableWritesSupported, getNextTransactionNumber = require('./shared').getNextTransactionNumber; const BSON = retrieveBSON(); /** * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is * used to construct connections. * * @example * var Mongos = require('mongodb-core').Mongos * , ReadPreference = require('mongodb-core').ReadPreference * , assert = require('assert'); * * var server = new Mongos([{host: 'localhost', port: 30000}]); * // Wait for the connection event * server.on('connect', function(server) { * server.destroy(); * }); * * // Start connecting * server.connect(); */ var MongoCR = require('../auth/mongocr'), X509 = require('../auth/x509'), Plain = require('../auth/plain'), GSSAPI = require('../auth/gssapi'), SSPI = require('../auth/sspi'), ScramSHA1 = require('../auth/scram'); // // States var DISCONNECTED = 'disconnected'; var CONNECTING = 'connecting'; var CONNECTED = 'connected'; var UNREFERENCED = 'unreferenced'; var DESTROYED = 'destroyed'; function stateTransition(self, newState) { var legalTransitions = { disconnected: [CONNECTING, DESTROYED, DISCONNECTED], connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], unreferenced: [UNREFERENCED, DESTROYED], destroyed: [DESTROYED] }; // Get current state var legalStates = legalTransitions[self.state]; if (legalStates && legalStates.indexOf(newState) !== -1) { self.state = newState; } else { self.logger.error( f( 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', self.id, self.state, newState, legalStates ) ); } } // // ReplSet instance id var id = 1; var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; /** * Creates a new Mongos instance * @class * @param {array} seedlist A list of seeds for the replicaset * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors * @param {number} [options.size=5] Server connection pool size * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting * @param {number} [options.socketTimeout=0] TCP Socket timeout setting * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed * @param {boolean} [options.ssl=false] Use SSL for connection * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {Buffer} [options.ca] SSL Certificate store binary buffer * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer * @param {Buffer} [options.cert] SSL Certificate binary buffer * @param {Buffer} [options.key] SSL Key file binary buffer * @param {string} [options.passphrase] SSL Certificate pass phrase * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @return {Mongos} A cursor instance * @fires Mongos#connect * @fires Mongos#reconnect * @fires Mongos#joined * @fires Mongos#left * @fires Mongos#failed * @fires Mongos#fullsetup * @fires Mongos#all * @fires Mongos#serverHeartbeatStarted * @fires Mongos#serverHeartbeatSucceeded * @fires Mongos#serverHeartbeatFailed * @fires Mongos#topologyOpening * @fires Mongos#topologyClosed * @fires Mongos#topologyDescriptionChanged * @property {string} type the topology type. * @property {string} parserType the parser type used (c++ or js). */ var Mongos = function(seedlist, options) { options = options || {}; // Get replSet Id this.id = id++; // Internal state this.s = { options: Object.assign({}, options), // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // Logger instance logger: Logger('Mongos', options), // Seedlist seedlist: seedlist, // Ha interval haInterval: options.haInterval ? options.haInterval : 10000, // Disconnect handler disconnectHandler: options.disconnectHandler, // Server selection index index: 0, // Connect function options passed in connectOptions: {}, // Are we running in debug mode debug: typeof options.debug === 'boolean' ? options.debug : false, // localThresholdMS localThresholdMS: options.localThresholdMS || 15, // Client info clientInfo: createClientInfo(options), // Authentication context authenticationContexts: [] }; // Set the client info this.s.options.clientInfo = createClientInfo(options); // Log info warning if the socketTimeout < haInterval as it will cause // a lot of recycled connections to happen. if ( this.s.logger.isWarn() && this.s.options.socketTimeout !== 0 && this.s.options.socketTimeout < this.s.haInterval ) { this.s.logger.warn( f( 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', this.s.options.socketTimeout, this.s.haInterval ) ); } // All the authProviders this.authProviders = options.authProviders || { mongocr: new MongoCR(this.s.bson), x509: new X509(this.s.bson), plain: new Plain(this.s.bson), gssapi: new GSSAPI(this.s.bson), sspi: new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson) }; // Disconnected state this.state = DISCONNECTED; // Current proxies we are connecting to this.connectingProxies = []; // Currently connected proxies this.connectedProxies = []; // Disconnected proxies this.disconnectedProxies = []; // Are we authenticating this.authenticating = false; // Index of proxy to run operations against this.index = 0; // High availability timeout id this.haTimeoutId = null; // Last ismaster this.ismaster = null; // Description of the Replicaset this.topologyDescription = { topologyType: 'Unknown', servers: [] }; // Highest clusterTime seen in responses from the current deployment this.clusterTime = null; // Add event listener EventEmitter.call(this); }; inherits(Mongos, EventEmitter); Object.assign(Mongos.prototype, SessionMixins); Object.defineProperty(Mongos.prototype, 'type', { enumerable: true, get: function() { return 'mongos'; } }); Object.defineProperty(Mongos.prototype, 'parserType', { enumerable: true, get: function() { return BSON.native ? 'c++' : 'js'; } }); Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { enumerable: true, get: function() { if (!this.ismaster) return null; return this.ismaster.logicalSessionTimeoutMinutes || null; } }); /** * Emit event if it exists * @method */ function emitSDAMEvent(self, event, description) { if (self.listeners(event).length > 0) { self.emit(event, description); } } /** * Initiate server connect * @method * @param {array} [options.auth=null] Array of auth options to apply on connect */ Mongos.prototype.connect = function(options) { var self = this; // Add any connect level options to the internal state this.s.connectOptions = options || {}; // Set connecting state stateTransition(this, CONNECTING); // Create server instances var servers = this.s.seedlist.map(function(x) { return new Server( Object.assign({}, self.s.options, x, { authProviders: self.authProviders, reconnect: false, monitoring: false, parent: self, clientInfo: clone(self.s.clientInfo) }) ); }); const serverDescriptionChangedCallback = event => { self.emit('serverDescriptionChanged', event); }; servers.forEach(function(server) { server.on('serverDescriptionChanged', serverDescriptionChangedCallback); server.on('destroy', () => server.removeListener('serverDescriptionChanged', serverDescriptionChangedCallback) ); }); // Emit the topology opening event emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); // Start all server connections connectProxies(self, servers); }; function handleEvent(self) { return function() { if (self.state === DESTROYED) return; // Move to list of disconnectedProxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); // Emit the initial topology emitTopologyDescriptionChanged(self); // Emit the left signal self.emit('left', 'mongos', this); // Emit the sdam event self.emit('serverClosed', { topologyId: self.id, address: this.name }); }; } function handleInitialConnectEvent(self, event) { return function() { var _this = this; // Destroy the instance if (self.state === DESTROYED) { // Emit the initial topology emitTopologyDescriptionChanged(self); // Move from connectingProxies moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); return this.destroy(); } // Check the type of server if (event === 'connect') { // Do we have authentication contexts that need to be applied applyAuthenticationContexts(self, _this, function() { // Get last known ismaster self.ismaster = _this.lastIsMaster(); // Is this not a proxy, remove t if (self.ismaster.msg === 'isdbgrid') { // Add to the connectd list for (var i = 0; i < self.connectedProxies.length; i++) { if (self.connectedProxies[i].name === _this.name) { // Move from connectingProxies moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); // Emit the initial topology emitTopologyDescriptionChanged(self); _this.destroy(); return self.emit('failed', _this); } } // Remove the handlers for (i = 0; i < handlers.length; i++) { _this.removeAllListeners(handlers[i]); } // Add stable state handlers _this.on('error', handleEvent(self, 'error')); _this.on('close', handleEvent(self, 'close')); _this.on('timeout', handleEvent(self, 'timeout')); _this.on('parseError', handleEvent(self, 'parseError')); // Move from connecting proxies connected moveServerFrom(self.connectingProxies, self.connectedProxies, _this); // Emit the joined event self.emit('joined', 'mongos', _this); } else { // Print warning if we did not find a mongos proxy if (self.s.logger.isWarn()) { var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; // We have a standalone server if (!self.ismaster.hosts) { message = 'expected mongos proxy, but found standalone mongod for server %s'; } self.s.logger.warn(f(message, _this.name)); } // This is not a mongos proxy, remove it completely removeProxyFrom(self.connectingProxies, _this); // Emit the left event self.emit('left', 'server', _this); // Emit failed event self.emit('failed', _this); } }); } else { moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); // Emit the left event self.emit('left', 'mongos', this); // Emit failed event self.emit('failed', this); } // Emit the initial topology emitTopologyDescriptionChanged(self); // Trigger topologyMonitor if (self.connectingProxies.length === 0) { // Emit connected if we are connected if (self.connectedProxies.length > 0 && self.state === CONNECTING) { // Set the state to connected stateTransition(self, CONNECTED); // Emit the connect event self.emit('connect', self); self.emit('fullsetup', self); self.emit('all', self); } else if (self.disconnectedProxies.length === 0) { // Print warning if we did not find a mongos proxy if (self.s.logger.isWarn()) { self.s.logger.warn( f('no mongos proxies found in seed list, did you mean to connect to a replicaset') ); } // Emit the error that no proxies were found return self.emit('error', new MongoError('no mongos proxies found in seed list')); } // Topology monitor topologyMonitor(self, { firstConnect: true }); } }; } function connectProxies(self, servers) { // Update connectingProxies self.connectingProxies = self.connectingProxies.concat(servers); // Index used to interleaf the server connects, avoiding // runtime issues on io constrained vm's var timeoutInterval = 0; function connect(server, timeoutInterval) { setTimeout(function() { // Emit opening server event self.emit('serverOpening', { topologyId: self.id, address: server.name }); // Emit the initial topology emitTopologyDescriptionChanged(self); // Add event handlers server.once('close', handleInitialConnectEvent(self, 'close')); server.once('timeout', handleInitialConnectEvent(self, 'timeout')); server.once('parseError', handleInitialConnectEvent(self, 'parseError')); server.once('error', handleInitialConnectEvent(self, 'error')); server.once('connect', handleInitialConnectEvent(self, 'connect')); // Start connection server.connect(self.s.connectOptions); }, timeoutInterval); } // Start all the servers while (servers.length > 0) { connect(servers.shift(), timeoutInterval++); } } function pickProxy(self) { // Get the currently connected Proxies var connectedProxies = self.connectedProxies.slice(0); // Set lower bound var lowerBoundLatency = Number.MAX_VALUE; // Determine the lower bound for the Proxies for (var i = 0; i < connectedProxies.length; i++) { if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { lowerBoundLatency = connectedProxies[i].lastIsMasterMS; } } // Filter out the possible servers connectedProxies = connectedProxies.filter(function(server) { if ( server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && server.isConnected() ) { return true; } }); // We have no connectedProxies pick first of the connected ones if (connectedProxies.length === 0) { return self.connectedProxies[0]; } // Get proxy var proxy = connectedProxies[self.index % connectedProxies.length]; // Update the index self.index = (self.index + 1) % connectedProxies.length; // Return the proxy return proxy; } function moveServerFrom(from, to, proxy) { for (var i = 0; i < from.length; i++) { if (from[i].name === proxy.name) { from.splice(i, 1); } } for (i = 0; i < to.length; i++) { if (to[i].name === proxy.name) { to.splice(i, 1); } } to.push(proxy); } function removeProxyFrom(from, proxy) { for (var i = 0; i < from.length; i++) { if (from[i].name === proxy.name) { from.splice(i, 1); } } } function reconnectProxies(self, proxies, callback) { // Count lefts var count = proxies.length; // Handle events var _handleEvent = function(self, event) { return function() { var _self = this; count = count - 1; // Destroyed if (self.state === DESTROYED || self.state === UNREFERENCED) { moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); // Return destroy return this.destroy(); } if (event === 'connect' && !self.authenticating) { // Do we have authentication contexts that need to be applied applyAuthenticationContexts(self, _self, function() { // Destroyed if (self.state === DESTROYED || self.state === UNREFERENCED) { moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); return _self.destroy(); } // Remove the handlers for (var i = 0; i < handlers.length; i++) { _self.removeAllListeners(handlers[i]); } // Add stable state handlers _self.on('error', handleEvent(self, 'error')); _self.on('close', handleEvent(self, 'close')); _self.on('timeout', handleEvent(self, 'timeout')); _self.on('parseError', handleEvent(self, 'parseError')); // Move to the connected servers moveServerFrom(self.disconnectedProxies, self.connectedProxies, _self); // Emit topology Change emitTopologyDescriptionChanged(self); // Emit joined event self.emit('joined', 'mongos', _self); }); } else if (event === 'connect' && self.authenticating) { // Move from connectingProxies moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); this.destroy(); } // Are we done finish up callback if (count === 0) { callback(); } }; }; // No new servers if (count === 0) { return callback(); } // Execute method function execute(_server, i) { setTimeout(function() { // Destroyed if (self.state === DESTROYED || self.state === UNREFERENCED) { return; } // Create a new server instance var server = new Server( Object.assign({}, self.s.options, { host: _server.name.split(':')[0], port: parseInt(_server.name.split(':')[1], 10), authProviders: self.authProviders, reconnect: false, monitoring: false, parent: self, clientInfo: clone(self.s.clientInfo) }) ); // Relay the server description change server.on('serverDescriptionChanged', function(event) { self.emit('serverDescriptionChanged', event); }); // Emit opening server event self.emit('serverOpening', { topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, address: server.name }); // Add temp handlers server.once('connect', _handleEvent(self, 'connect')); server.once('close', _handleEvent(self, 'close')); server.once('timeout', _handleEvent(self, 'timeout')); server.once('error', _handleEvent(self, 'error')); server.once('parseError', _handleEvent(self, 'parseError')); // Connect to proxy server.connect(self.s.connectOptions); }, i); } // Create new instances for (var i = 0; i < proxies.length; i++) { execute(proxies[i], i); } } function applyAuthenticationContexts(self, server, callback) { if (self.s.authenticationContexts.length === 0) { return callback(); } // Copy contexts to ensure no modificiation in the middle of // auth process. var authContexts = self.s.authenticationContexts.slice(0); // Apply one of the contexts function applyAuth(authContexts, server, callback) { if (authContexts.length === 0) return callback(); // Get the first auth context var authContext = authContexts.shift(); // Copy the params var customAuthContext = authContext.slice(0); // Push our callback handler customAuthContext.push(function(/* err */) { applyAuth(authContexts, server, callback); }); // Attempt authentication server.auth.apply(server, customAuthContext); } // Apply all auth contexts applyAuth(authContexts, server, callback); } function topologyMonitor(self, options) { options = options || {}; // Set momitoring timeout self.haTimeoutId = setTimeout(function() { if (self.state === DESTROYED || self.state === UNREFERENCED) return; // If we have a primary and a disconnect handler, execute // buffered operations if (self.isConnected() && self.s.disconnectHandler) { self.s.disconnectHandler.execute(); } // Get the connectingServers var proxies = self.connectedProxies.slice(0); // Get the count var count = proxies.length; // If the count is zero schedule a new fast function pingServer(_self, _server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); // Execute ismaster _server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { // Move from connectingProxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); _server.destroy(); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name }); // Move from connected proxies to disconnected proxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); } else { // Update the server ismaster _server.ismaster = r.result; _server.lastIsMasterMS = latencyMS; // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name }); } cb(err, r); } ); } // No proxies initiate monitor again if (proxies.length === 0) { // Emit close event if any listeners registered if (self.listeners('close').length > 0 && self.state === CONNECTING) { self.emit('error', new MongoError('no mongos proxy available')); } else { self.emit('close', self); } // Attempt to connect to any unknown servers return reconnectProxies(self, self.disconnectedProxies, function() { if (self.state === DESTROYED || self.state === UNREFERENCED) return; // Are we connected ? emit connect event if (self.state === CONNECTING && options.firstConnect) { self.emit('connect', self); self.emit('fullsetup', self); self.emit('all', self); } else if (self.isConnected()) { self.emit('reconnect', self); } else if (!self.isConnected() && self.listeners('close').length > 0) { self.emit('close', self); } // Perform topology monitor topologyMonitor(self); }); } // Ping all servers for (var i = 0; i < proxies.length; i++) { pingServer(self, proxies[i], function() { count = count - 1; if (count === 0) { if (self.state === DESTROYED || self.state === UNREFERENCED) return; // Attempt to connect to any unknown servers reconnectProxies(self, self.disconnectedProxies, function() { if (self.state === DESTROYED || self.state === UNREFERENCED) return; // Perform topology monitor topologyMonitor(self); }); } }); } }, self.s.haInterval); } /** * Returns the last known ismaster document for this server * @method * @return {object} */ Mongos.prototype.lastIsMaster = function() { return this.ismaster; }; /** * Unref all connections belong to this server * @method */ Mongos.prototype.unref = function() { // Transition state stateTransition(this, UNREFERENCED); // Get all proxies var proxies = this.connectedProxies.concat(this.connectingProxies); proxies.forEach(function(x) { x.unref(); }); clearTimeout(this.haTimeoutId); }; /** * Destroy the server connection * @param {boolean} [options.force=false] Force destroy the pool * @method */ Mongos.prototype.destroy = function(options) { var self = this; // Transition state stateTransition(this, DESTROYED); // Get all proxies var proxies = this.connectedProxies.concat(this.connectingProxies); // Clear out any monitoring process if (this.haTimeoutId) clearTimeout(this.haTimeoutId); // Clear out authentication contexts this.s.authenticationContexts = []; // Destroy all connecting servers proxies.forEach(function(x) { // Emit the sdam event self.emit('serverClosed', { topologyId: self.id, address: x.name }); // Destroy the server x.destroy(options); // Move to list of disconnectedProxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, x); }); // Emit the final topology change emitTopologyDescriptionChanged(self); // Emit toplogy closing event emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); }; /** * Figure out if the server is connected * @method * @return {boolean} */ Mongos.prototype.isConnected = function() { return this.connectedProxies.length > 0; }; /** * Figure out if the server instance was destroyed by calling destroy * @method * @return {boolean} */ Mongos.prototype.isDestroyed = function() { return this.state === DESTROYED; }; // // Operations // // Execute write operation var executeWriteOperation = function(self, op, ns, ops, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Pick a server let server = pickProxy(self); // No server found error out if (!server) return callback(new MongoError('no mongos proxy available')); if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) { // Execute the command return server[op](ns, ops, options, callback); } // increment and assign txnNumber options.txnNumber = getNextTransactionNumber(options.session); server[op](ns, ops, options, (err, result) => { if (!err) return callback(null, result); if (!(err instanceof errors.MongoNetworkError) && !err.message.match(/not master/)) { return callback(err); } // Pick another server server = pickProxy(self); // No server found error out with original error if (!server || !isRetryableWritesSupported(server)) { return callback(err); } // rerun the operation server[op](ns, ops, options, callback); }); }; /** * Insert one or more documents * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of documents to insert * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {boolean} [options.retryWrites] Enable retryable writes for this operation * @param {opResultCallback} callback A callback function */ Mongos.prototype.insert = function(ns, ops, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Not connected but we have a disconnecthandler if (!this.isConnected() && this.s.disconnectHandler != null) { return this.s.disconnectHandler.add('insert', ns, ops, options, callback); } // No mongos proxy available if (!this.isConnected()) { return callback(new MongoError('no mongos proxy available')); } // Execute write operation executeWriteOperation(this, 'insert', ns, ops, options, callback); }; /** * Perform one or more update operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of updates * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {boolean} [options.retryWrites] Enable retryable writes for this operation * @param {opResultCallback} callback A callback function */ Mongos.prototype.update = function(ns, ops, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Not connected but we have a disconnecthandler if (!this.isConnected() && this.s.disconnectHandler != null) { return this.s.disconnectHandler.add('update', ns, ops, options, callback); } // No mongos proxy available if (!this.isConnected()) { return callback(new MongoError('no mongos proxy available')); } // Execute write operation executeWriteOperation(this, 'update', ns, ops, options, callback); }; /** * Perform one or more remove operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of removes * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {boolean} [options.retryWrites] Enable retryable writes for this operation * @param {opResultCallback} callback A callback function */ Mongos.prototype.remove = function(ns, ops, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Not connected but we have a disconnecthandler if (!this.isConnected() && this.s.disconnectHandler != null) { return this.s.disconnectHandler.add('remove', ns, ops, options, callback); } // No mongos proxy available if (!this.isConnected()) { return callback(new MongoError('no mongos proxy available')); } // Execute write operation executeWriteOperation(this, 'remove', ns, ops, options, callback); }; /** * Execute a command * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cmd The command hash * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Connection} [options.connection] Specify connection object to execute command against * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ Mongos.prototype.command = function(ns, cmd, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); var self = this; // Pick a proxy var server = pickProxy(self); // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { return this.s.disconnectHandler.add('command', ns, cmd, options, callback); } // No server returned we had an error if (server == null) { return callback(new MongoError('no mongos proxy available')); } // Cloned options var clonedOptions = cloneOptions(options); clonedOptions.topology = self; // Execute the command server.command(ns, cmd, clonedOptions, callback); }; /** * Get a new cursor * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId * @param {object} [options] Options for the cursor * @param {object} [options.batchSize=0] Batchsize for the operation * @param {array} [options.documents=[]] Initial documents list for cursor * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {object} [options.topology] The internal topology of the created cursor * @returns {Cursor} */ Mongos.prototype.cursor = function(ns, cmd, options) { options = options || {}; const topology = options.topology || this; // Set up final cursor type var FinalCursor = options.cursorFactory || this.s.Cursor; // Return the cursor return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); }; /** * Authenticate using a specified mechanism * @method * @param {string} mechanism The Auth mechanism we are invoking * @param {string} db The db we are invoking the mechanism against * @param {...object} param Parameters for the specific mechanism * @param {authResultCallback} callback A callback function */ Mongos.prototype.auth = function(mechanism, db) { var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); var self = this; var args = Array.prototype.slice.call(arguments, 2); var callback = args.pop(); var currentContextIndex = 0; // If we don't have the mechanism fail if (this.authProviders[mechanism] == null && mechanism !== 'default') { return callback(new MongoError(f('auth provider %s does not exist', mechanism))); } // Are we already authenticating, throw if (this.authenticating) { return callback(new MongoError('authentication or logout allready in process')); } // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if (!self.isConnected() && self.s.disconnectHandler != null) { return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); } // Set to authenticating this.authenticating = true; // All errors var errors = []; // Get all the servers var servers = this.connectedProxies.slice(0); // No servers return if (servers.length === 0) { this.authenticating = false; callback(null, true); } // Authenticate function auth(server) { // Arguments without a callback var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); // Create arguments var finalArguments = argsWithoutCallback.concat([ function(err) { count = count - 1; // Save all the errors if (err) errors.push({ name: server.name, err: err }); // We are done if (count === 0) { // Auth is done self.authenticating = false; // Return the auth error if (errors.length) { // Remove the entry from the stored authentication contexts self.s.authenticationContexts.splice(currentContextIndex, 0); // Return error return callback( new MongoError({ message: 'authentication fail', errors: errors }), false ); } // Successfully authenticated session callback(null, self); } } ]); // Execute the auth only against non arbiter servers if (!server.lastIsMaster().arbiterOnly) { server.auth.apply(server, finalArguments); } } // Save current context index currentContextIndex = this.s.authenticationContexts.length; // Store the auth context and return the last index this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); // Get total count var count = servers.length; // Authenticate against all servers while (servers.length > 0) { auth(servers.shift()); } }; /** * Logout from a database * @method * @param {string} db The db we are logging out from * @param {authResultCallback} callback A callback function */ Mongos.prototype.logout = function(dbName, callback) { var self = this; // Are we authenticating or logging out, throw if (this.authenticating) { throw new MongoError('authentication or logout allready in process'); } // Ensure no new members are processed while logging out this.authenticating = true; // Remove from all auth providers (avoid any reaplication of the auth details) var providers = Object.keys(this.authProviders); for (var i = 0; i < providers.length; i++) { this.authProviders[providers[i]].logout(dbName); } // Now logout all the servers var servers = this.connectedProxies.slice(0); var count = servers.length; if (count === 0) return callback(); var errors = []; function logoutServer(_server, cb) { _server.logout(dbName, function(err) { if (err) errors.push({ name: _server.name, err: err }); cb(); }); } // Execute logout on all server instances for (i = 0; i < servers.length; i++) { logoutServer(servers[i], function() { count = count - 1; if (count === 0) { // Do not block new operations self.authenticating = false; // If we have one or more errors if (errors.length) return callback( new MongoError({ message: f('logout failed against db %s', dbName), errors: errors }), false ); // No errors callback(); } }); } }; /** * Get server * @method * @return {Server} */ Mongos.prototype.getServer = function() { var server = pickProxy(this); if (this.s.debug) this.emit('pickedServer', null, server); return server; }; /** * Get a direct connection * @method * @return {Connection} */ Mongos.prototype.getConnection = function() { var server = this.getServer(); if (server) return server.getConnection(); }; /** * All raw connections * @method * @return {Connection[]} */ Mongos.prototype.connections = function() { var connections = []; for (var i = 0; i < this.connectedProxies.length; i++) { connections = connections.concat(this.connectedProxies[i].connections()); } return connections; }; function emitTopologyDescriptionChanged(self) { if (self.listeners('topologyDescriptionChanged').length > 0) { var topology = 'Unknown'; if (self.connectedProxies.length > 0) { topology = 'Sharded'; } // Generate description var description = { topologyType: topology, servers: [] }; // All proxies var proxies = self.disconnectedProxies.concat(self.connectingProxies); // Add all the disconnected proxies description.servers = description.servers.concat( proxies.map(function(x) { var description = x.getDescription(); description.type = 'Unknown'; return description; }) ); // Add all the connected proxies description.servers = description.servers.concat( self.connectedProxies.map(function(x) { var description = x.getDescription(); description.type = 'Mongos'; return description; }) ); // Get the diff var diffResult = diff(self.topologyDescription, description); // Create the result var result = { topologyId: self.id, previousDescription: self.topologyDescription, newDescription: description, diff: diffResult }; // Emit the topologyDescription change if (diffResult.servers.length > 0) { self.emit('topologyDescriptionChanged', result); } // Set the new description self.topologyDescription = description; } } /** * A mongos connect event, used to verify that the connection is up and running * * @event Mongos#connect * @type {Mongos} */ /** * A mongos reconnect event, used to verify that the mongos topology has reconnected * * @event Mongos#reconnect * @type {Mongos} */ /** * A mongos fullsetup event, used to signal that all topology members have been contacted. * * @event Mongos#fullsetup * @type {Mongos} */ /** * A mongos all event, used to signal that all topology members have been contacted. * * @event Mongos#all * @type {Mongos} */ /** * A server member left the mongos list * * @event Mongos#left * @type {Mongos} * @param {string} type The type of member that left (mongos) * @param {Server} server The server object that left */ /** * A server member joined the mongos list * * @event Mongos#joined * @type {Mongos} * @param {string} type The type of member that left (mongos) * @param {Server} server The server object that joined */ /** * A server opening SDAM monitoring event * * @event Mongos#serverOpening * @type {object} */ /** * A server closed SDAM monitoring event * * @event Mongos#serverClosed * @type {object} */ /** * A server description SDAM change monitoring event * * @event Mongos#serverDescriptionChanged * @type {object} */ /** * A topology open SDAM event * * @event Mongos#topologyOpening * @type {object} */ /** * A topology closed SDAM event * * @event Mongos#topologyClosed * @type {object} */ /** * A topology structure SDAM change event * * @event Mongos#topologyDescriptionChanged * @type {object} */ /** * A topology serverHeartbeatStarted SDAM event * * @event Mongos#serverHeartbeatStarted * @type {object} */ /** * A topology serverHeartbeatFailed SDAM event * * @event Mongos#serverHeartbeatFailed * @type {object} */ /** * A topology serverHeartbeatSucceeded SDAM change event * * @event Mongos#serverHeartbeatSucceeded * @type {object} */ module.exports = Mongos; },{"../auth/gssapi":346,"../auth/mongocr":347,"../auth/plain":348,"../auth/scram":349,"../auth/sspi":350,"../auth/x509":351,"../connection/logger":355,"../connection/utils":357,"../cursor":358,"../error":359,"./server":365,"./shared":366,"events":316,"util":563}],362:[function(require,module,exports){ 'use strict'; /** * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is * used to construct connections. * * @example * const ReplSet = require('mongodb-core').ReplSet, * ReadPreference = require('mongodb-core').ReadPreference, * assert = require('assert'); * * const server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); * // Wait for the connection event * server.on('connect', function(server) { * const cursor = server.cursor( * 'db.test', * { find: 'db.test', query: {} }, * { readPreference: new ReadPreference('secondary') } * ); * * cursor.next(function(err, doc) { * server.destroy(); * }); * }); * * // Start connecting * server.connect(); */ /** * Creates a new Pool instance * @class * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) * @param {array} tags The tags object * @param {object} [options] Additional read preference options * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. * @property {string} mode The read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) * @property {array} tags The tags object * @property {object} options Additional read preference options * @property {number} maxStalenessSeconds MaxStalenessSeconds value for the read preference * @return {ReadPreference} */ const ReadPreference = function(mode, tags, options) { this.mode = mode; this.tags = tags; this.options = options; // Add the maxStalenessSeconds value to the read Preference if (this.options && this.options.maxStalenessSeconds != null) { this.options = options; this.maxStalenessSeconds = this.options.maxStalenessSeconds >= 0 ? this.options.maxStalenessSeconds : null; } else if (tags && typeof tags === 'object') { (this.options = tags), (tags = null); } }; // Support the deprecated `preference` property introduced in the porcelain layer Object.defineProperty(ReadPreference.prototype, 'preference', { enumerable: true, get: function() { return this.mode; } }); /** * Read preference mode constants */ ReadPreference.PRIMARY = 'primary'; ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; ReadPreference.SECONDARY = 'secondary'; ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; ReadPreference.NEAREST = 'nearest'; const VALID_MODES = [ ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST, true, false, null ]; /** * Validate if a mode is legal * * @method * @param {string} mode The string representing the read preference mode. * @return {boolean} */ ReadPreference.isValid = function(mode) { return VALID_MODES.indexOf(mode) !== -1; }; /** * Validate if a mode is legal * * @method * @param {string} mode The string representing the read preference mode. * @return {boolean} */ ReadPreference.prototype.isValid = function(mode) { return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); }; const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; /** * This needs slaveOk bit set * @method * @return {boolean} */ ReadPreference.prototype.slaveOk = function() { return needSlaveOk.indexOf(this.mode) !== -1; }; /** * Are the two read preference equal * @method * @return {boolean} */ ReadPreference.prototype.equals = function(readPreference) { return readPreference.mode === this.mode; }; /** * Return JSON representation * @method * @return {Object} */ ReadPreference.prototype.toJSON = function() { const readPreference = { mode: this.mode }; if (Array.isArray(this.tags)) readPreference.tags = this.tags; if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; return readPreference; }; /** * Primary read preference * @method * @return {ReadPreference} */ ReadPreference.primary = new ReadPreference('primary'); /** * Primary Preferred read preference * @method * @return {ReadPreference} */ ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); /** * Secondary read preference * @method * @return {ReadPreference} */ ReadPreference.secondary = new ReadPreference('secondary'); /** * Secondary Preferred read preference * @method * @return {ReadPreference} */ ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); /** * Nearest read preference * @method * @return {ReadPreference} */ ReadPreference.nearest = new ReadPreference('nearest'); module.exports = ReadPreference; },{}],363:[function(require,module,exports){ (function (process){ 'use strict'; var inherits = require('util').inherits, f = require('util').format, EventEmitter = require('events').EventEmitter, ReadPreference = require('./read_preference'), BasicCursor = require('../cursor'), retrieveBSON = require('../connection/utils').retrieveBSON, Logger = require('../connection/logger'), MongoError = require('../error').MongoError, errors = require('../error'), Server = require('./server'), ReplSetState = require('./replset_state'), clone = require('./shared').clone, Timeout = require('./shared').Timeout, Interval = require('./shared').Interval, createClientInfo = require('./shared').createClientInfo, SessionMixins = require('./shared').SessionMixins, isRetryableWritesSupported = require('./shared').isRetryableWritesSupported, getNextTransactionNumber = require('./shared').getNextTransactionNumber; var MongoCR = require('../auth/mongocr'), X509 = require('../auth/x509'), Plain = require('../auth/plain'), GSSAPI = require('../auth/gssapi'), SSPI = require('../auth/sspi'), ScramSHA1 = require('../auth/scram'); var BSON = retrieveBSON(); // // States var DISCONNECTED = 'disconnected'; var CONNECTING = 'connecting'; var CONNECTED = 'connected'; var UNREFERENCED = 'unreferenced'; var DESTROYED = 'destroyed'; function stateTransition(self, newState) { var legalTransitions = { disconnected: [CONNECTING, DESTROYED, DISCONNECTED], connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], unreferenced: [UNREFERENCED, DESTROYED], destroyed: [DESTROYED] }; // Get current state var legalStates = legalTransitions[self.state]; if (legalStates && legalStates.indexOf(newState) !== -1) { self.state = newState; } else { self.s.logger.error( f( 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', self.id, self.state, newState, legalStates ) ); } } // // ReplSet instance id var id = 1; var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; /** * Creates a new Replset instance * @class * @param {array} seedlist A list of seeds for the replicaset * @param {boolean} options.setName The Replicaset set name * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry * @param {boolean} [options.emitError=false] Server will emit errors events * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors * @param {number} [options.size=5] Server connection pool size * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting * @param {number} [options.socketTimeout=0] TCP Socket timeout setting * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed * @param {boolean} [options.ssl=false] Use SSL for connection * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {Buffer} [options.ca] SSL Certificate store binary buffer * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer * @param {Buffer} [options.cert] SSL Certificate binary buffer * @param {Buffer} [options.key] SSL Key file binary buffer * @param {string} [options.passphrase] SSL Certificate pass phrase * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @return {ReplSet} A cursor instance * @fires ReplSet#connect * @fires ReplSet#ha * @fires ReplSet#joined * @fires ReplSet#left * @fires ReplSet#failed * @fires ReplSet#fullsetup * @fires ReplSet#all * @fires ReplSet#error * @fires ReplSet#serverHeartbeatStarted * @fires ReplSet#serverHeartbeatSucceeded * @fires ReplSet#serverHeartbeatFailed * @fires ReplSet#topologyOpening * @fires ReplSet#topologyClosed * @fires ReplSet#topologyDescriptionChanged * @property {string} type the topology type. * @property {string} parserType the parser type used (c++ or js). */ var ReplSet = function(seedlist, options) { var self = this; options = options || {}; // Validate seedlist if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); // Validate list if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); // Validate entries seedlist.forEach(function(e) { if (typeof e.host !== 'string' || typeof e.port !== 'number') throw new MongoError('seedlist entry must contain a host and port'); }); // Add event listener EventEmitter.call(this); // Get replSet Id this.id = id++; // Get the localThresholdMS var localThresholdMS = options.localThresholdMS || 15; // Backward compatibility if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; // Create a logger var logger = Logger('ReplSet', options); // Internal state this.s = { options: Object.assign({}, options), // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // Logger instance logger: logger, // Seedlist seedlist: seedlist, // Replicaset state replicaSetState: new ReplSetState({ id: this.id, setName: options.setName, acceptableLatency: localThresholdMS, heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, logger: logger }), // Current servers we are connecting to connectingServers: [], // Ha interval haInterval: options.haInterval ? options.haInterval : 10000, // Minimum heartbeat frequency used if we detect a server close minHeartbeatFrequencyMS: 500, // Disconnect handler disconnectHandler: options.disconnectHandler, // Server selection index index: 0, // Connect function options passed in connectOptions: {}, // Are we running in debug mode debug: typeof options.debug === 'boolean' ? options.debug : false, // Client info clientInfo: createClientInfo(options), // Authentication context authenticationContexts: [] }; // Add handler for topology change this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { self.emit('topologyDescriptionChanged', r); }); // Log info warning if the socketTimeout < haInterval as it will cause // a lot of recycled connections to happen. if ( this.s.logger.isWarn() && this.s.options.socketTimeout !== 0 && this.s.options.socketTimeout < this.s.haInterval ) { this.s.logger.warn( f( 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', this.s.options.socketTimeout, this.s.haInterval ) ); } // All the authProviders this.authProviders = options.authProviders || { mongocr: new MongoCR(this.s.bson), x509: new X509(this.s.bson), plain: new Plain(this.s.bson), gssapi: new GSSAPI(this.s.bson), sspi: new SSPI(this.s.bson), 'scram-sha-1': new ScramSHA1(this.s.bson) }; // Add forwarding of events from state handler var types = ['joined', 'left']; types.forEach(function(x) { self.s.replicaSetState.on(x, function(t, s) { self.emit(x, t, s); }); }); // Connect stat this.initialConnectState = { connect: false, fullsetup: false, all: false }; // Disconnected state this.state = DISCONNECTED; this.haTimeoutId = null; // Are we authenticating this.authenticating = false; // Last ismaster this.ismaster = null; // Contains the intervalId this.intervalIds = []; // Highest clusterTime seen in responses from the current deployment this.clusterTime = null; }; inherits(ReplSet, EventEmitter); Object.assign(ReplSet.prototype, SessionMixins); Object.defineProperty(ReplSet.prototype, 'type', { enumerable: true, get: function() { return 'replset'; } }); Object.defineProperty(ReplSet.prototype, 'parserType', { enumerable: true, get: function() { return BSON.native ? 'c++' : 'js'; } }); Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { enumerable: true, get: function() { return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; } }); function rexecuteOperations(self) { // If we have a primary and a disconnect handler, execute // buffered operations if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { self.s.disconnectHandler.execute(); } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { self.s.disconnectHandler.execute({ executePrimary: true }); } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { self.s.disconnectHandler.execute({ executeSecondary: true }); } } function connectNewServers(self, servers, callback) { // Count lefts var count = servers.length; var error = null; // Handle events var _handleEvent = function(self, event) { return function(err) { var _self = this; count = count - 1; // Destroyed if (self.state === DESTROYED || self.state === UNREFERENCED) { return this.destroy({ force: true }); } if (event === 'connect' && !self.authenticating) { // Destroyed if (self.state === DESTROYED || self.state === UNREFERENCED) { return _self.destroy({ force: true }); } // Do we have authentication contexts that need to be applied applyAuthenticationContexts(self, _self, function() { // Destroy the instance if (self.state === DESTROYED || self.state === UNREFERENCED) { return _self.destroy({ force: true }); } // Update the state var result = self.s.replicaSetState.update(_self); // Update the state with the new server if (result) { // Primary lastIsMaster store it if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { self.ismaster = _self.lastIsMaster(); } // Remove the handlers for (var i = 0; i < handlers.length; i++) { _self.removeAllListeners(handlers[i]); } // Add stable state handlers _self.on('error', handleEvent(self, 'error')); _self.on('close', handleEvent(self, 'close')); _self.on('timeout', handleEvent(self, 'timeout')); _self.on('parseError', handleEvent(self, 'parseError')); // Enalbe the monitoring of the new server monitorServer(_self.lastIsMaster().me, self, {}); // Rexecute any stalled operation rexecuteOperations(self); } else { _self.destroy({ force: true }); } }); } else if (event === 'connect' && self.authenticating) { this.destroy({ force: true }); } else if (event === 'error') { error = err; } // Rexecute any stalled operation rexecuteOperations(self); // Are we done finish up callback if (count === 0) { callback(error); } }; }; // No new servers if (count === 0) return callback(); // Execute method function execute(_server, i) { setTimeout(function() { // Destroyed if (self.state === DESTROYED || self.state === UNREFERENCED) { return; } // Create a new server instance var server = new Server( Object.assign({}, self.s.options, { host: _server.split(':')[0], port: parseInt(_server.split(':')[1], 10), authProviders: self.authProviders, reconnect: false, monitoring: false, parent: self, clientInfo: clone(self.s.clientInfo) }) ); // Add temp handlers server.once('connect', _handleEvent(self, 'connect')); server.once('close', _handleEvent(self, 'close')); server.once('timeout', _handleEvent(self, 'timeout')); server.once('error', _handleEvent(self, 'error')); server.once('parseError', _handleEvent(self, 'parseError')); // SDAM Monitoring events server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); server.connect(self.s.connectOptions); }, i); } // Create new instances for (var i = 0; i < servers.length; i++) { execute(servers[i], i); } } // Ping the server var pingServer = function(self, server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); // Execute ismaster // Set the socketTimeout for a monitoring message to a low number // Ensuring ismaster calls are timed out quickly server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { server.destroy({ force: true }); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // Set the last updatedTime var hrTime = process.hrtime(); // Calculate the last update time server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1] / 1000); // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: server.name }); // Remove server from the state self.s.replicaSetState.remove(server); } else { // Update the server ismaster server.ismaster = r.result; // Check if we have a lastWriteDate convert it to MS // and store on the server instance for later use if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); } // Do we have a brand new server if (server.lastIsMasterMS === -1) { server.lastIsMasterMS = latencyMS; } else if (server.lastIsMasterMS) { // After the first measurement, average RTT MUST be computed using an // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. // If the prior average is denoted old_rtt, then the new average (new_rtt) is // computed from a new RTT measurement (x) using the following formula: // alpha = 0.2 // new_rtt = alpha * x + (1 - alpha) * old_rtt server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; } if (self.s.replicaSetState.update(server)) { // Primary lastIsMaster store it if (server.lastIsMaster() && server.lastIsMaster().ismaster) { self.ismaster = server.lastIsMaster(); } } // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: server.name }); } // Calculate the staleness for this server self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); // Callback cb(err, r); } ); }; // Each server is monitored in parallel in their own timeout loop var monitorServer = function(host, self, options) { // If this is not the initial scan // Is this server already being monitoried, then skip monitoring if (!options.haInterval) { for (var i = 0; i < self.intervalIds.length; i++) { if (self.intervalIds[i].__host === host) { return; } } } // Get the haInterval var _process = options.haInterval ? Timeout : Interval; var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; // Create the interval var intervalId = new _process(function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { // clearInterval(intervalId); intervalId.stop(); return; } // Do we already have server connection available for this host var _server = self.s.replicaSetState.get(host); // Check if we have a known server connection and reuse if (_server) { // Ping the server return pingServer(self, _server, function(err) { if (err) { // NOTE: should something happen here? return; } if (self.state === DESTROYED || self.state === UNREFERENCED) { intervalId.stop(); return; } // Filter out all called intervaliIds self.intervalIds = self.intervalIds.filter(function(intervalId) { return intervalId.isRunning(); }); // Initial sweep if (_process === Timeout) { if ( self.state === CONNECTING && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Emit connected sign process.nextTick(function() { self.emit('connect', self); }); // Start topology interval check topologyMonitor(self, {}); } } else { if ( self.state === DISCONNECTED && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Rexecute any stalled operation rexecuteOperations(self); // Emit connected sign process.nextTick(function() { self.emit('reconnect', self); }); } } if ( self.initialConnectState.connect && !self.initialConnectState.fullsetup && self.s.replicaSetState.hasPrimaryAndSecondary() ) { // Set initial connect state self.initialConnectState.fullsetup = true; self.initialConnectState.all = true; process.nextTick(function() { self.emit('fullsetup', self); self.emit('all', self); }); } }); } }, _haInterval); // Start the interval intervalId.start(); // Add the intervalId host name intervalId.__host = host; // Add the intervalId to our list of intervalIds self.intervalIds.push(intervalId); }; function topologyMonitor(self, options) { if (self.state === DESTROYED || self.state === UNREFERENCED) return; options = options || {}; // Get the servers var servers = Object.keys(self.s.replicaSetState.set); // Get the haInterval var _process = options.haInterval ? Timeout : Interval; var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; if (_process === Timeout) { return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { // Don't emit errors if the connection was already if (self.state === DESTROYED || self.state === UNREFERENCED) { return; } if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { if (err) { return self.emit('error', err); } self.emit( 'error', new MongoError('no primary found in replicaset or invalid replica set name') ); return self.destroy({ force: true }); } else if ( !self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed ) { if (err) { return self.emit('error', err); } self.emit( 'error', new MongoError('no secondary found in replicaset or invalid replica set name') ); return self.destroy({ force: true }); } for (var i = 0; i < servers.length; i++) { monitorServer(servers[i], self, options); } }); } else { for (var i = 0; i < servers.length; i++) { monitorServer(servers[i], self, options); } } // Run the reconnect process function executeReconnect(self) { return function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { return; } connectNewServers(self, self.s.replicaSetState.unknownServers, function() { var monitoringFrequencey = self.s.replicaSetState.hasPrimary() ? _haInterval : self.s.minHeartbeatFrequencyMS; // Create a timeout self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); }); }; } // Decide what kind of interval to use var intervalTime = !self.s.replicaSetState.hasPrimary() ? self.s.minHeartbeatFrequencyMS : _haInterval; self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); } function addServerToList(list, server) { for (var i = 0; i < list.length; i++) { if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; } list.push(server); } function handleEvent(self, event) { return function() { if (self.state === DESTROYED || self.state === UNREFERENCED) return; // Debug log if (self.s.logger.isDebug()) { self.s.logger.debug( f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) ); } // Remove from the replicaset state self.s.replicaSetState.remove(this); // Are we in a destroyed state return if (self.state === DESTROYED || self.state === UNREFERENCED) return; // If no primary and secondary available if ( !self.s.replicaSetState.hasPrimary() && !self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed ) { stateTransition(self, DISCONNECTED); } else if (!self.s.replicaSetState.hasPrimary()) { stateTransition(self, DISCONNECTED); } addServerToList(self.s.connectingServers, this); }; } function applyAuthenticationContexts(self, server, callback) { if (self.s.authenticationContexts.length === 0) { return callback(); } // Do not apply any auth contexts if it's an arbiter if (server.lastIsMaster() && server.lastIsMaster().arbiterOnly) { return callback(); } // Copy contexts to ensure no modificiation in the middle of // auth process. var authContexts = self.s.authenticationContexts.slice(0); // Apply one of the contexts function applyAuth(authContexts, server, callback) { if (authContexts.length === 0) return callback(); // Get the first auth context var authContext = authContexts.shift(); // Copy the params var customAuthContext = authContext.slice(0); // Push our callback handler customAuthContext.push(function(/* err */) { applyAuth(authContexts, server, callback); }); // Attempt authentication server.auth.apply(server, customAuthContext); } // Apply all auth contexts applyAuth(authContexts, server, callback); } function shouldTriggerConnect(self) { const isConnecting = self.state === CONNECTING; const hasPrimary = self.s.replicaSetState.hasPrimary(); const hasSecondary = self.s.replicaSetState.hasSecondary(); const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; const readPreferenceSecondary = self.s.connectOptions.readPreference && self.s.connectOptions.readPreference.equals(ReadPreference.secondary); return ( (isConnecting && ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || (hasSecondary && secondaryOnlyConnectionAllowed) ); } function handleInitialConnectEvent(self, event) { return function() { var _this = this; // Debug log if (self.s.logger.isDebug()) { self.s.logger.debug( f( 'handleInitialConnectEvent %s from server %s in replset with id %s', event, this.name, self.id ) ); } // Destroy the instance if (self.state === DESTROYED || self.state === UNREFERENCED) { return this.destroy({ force: true }); } // Check the type of server if (event === 'connect') { // Do we have authentication contexts that need to be applied applyAuthenticationContexts(self, _this, function() { // Destroy the instance if (self.state === DESTROYED || self.state === UNREFERENCED) { return _this.destroy({ force: true }); } // Update the state var result = self.s.replicaSetState.update(_this); if (result === true) { // Primary lastIsMaster store it if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { self.ismaster = _this.lastIsMaster(); } // Debug log if (self.s.logger.isDebug()) { self.s.logger.debug( f( 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', event, _this.name, self.id, JSON.stringify(self.s.replicaSetState.set) ) ); } // Remove the handlers for (var i = 0; i < handlers.length; i++) { _this.removeAllListeners(handlers[i]); } // Add stable state handlers _this.on('error', handleEvent(self, 'error')); _this.on('close', handleEvent(self, 'close')); _this.on('timeout', handleEvent(self, 'timeout')); _this.on('parseError', handleEvent(self, 'parseError')); // Do we have a primary or primaryAndSecondary if (shouldTriggerConnect(self)) { // We are connected self.state = CONNECTED; // Set initial connect state self.initialConnectState.connect = true; // Emit connect event process.nextTick(function() { self.emit('connect', self); }); topologyMonitor(self, {}); } } else if (result instanceof MongoError) { _this.destroy({ force: true }); self.destroy({ force: true }); return self.emit('error', result); } else { _this.destroy({ force: true }); } }); } else { // Emit failure to connect self.emit('failed', this); addServerToList(self.s.connectingServers, this); // Remove from the state self.s.replicaSetState.remove(this); } if ( self.initialConnectState.connect && !self.initialConnectState.fullsetup && self.s.replicaSetState.hasPrimaryAndSecondary() ) { // Set initial connect state self.initialConnectState.fullsetup = true; self.initialConnectState.all = true; process.nextTick(function() { self.emit('fullsetup', self); self.emit('all', self); }); } // Remove from the list from connectingServers for (var i = 0; i < self.s.connectingServers.length; i++) { if (self.s.connectingServers[i].equals(this)) { self.s.connectingServers.splice(i, 1); } } // Trigger topologyMonitor if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { topologyMonitor(self, { haInterval: 1 }); } }; } function connectServers(self, servers) { // Update connectingServers self.s.connectingServers = self.s.connectingServers.concat(servers); // Index used to interleaf the server connects, avoiding // runtime issues on io constrained vm's var timeoutInterval = 0; function connect(server, timeoutInterval) { setTimeout(function() { // Add the server to the state if (self.s.replicaSetState.update(server)) { // Primary lastIsMaster store it if (server.lastIsMaster() && server.lastIsMaster().ismaster) { self.ismaster = server.lastIsMaster(); } } // Add event handlers server.once('close', handleInitialConnectEvent(self, 'close')); server.once('timeout', handleInitialConnectEvent(self, 'timeout')); server.once('parseError', handleInitialConnectEvent(self, 'parseError')); server.once('error', handleInitialConnectEvent(self, 'error')); server.once('connect', handleInitialConnectEvent(self, 'connect')); // SDAM Monitoring events server.on('serverOpening', function(e) { self.emit('serverOpening', e); }); server.on('serverDescriptionChanged', function(e) { self.emit('serverDescriptionChanged', e); }); server.on('serverClosed', function(e) { self.emit('serverClosed', e); }); // Start connection server.connect(self.s.connectOptions); }, timeoutInterval); } // Start all the servers while (servers.length > 0) { connect(servers.shift(), timeoutInterval++); } } /** * Emit event if it exists * @method */ function emitSDAMEvent(self, event, description) { if (self.listeners(event).length > 0) { self.emit(event, description); } } /** * Initiate server connect * @method * @param {array} [options.auth=null] Array of auth options to apply on connect */ ReplSet.prototype.connect = function(options) { var self = this; // Add any connect level options to the internal state this.s.connectOptions = options || {}; // Set connecting state stateTransition(this, CONNECTING); // Create server instances var servers = this.s.seedlist.map(function(x) { return new Server( Object.assign({}, self.s.options, x, { authProviders: self.authProviders, reconnect: false, monitoring: false, parent: self, clientInfo: clone(self.s.clientInfo) }) ); }); // Error out as high availbility interval must be < than socketTimeout if ( this.s.options.socketTimeout > 0 && this.s.options.socketTimeout <= this.s.options.haInterval ) { return self.emit( 'error', new MongoError( f( 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', this.s.options.haInterval, this.s.options.socketTimeout ) ) ); } // Emit the topology opening event emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); // Start all server connections connectServers(self, servers); }; /** * Destroy the server connection * @param {boolean} [options.force=false] Force destroy the pool * @method */ ReplSet.prototype.destroy = function(options) { options = options || {}; // Transition state stateTransition(this, DESTROYED); // Clear out any monitoring process if (this.haTimeoutId) clearTimeout(this.haTimeoutId); // Destroy the replicaset this.s.replicaSetState.destroy(options); // Clear out authentication contexts this.s.authenticationContexts = []; // Destroy all connecting servers this.s.connectingServers.forEach(function(x) { x.destroy(options); }); // Clear out all monitoring for (var i = 0; i < this.intervalIds.length; i++) { this.intervalIds[i].stop(); this.intervalIds[i].stop(); } // Reset list of intervalIds this.intervalIds = []; // Emit toplogy closing event emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); }; /** * Unref all connections belong to this server * @method */ ReplSet.prototype.unref = function() { // Transition state stateTransition(this, UNREFERENCED); this.s.replicaSetState.allServers().forEach(function(x) { x.unref(); }); clearTimeout(this.haTimeoutId); }; /** * Returns the last known ismaster document for this server * @method * @return {object} */ ReplSet.prototype.lastIsMaster = function() { // If secondaryOnlyConnectionAllowed and no primary but secondary // return the secondaries ismaster result. if ( this.s.options.secondaryOnlyConnectionAllowed && !this.s.replicaSetState.hasPrimary() && this.s.replicaSetState.hasSecondary() ) { return this.s.replicaSetState.secondaries[0].lastIsMaster(); } return this.s.replicaSetState.primary ? this.s.replicaSetState.primary.lastIsMaster() : this.ismaster; }; /** * All raw connections * @method * @return {Connection[]} */ ReplSet.prototype.connections = function() { var servers = this.s.replicaSetState.allServers(); var connections = []; for (var i = 0; i < servers.length; i++) { connections = connections.concat(servers[i].connections()); } return connections; }; /** * Figure out if the server is connected * @method * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @return {boolean} */ ReplSet.prototype.isConnected = function(options) { options = options || {}; // If we are authenticating signal not connected // To avoid interleaving of operations if (this.authenticating) return false; // If we specified a read preference check if we are connected to something // than can satisfy this if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { return this.s.replicaSetState.hasSecondary(); } if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { return this.s.replicaSetState.hasPrimary(); } if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); } if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); } if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { return true; } return this.s.replicaSetState.hasPrimary(); }; /** * Figure out if the replicaset instance was destroyed by calling destroy * @method * @return {boolean} */ ReplSet.prototype.isDestroyed = function() { return this.state === DESTROYED; }; /** * Get server * @method * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @return {Server} */ ReplSet.prototype.getServer = function(options) { // Ensure we have no options options = options || {}; // Pick the right server based on readPreference var server = this.s.replicaSetState.pickServer(options.readPreference); if (this.s.debug) this.emit('pickedServer', options.readPreference, server); return server; }; /** * Get a direct connection * @method * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @return {Connection} */ ReplSet.prototype.getConnection = function(options) { var server = this.getServer(options); if (server) return server.getConnection(); }; /** * Get all connected servers * @method * @return {Server[]} */ ReplSet.prototype.getServers = function() { return this.s.replicaSetState.allServers(); }; // // Execute write operation var executeWriteOperation = function(self, op, ns, ops, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) { // No server returned we had an error if (self.s.replicaSetState.primary == null) { return callback(new MongoError('no primary server found')); } // Execute the command return self.s.replicaSetState.primary[op](ns, ops, options, callback); } // increment and assign txnNumber options.txnNumber = getNextTransactionNumber(options.session); self.s.replicaSetState.primary[op](ns, ops, options, (err, result) => { if (!err) return callback(null, result); if (!(err instanceof errors.MongoNetworkError) && !err.message.match(/not master/)) { return callback(err); } if (self.s.replicaSetState.primary == null) { return callback(new MongoError('no primary server found')); } // Re-execute the command self.s.replicaSetState.primary[op](ns, ops, options, callback); }); }; /** * Insert one or more documents * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of documents to insert * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {boolean} [options.retryWrites] Enable retryable writes for this operation * @param {opResultCallback} callback A callback function */ ReplSet.prototype.insert = function(ns, ops, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Not connected but we have a disconnecthandler if (!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { return this.s.disconnectHandler.add('insert', ns, ops, options, callback); } // Execute write operation executeWriteOperation(this, 'insert', ns, ops, options, callback); }; /** * Perform one or more update operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of updates * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {boolean} [options.retryWrites] Enable retryable writes for this operation * @param {opResultCallback} callback A callback function */ ReplSet.prototype.update = function(ns, ops, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Not connected but we have a disconnecthandler if (!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { return this.s.disconnectHandler.add('update', ns, ops, options, callback); } // Execute write operation executeWriteOperation(this, 'update', ns, ops, options, callback); }; /** * Perform one or more remove operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of removes * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {boolean} [options.retryWrites] Enable retryable writes for this operation * @param {opResultCallback} callback A callback function */ ReplSet.prototype.remove = function(ns, ops, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); // Not connected but we have a disconnecthandler if (!this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null) { return this.s.disconnectHandler.add('remove', ns, ops, options, callback); } // Execute write operation executeWriteOperation(this, 'remove', ns, ops, options, callback); }; /** * Execute a command * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cmd The command hash * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Connection} [options.connection] Specify connection object to execute command against * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ ReplSet.prototype.command = function(ns, cmd, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); var self = this; // Establish readPreference var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; // If the readPreference is primary and we have no primary, store it if ( readPreference.preference === 'primary' && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null ) { return this.s.disconnectHandler.add('command', ns, cmd, options, callback); } else if ( readPreference.preference === 'secondary' && !this.s.replicaSetState.hasSecondary() && this.s.disconnectHandler != null ) { return this.s.disconnectHandler.add('command', ns, cmd, options, callback); } else if ( readPreference.preference !== 'primary' && !this.s.replicaSetState.hasSecondary() && !this.s.replicaSetState.hasPrimary() && this.s.disconnectHandler != null ) { return this.s.disconnectHandler.add('command', ns, cmd, options, callback); } // Pick a server var server = this.s.replicaSetState.pickServer(readPreference); // We received an error, return it if (!(server instanceof Server)) return callback(server); // Emit debug event if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); // No server returned we had an error if (server == null) { return callback( new MongoError( f('no server found that matches the provided readPreference %s', readPreference) ) ); } // Execute the command server.command(ns, cmd, options, callback); }; /** * Authenticate using a specified mechanism * @method * @param {string} mechanism The Auth mechanism we are invoking * @param {string} db The db we are invoking the mechanism against * @param {...object} param Parameters for the specific mechanism * @param {authResultCallback} callback A callback function */ ReplSet.prototype.auth = function(mechanism, db) { var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); var self = this; var args = Array.prototype.slice.call(arguments, 2); var callback = args.pop(); var currentContextIndex = 0; // If we don't have the mechanism fail if (this.authProviders[mechanism] == null && mechanism !== 'default') { return callback(new MongoError(f('auth provider %s does not exist', mechanism))); } // Are we already authenticating, throw if (this.authenticating) { return callback(new MongoError('authentication or logout allready in process')); } // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if (self.s.disconnectHandler != null) { if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); } else if ( !self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed ) { return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); } } // Set to authenticating this.authenticating = true; // All errors var errors = []; // Get all the servers var servers = this.s.replicaSetState.allServers(); // No servers return if (servers.length === 0) { this.authenticating = false; callback(null, true); } // Authenticate function auth(server) { // Arguments without a callback var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); // Create arguments var finalArguments = argsWithoutCallback.concat([ function(err) { count = count - 1; // Save all the errors if (err) errors.push({ name: server.name, err: err }); // We are done if (count === 0) { // Auth is done self.authenticating = false; // Return the auth error if (errors.length) { // Remove the entry from the stored authentication contexts self.s.authenticationContexts.splice(currentContextIndex, 0); // Return error return callback( new MongoError({ message: 'authentication fail', errors: errors }), false ); } // Successfully authenticated session callback(null, self); } } ]); if (!server.lastIsMaster().arbiterOnly) { // Execute the auth only against non arbiter servers server.auth.apply(server, finalArguments); } else { // If we are authenticating against an arbiter just ignore it finalArguments.pop()(null); } } // Get total count var count = servers.length; // Save current context index currentContextIndex = this.s.authenticationContexts.length; // Store the auth context and return the last index this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); // Authenticate against all servers while (servers.length > 0) { auth(servers.shift()); } }; /** * Logout from a database * @method * @param {string} db The db we are logging out from * @param {authResultCallback} callback A callback function */ ReplSet.prototype.logout = function(dbName, callback) { var self = this; // Are we authenticating or logging out, throw if (this.authenticating) { throw new MongoError('authentication or logout allready in process'); } // Ensure no new members are processed while logging out this.authenticating = true; // Remove from all auth providers (avoid any reaplication of the auth details) var providers = Object.keys(this.authProviders); for (var i = 0; i < providers.length; i++) { this.authProviders[providers[i]].logout(dbName); } // Clear out any contexts associated with the db self.s.authenticationContexts = self.s.authenticationContexts.filter(function(context) { return context[1] !== dbName; }); // Now logout all the servers var servers = this.s.replicaSetState.allServers(); var count = servers.length; if (count === 0) return callback(); var errors = []; function logoutServer(_server, cb) { _server.logout(dbName, function(err) { if (err) errors.push({ name: _server.name, err: err }); cb(); }); } // Execute logout on all server instances for (i = 0; i < servers.length; i++) { logoutServer(servers[i], function() { count = count - 1; if (count === 0) { // Do not block new operations self.authenticating = false; // If we have one or more errors if (errors.length) return callback( new MongoError({ message: f('logout failed against db %s', dbName), errors: errors }), false ); // No errors callback(); } }); } }; /** * Get a new cursor * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId * @param {object} [options] Options for the cursor * @param {object} [options.batchSize=0] Batchsize for the operation * @param {array} [options.documents=[]] Initial documents list for cursor * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {object} [options.topology] The internal topology of the created cursor * @returns {Cursor} */ ReplSet.prototype.cursor = function(ns, cmd, options) { options = options || {}; const topology = options.topology || this; // Set up final cursor type var FinalCursor = options.cursorFactory || this.s.Cursor; // Return the cursor return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); }; /** * A replset connect event, used to verify that the connection is up and running * * @event ReplSet#connect * @type {ReplSet} */ /** * A replset reconnect event, used to verify that the topology reconnected * * @event ReplSet#reconnect * @type {ReplSet} */ /** * A replset fullsetup event, used to signal that all topology members have been contacted. * * @event ReplSet#fullsetup * @type {ReplSet} */ /** * A replset all event, used to signal that all topology members have been contacted. * * @event ReplSet#all * @type {ReplSet} */ /** * A replset failed event, used to signal that initial replset connection failed. * * @event ReplSet#failed * @type {ReplSet} */ /** * A server member left the replicaset * * @event ReplSet#left * @type {function} * @param {string} type The type of member that left (primary|secondary|arbiter) * @param {Server} server The server object that left */ /** * A server member joined the replicaset * * @event ReplSet#joined * @type {function} * @param {string} type The type of member that joined (primary|secondary|arbiter) * @param {Server} server The server object that joined */ /** * A server opening SDAM monitoring event * * @event ReplSet#serverOpening * @type {object} */ /** * A server closed SDAM monitoring event * * @event ReplSet#serverClosed * @type {object} */ /** * A server description SDAM change monitoring event * * @event ReplSet#serverDescriptionChanged * @type {object} */ /** * A topology open SDAM event * * @event ReplSet#topologyOpening * @type {object} */ /** * A topology closed SDAM event * * @event ReplSet#topologyClosed * @type {object} */ /** * A topology structure SDAM change event * * @event ReplSet#topologyDescriptionChanged * @type {object} */ /** * A topology serverHeartbeatStarted SDAM event * * @event ReplSet#serverHeartbeatStarted * @type {object} */ /** * A topology serverHeartbeatFailed SDAM event * * @event ReplSet#serverHeartbeatFailed * @type {object} */ /** * A topology serverHeartbeatSucceeded SDAM change event * * @event ReplSet#serverHeartbeatSucceeded * @type {object} */ module.exports = ReplSet; }).call(this,require('_process')) },{"../auth/gssapi":346,"../auth/mongocr":347,"../auth/plain":348,"../auth/scram":349,"../auth/sspi":350,"../auth/x509":351,"../connection/logger":355,"../connection/utils":357,"../cursor":358,"../error":359,"./read_preference":362,"./replset_state":364,"./server":365,"./shared":366,"_process":507,"events":316,"util":563}],364:[function(require,module,exports){ (function (Buffer){ 'use strict'; var inherits = require('util').inherits, f = require('util').format, diff = require('./shared').diff, EventEmitter = require('events').EventEmitter, Logger = require('../connection/logger'), ReadPreference = require('./read_preference'), MongoError = require('../error').MongoError; var TopologyType = { Single: 'Single', ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', Sharded: 'Sharded', Unknown: 'Unknown' }; var ServerType = { Standalone: 'Standalone', Mongos: 'Mongos', PossiblePrimary: 'PossiblePrimary', RSPrimary: 'RSPrimary', RSSecondary: 'RSSecondary', RSArbiter: 'RSArbiter', RSOther: 'RSOther', RSGhost: 'RSGhost', Unknown: 'Unknown' }; var ReplSetState = function(options) { options = options || {}; // Add event listener EventEmitter.call(this); // Topology state this.topologyType = TopologyType.ReplicaSetNoPrimary; this.setName = options.setName; // Server set this.set = {}; // Unpacked options this.id = options.id; this.setName = options.setName; // Replicaset logger this.logger = options.logger || Logger('ReplSet', options); // Server selection index this.index = 0; // Acceptable latency this.acceptableLatency = options.acceptableLatency || 15; // heartbeatFrequencyMS this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; // Server side this.primary = null; this.secondaries = []; this.arbiters = []; this.passives = []; this.ghosts = []; // Current unknown hosts this.unknownServers = []; // In set status this.set = {}; // Status this.maxElectionId = null; this.maxSetVersion = 0; // Description of the Replicaset this.replicasetDescription = { topologyType: 'Unknown', servers: [] }; this.logicalSessionTimeoutMinutes = undefined; }; inherits(ReplSetState, EventEmitter); ReplSetState.prototype.hasPrimaryAndSecondary = function() { return this.primary != null && this.secondaries.length > 0; }; ReplSetState.prototype.hasPrimaryOrSecondary = function() { return this.hasPrimary() || this.hasSecondary(); }; ReplSetState.prototype.hasPrimary = function() { return this.primary != null; }; ReplSetState.prototype.hasSecondary = function() { return this.secondaries.length > 0; }; ReplSetState.prototype.get = function(host) { var servers = this.allServers(); for (var i = 0; i < servers.length; i++) { if (servers[i].name.toLowerCase() === host.toLowerCase()) { return servers[i]; } } return null; }; ReplSetState.prototype.allServers = function(options) { options = options || {}; var servers = this.primary ? [this.primary] : []; servers = servers.concat(this.secondaries); if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); servers = servers.concat(this.passives); return servers; }; ReplSetState.prototype.destroy = function(options) { // Destroy all sockets if (this.primary) this.primary.destroy(options); this.secondaries.forEach(function(x) { x.destroy(options); }); this.arbiters.forEach(function(x) { x.destroy(options); }); this.passives.forEach(function(x) { x.destroy(options); }); this.ghosts.forEach(function(x) { x.destroy(options); }); // Clear out the complete state this.secondaries = []; this.arbiters = []; this.passives = []; this.ghosts = []; this.unknownServers = []; this.set = {}; this.primary = null; // Emit the topology changed emitTopologyDescriptionChanged(this); }; ReplSetState.prototype.remove = function(server, options) { options = options || {}; // Get the server name and lowerCase it var serverName = server.name.toLowerCase(); // Only remove if the current server is not connected var servers = this.primary ? [this.primary] : []; servers = servers.concat(this.secondaries); servers = servers.concat(this.arbiters); servers = servers.concat(this.passives); // Check if it's active and this is just a failed connection attempt for (var i = 0; i < servers.length; i++) { if ( !options.force && servers[i].equals(server) && servers[i].isConnected && servers[i].isConnected() ) { return; } } // If we have it in the set remove it if (this.set[serverName]) { this.set[serverName].type = ServerType.Unknown; this.set[serverName].electionId = null; this.set[serverName].setName = null; this.set[serverName].setVersion = null; } // Remove type var removeType = null; // Remove from any lists if (this.primary && this.primary.equals(server)) { this.primary = null; this.topologyType = TopologyType.ReplicaSetNoPrimary; removeType = 'primary'; } // Remove from any other server lists removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; removeFrom(server, this.ghosts); removeFrom(server, this.unknownServers); // Push to unknownServers this.unknownServers.push(serverName); // Do we have a removeType if (removeType) { this.emit('left', removeType, server); } }; const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; ReplSetState.prototype.update = function(server) { var self = this; // Get the current ismaster var ismaster = server.lastIsMaster(); // Get the server name and lowerCase it var serverName = server.name.toLowerCase(); // // Add any hosts // if (ismaster) { // Join all the possible new hosts var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); hosts = hosts.map(function(s) { return s.toLowerCase(); }); // Add all hosts as unknownServers for (var i = 0; i < hosts.length; i++) { // Add to the list of unknown server if ( this.unknownServers.indexOf(hosts[i]) === -1 && (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) ) { this.unknownServers.push(hosts[i].toLowerCase()); } if (!this.set[hosts[i]]) { this.set[hosts[i]] = { type: ServerType.Unknown, electionId: null, setName: null, setVersion: null }; } } } // // Unknown server // if (!ismaster && !inList(ismaster, server, this.unknownServers)) { self.set[serverName] = { type: ServerType.Unknown, setVersion: null, electionId: null, setName: null }; // Update set information about the server instance self.set[serverName].type = ServerType.Unknown; self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; if (self.unknownServers.indexOf(server.name) === -1) { self.unknownServers.push(serverName); } // Set the topology return false; } // Update logicalSessionTimeoutMinutes if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { if ( self.logicalSessionTimeoutMinutes === undefined || ismaster.logicalSessionTimeoutMinutes === null ) { self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; } else { self.logicalSessionTimeoutMinutes = Math.min( self.logicalSessionTimeoutMinutes, ismaster.logicalSessionTimeoutMinutes ); } } // // Is this a mongos // if (ismaster && ismaster.msg === 'isdbgrid') { return false; } // A RSOther instance if ( (ismaster.setName && ismaster.hidden) || (ismaster.setName && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly && !ismaster.passive) ) { self.set[serverName] = { type: ServerType.RSOther, setVersion: null, electionId: null, setName: ismaster.setName }; // Set the topology this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; if (ismaster.setName) this.setName = ismaster.setName; return false; } // A RSGhost instance if (ismaster.isreplicaset) { self.set[serverName] = { type: ServerType.RSGhost, setVersion: null, electionId: null, setName: null }; // Set the topology this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; if (ismaster.setName) this.setName = ismaster.setName; // Set the topology return false; } // // Standalone server, destroy and return // if (ismaster && ismaster.ismaster && !ismaster.setName) { this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; this.remove(server, { force: true }); return false; } // // Server in maintanance mode // if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { this.remove(server, { force: true }); return false; } // // If the .me field does not match the passed in server // if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { if (this.logger.isWarn()) { this.logger.warn( f( 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', server.name, ismaster.me ) ); } // Delete from the set delete this.set[serverName]; // Delete unknown servers removeFrom(server, self.unknownServers); // Destroy the instance server.destroy(); // Set the type of topology we have if (this.primary && !this.primary.equals(server)) { this.topologyType = TopologyType.ReplicaSetWithPrimary; } else { this.topologyType = TopologyType.ReplicaSetNoPrimary; } // // We have a potential primary // if (!this.primary && ismaster.primary) { this.set[ismaster.primary.toLowerCase()] = { type: ServerType.PossiblePrimary, setName: null, electionId: null, setVersion: null }; } return false; } // // Primary handling // if (!this.primary && ismaster.ismaster && ismaster.setName) { var ismasterElectionId = server.lastIsMaster().electionId; if (this.setName && this.setName !== ismaster.setName) { this.topologyType = TopologyType.ReplicaSetNoPrimary; return new MongoError( f( 'setName from ismaster does not match provided connection setName [%s] != [%s]', ismaster.setName, this.setName ) ); } if (!this.maxElectionId && ismasterElectionId) { this.maxElectionId = ismasterElectionId; } else if (this.maxElectionId && ismasterElectionId) { var result = compareObjectIds(this.maxElectionId, ismasterElectionId); // Get the electionIds var ismasterSetVersion = server.lastIsMaster().setVersion; if (result === 1) { this.topologyType = TopologyType.ReplicaSetNoPrimary; return false; } else if (result === 0 && ismasterSetVersion) { if (ismasterSetVersion < this.maxSetVersion) { this.topologyType = TopologyType.ReplicaSetNoPrimary; return false; } } this.maxSetVersion = ismasterSetVersion; this.maxElectionId = ismasterElectionId; } // Hande normalization of server names var normalizedHosts = ismaster.hosts.map(function(x) { return x.toLowerCase(); }); var locationIndex = normalizedHosts.indexOf(serverName); // Validate that the server exists in the host list if (locationIndex !== -1) { self.primary = server; self.set[serverName] = { type: ServerType.RSPrimary, setVersion: ismaster.setVersion, electionId: ismaster.electionId, setName: ismaster.setName }; // Set the topology this.topologyType = TopologyType.ReplicaSetWithPrimary; if (ismaster.setName) this.setName = ismaster.setName; removeFrom(server, self.unknownServers); removeFrom(server, self.secondaries); removeFrom(server, self.passives); self.emit('joined', 'primary', server); } else { this.topologyType = TopologyType.ReplicaSetNoPrimary; } emitTopologyDescriptionChanged(self); return true; } else if (ismaster.ismaster && ismaster.setName) { // Get the electionIds var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; var currentSetName = self.set[self.primary.name.toLowerCase()].setName; ismasterElectionId = server.lastIsMaster().electionId; ismasterSetVersion = server.lastIsMaster().setVersion; var ismasterSetName = server.lastIsMaster().setName; // Is it the same server instance if (this.primary.equals(server) && currentSetName === ismasterSetName) { return false; } // If we do not have the same rs name if (currentSetName && currentSetName !== ismasterSetName) { if (!this.primary.equals(server)) { this.topologyType = TopologyType.ReplicaSetWithPrimary; } else { this.topologyType = TopologyType.ReplicaSetNoPrimary; } return false; } // Check if we need to replace the server if (currentElectionId && ismasterElectionId) { result = compareObjectIds(currentElectionId, ismasterElectionId); if (result === 1) { return false; } else if (result === 0 && currentSetVersion > ismasterSetVersion) { return false; } } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { if (ismasterSetVersion < this.maxSetVersion) { return false; } } if (!this.maxElectionId && ismasterElectionId) { this.maxElectionId = ismasterElectionId; } else if (this.maxElectionId && ismasterElectionId) { result = compareObjectIds(this.maxElectionId, ismasterElectionId); if (result === 1) { return false; } else if (result === 0 && currentSetVersion && ismasterSetVersion) { if (ismasterSetVersion < this.maxSetVersion) { return false; } } else { if (ismasterSetVersion < this.maxSetVersion) { return false; } } this.maxElectionId = ismasterElectionId; this.maxSetVersion = ismasterSetVersion; } else { this.maxSetVersion = ismasterSetVersion; } // Modify the entry to unknown self.set[self.primary.name.toLowerCase()] = { type: ServerType.Unknown, setVersion: null, electionId: null, setName: null }; // Signal primary left self.emit('left', 'primary', this.primary); // Destroy the instance self.primary.destroy(); // Set the new instance self.primary = server; // Set the set information self.set[serverName] = { type: ServerType.RSPrimary, setVersion: ismaster.setVersion, electionId: ismaster.electionId, setName: ismaster.setName }; // Set the topology this.topologyType = TopologyType.ReplicaSetWithPrimary; if (ismaster.setName) this.setName = ismaster.setName; removeFrom(server, self.unknownServers); removeFrom(server, self.secondaries); removeFrom(server, self.passives); self.emit('joined', 'primary', server); emitTopologyDescriptionChanged(self); return true; } // A possible instance if (!this.primary && ismaster.primary) { self.set[ismaster.primary.toLowerCase()] = { type: ServerType.PossiblePrimary, setVersion: null, electionId: null, setName: null }; } // // Secondary handling // if ( ismaster.secondary && ismaster.setName && !inList(ismaster, server, this.secondaries) && this.setName && this.setName === ismaster.setName ) { addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); // Set the topology this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; if (ismaster.setName) this.setName = ismaster.setName; removeFrom(server, self.unknownServers); // Remove primary if (this.primary && this.primary.name.toLowerCase() === serverName) { server.destroy(); this.primary = null; self.emit('left', 'primary', server); } // Emit secondary joined replicaset self.emit('joined', 'secondary', server); emitTopologyDescriptionChanged(self); return true; } // // Arbiter handling // if ( isArbiter(ismaster) && !inList(ismaster, server, this.arbiters) && this.setName && this.setName === ismaster.setName ) { addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); // Set the topology this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; if (ismaster.setName) this.setName = ismaster.setName; removeFrom(server, self.unknownServers); self.emit('joined', 'arbiter', server); emitTopologyDescriptionChanged(self); return true; } // // Passive handling // if ( ismaster.passive && ismaster.setName && !inList(ismaster, server, this.passives) && this.setName && this.setName === ismaster.setName ) { addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); // Set the topology this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; if (ismaster.setName) this.setName = ismaster.setName; removeFrom(server, self.unknownServers); // Remove primary if (this.primary && this.primary.name.toLowerCase() === serverName) { server.destroy(); this.primary = null; self.emit('left', 'primary', server); } self.emit('joined', 'secondary', server); emitTopologyDescriptionChanged(self); return true; } // // Remove the primary // if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { self.emit('left', 'primary', this.primary); this.primary.destroy(); this.primary = null; this.topologyType = TopologyType.ReplicaSetNoPrimary; return false; } this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.ReplicaSetNoPrimary; return false; }; /** * Recalculate single server max staleness * @method */ ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { // Locate the max secondary lastwrite var max = 0; // Go over all secondaries for (var i = 0; i < this.secondaries.length; i++) { max = Math.max(max, this.secondaries[i].lastWriteDate); } // Perform this servers staleness calculation if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { server.staleness = server.lastUpdateTime - server.lastWriteDate - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + haInterval; } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { server.staleness = max - server.lastWriteDate + haInterval; } }; /** * Recalculate all the staleness values for secodaries * @method */ ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { for (var i = 0; i < this.secondaries.length; i++) { this.updateServerMaxStaleness(this.secondaries[i], haInterval); } }; /** * Pick a server by the passed in ReadPreference * @method * @param {ReadPreference} readPreference The ReadPreference instance to use */ ReplSetState.prototype.pickServer = function(readPreference) { // If no read Preference set to primary by default readPreference = readPreference || ReadPreference.primary; // maxStalenessSeconds is not allowed with a primary read if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); } // Check if we have any non compatible servers for maxStalenessSeconds var allservers = this.primary ? [this.primary] : []; allservers = allservers.concat(this.secondaries); // Does any of the servers not support the right wire protocol version // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out if (readPreference.maxStalenessSeconds != null) { for (var i = 0; i < allservers.length; i++) { if (allservers[i].ismaster.maxWireVersion < 5) { return new MongoError( 'maxStalenessSeconds not supported by at least one of the replicaset members' ); } } } // Do we have the nearest readPreference if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { return pickNearest(this, readPreference); } else if ( readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds != null ) { return pickNearestMaxStalenessSeconds(this, readPreference); } // Get all the secondaries var secondaries = this.secondaries; // Check if we can satisfy and of the basic read Preferences if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { return new MongoError('no secondary server available'); } if ( readPreference.equals(ReadPreference.secondaryPreferred) && secondaries.length === 0 && this.primary == null ) { return new MongoError('no secondary or primary server available'); } if (readPreference.equals(ReadPreference.primary) && this.primary == null) { return new MongoError('no primary server available'); } // Secondary preferred or just secondaries if ( readPreference.equals(ReadPreference.secondaryPreferred) || readPreference.equals(ReadPreference.secondary) ) { if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { // Pick nearest of any other servers available var server = pickNearest(this, readPreference); // No server in the window return primary if (server) { return server; } } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { // Pick nearest of any other servers available server = pickNearestMaxStalenessSeconds(this, readPreference); // No server in the window return primary if (server) { return server; } } if (readPreference.equals(ReadPreference.secondaryPreferred)) { return this.primary; } return null; } // Primary preferred if (readPreference.equals(ReadPreference.primaryPreferred)) { server = null; // We prefer the primary if it's available if (this.primary) { return this.primary; } // Pick a secondary if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { server = pickNearest(this, readPreference); } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { server = pickNearestMaxStalenessSeconds(this, readPreference); } // Did we find a server if (server) return server; } // Return the primary return this.primary; }; // // Filter serves by tags var filterByTags = function(readPreference, servers) { if (readPreference.tags == null) return servers; var filteredServers = []; var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; // Iterate over the tags for (var j = 0; j < tagsArray.length; j++) { var tags = tagsArray[j]; // Iterate over all the servers for (var i = 0; i < servers.length; i++) { var serverTag = servers[i].lastIsMaster().tags || {}; // Did we find the a matching server var found = true; // Check if the server is valid for (var name in tags) { if (serverTag[name] !== tags[name]) { found = false; } } // Add to candidate list if (found) { filteredServers.push(servers[i]); } } } // Returned filtered servers return filteredServers; }; function pickNearestMaxStalenessSeconds(self, readPreference) { // Only get primary and secondaries as seeds var servers = []; // Get the maxStalenessMS var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; // Check if the maxStalenessMS > 90 seconds if (maxStalenessMS < 90 * 1000) { return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); } // Add primary to list if not a secondary read preference if ( self.primary && readPreference.preference !== 'secondary' && readPreference.preference !== 'secondaryPreferred' ) { servers.push(self.primary); } // Add all the secondaries for (var i = 0; i < self.secondaries.length; i++) { servers.push(self.secondaries[i]); } // If we have a secondaryPreferred readPreference and no server add the primary if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { servers.push(self.primary); } // Filter by tags servers = filterByTags(readPreference, servers); // // Locate lowest time (picked servers are lowest time + acceptable Latency margin) // var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; // Filter by latency servers = servers.filter(function(s) { return s.staleness <= maxStalenessMS; }); // Sort by time servers.sort(function(a, b) { // return a.time > b.time; return a.lastIsMasterMS > b.lastIsMasterMS; }); // No servers, default to primary if (servers.length === 0) { return null; } // Ensure index does not overflow the number of available servers self.index = self.index % servers.length; // Get the server var server = servers[self.index]; // Add to the index self.index = self.index + 1; // Return the first server of the sorted and filtered list return server; } function pickNearest(self, readPreference) { // Only get primary and secondaries as seeds var servers = []; // Add primary to list if not a secondary read preference if ( self.primary && readPreference.preference !== 'secondary' && readPreference.preference !== 'secondaryPreferred' ) { servers.push(self.primary); } // Add all the secondaries for (var i = 0; i < self.secondaries.length; i++) { servers.push(self.secondaries[i]); } // If we have a secondaryPreferred readPreference and no server add the primary if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { servers.push(self.primary); } // Filter by tags servers = filterByTags(readPreference, servers); // Sort by time servers.sort(function(a, b) { // return a.time > b.time; return a.lastIsMasterMS > b.lastIsMasterMS; }); // Locate lowest time (picked servers are lowest time + acceptable Latency margin) var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; // Filter by latency servers = servers.filter(function(s) { return s.lastIsMasterMS <= lowest + self.acceptableLatency; }); // No servers, default to primary if (servers.length === 0) { return null; } // Ensure index does not overflow the number of available servers self.index = self.index % servers.length; // Get the server var server = servers[self.index]; // Add to the index self.index = self.index + 1; // Return the first server of the sorted and filtered list return server; } function inList(ismaster, server, list) { for (var i = 0; i < list.length; i++) { if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) return true; } return false; } function addToList(self, type, ismaster, server, list) { var serverName = server.name.toLowerCase(); // Update set information about the server instance self.set[serverName].type = type; self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; // Add to the list list.push(server); } function compareObjectIds(id1, id2) { var a = new Buffer(id1.toHexString(), 'hex'); var b = new Buffer(id2.toHexString(), 'hex'); if (a === b) { return 0; } if (typeof Buffer.compare === 'function') { return Buffer.compare(a, b); } var x = a.length; var y = b.length; var len = Math.min(x, y); for (var i = 0; i < len; i++) { if (a[i] !== b[i]) { break; } } if (i !== len) { x = a[i]; y = b[i]; } return x < y ? -1 : y < x ? 1 : 0; } function removeFrom(server, list) { for (var i = 0; i < list.length; i++) { if (list[i].equals && list[i].equals(server)) { list.splice(i, 1); return true; } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { list.splice(i, 1); return true; } } return false; } function emitTopologyDescriptionChanged(self) { if (self.listeners('topologyDescriptionChanged').length > 0) { var topology = 'Unknown'; var setName = self.setName; if (self.hasPrimaryAndSecondary()) { topology = 'ReplicaSetWithPrimary'; } else if (!self.hasPrimary() && self.hasSecondary()) { topology = 'ReplicaSetNoPrimary'; } // Generate description var description = { topologyType: topology, setName: setName, servers: [] }; // Add the primary to the list if (self.hasPrimary()) { var desc = self.primary.getDescription(); desc.type = 'RSPrimary'; description.servers.push(desc); } // Add all the secondaries description.servers = description.servers.concat( self.secondaries.map(function(x) { var description = x.getDescription(); description.type = 'RSSecondary'; return description; }) ); // Add all the arbiters description.servers = description.servers.concat( self.arbiters.map(function(x) { var description = x.getDescription(); description.type = 'RSArbiter'; return description; }) ); // Add all the passives description.servers = description.servers.concat( self.passives.map(function(x) { var description = x.getDescription(); description.type = 'RSSecondary'; return description; }) ); // Get the diff var diffResult = diff(self.replicasetDescription, description); // Create the result var result = { topologyId: self.id, previousDescription: self.replicasetDescription, newDescription: description, diff: diffResult }; // Emit the topologyDescription change // if(diffResult.servers.length > 0) { self.emit('topologyDescriptionChanged', result); // } // Set the new description self.replicasetDescription = description; } } module.exports = ReplSetState; }).call(this,require("buffer").Buffer) },{"../connection/logger":355,"../error":359,"./read_preference":362,"./shared":366,"buffer":144,"events":316,"util":563}],365:[function(require,module,exports){ 'use strict'; var inherits = require('util').inherits, f = require('util').format, EventEmitter = require('events').EventEmitter, ReadPreference = require('./read_preference'), Logger = require('../connection/logger'), debugOptions = require('../connection/utils').debugOptions, retrieveBSON = require('../connection/utils').retrieveBSON, Pool = require('../connection/pool'), Query = require('../connection/commands').Query, MongoError = require('../error').MongoError, MongoNetworkError = require('../error').MongoNetworkError, TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'), ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'), BasicCursor = require('../cursor'), sdam = require('./shared'), createClientInfo = require('./shared').createClientInfo, createCompressionInfo = require('./shared').createCompressionInfo, resolveClusterTime = require('./shared').resolveClusterTime, SessionMixins = require('./shared').SessionMixins; // Used for filtering out fields for loggin var debugFields = [ 'reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout', 'checkServerIdentity', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'crl', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'servername' ]; // Server instance id var id = 0; var serverAccounting = false; var servers = {}; var BSON = retrieveBSON(); /** * Creates a new Server instance * @class * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors * @param {string} options.host The server host * @param {number} options.port The server port * @param {number} [options.size=5] Server connection pool size * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting * @param {boolean} [options.ssl=false] Use SSL for connection * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {Buffer} [options.ca] SSL Certificate store binary buffer * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer * @param {Buffer} [options.cert] SSL Certificate binary buffer * @param {Buffer} [options.key] SSL Key file binary buffer * @param {string} [options.passphrase] SSL Certificate pass phrase * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @return {Server} A cursor instance * @fires Server#connect * @fires Server#close * @fires Server#error * @fires Server#timeout * @fires Server#parseError * @fires Server#reconnect * @fires Server#reconnectFailed * @fires Server#serverHeartbeatStarted * @fires Server#serverHeartbeatSucceeded * @fires Server#serverHeartbeatFailed * @fires Server#topologyOpening * @fires Server#topologyClosed * @fires Server#topologyDescriptionChanged * @property {string} type the topology type. * @property {string} parserType the parser type used (c++ or js). */ var Server = function(options) { options = options || {}; // Add event listener EventEmitter.call(this); // Server instance id this.id = id++; // Internal state this.s = { // Options options: options, // Logger logger: Logger('Server', options), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Pool pool: null, // Disconnect handler disconnectHandler: options.disconnectHandler, // Monitor thread (keeps the connection alive) monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, // Is the server in a topology inTopology: !!options.parent, // Monitoring timeout monitoringInterval: typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, // Topology id topologyId: -1, compression: { compressors: createCompressionInfo(options) }, // Optional parent topology parent: options.parent }; // If this is a single deployment we need to track the clusterTime here if (!this.s.parent) { this.s.clusterTime = null; } // Curent ismaster this.ismaster = null; // Current ping time this.lastIsMasterMS = -1; // The monitoringProcessId this.monitoringProcessId = null; // Initial connection this.initialConnect = true; // Wire protocol handler, default to oldest known protocol handler // this gets changed when the first ismaster is called. this.wireProtocolHandler = new TwoSixWireProtocolSupport(); // Default type this._type = 'server'; // Set the client info this.clientInfo = createClientInfo(options); // Max Stalleness values // last time we updated the ismaster state this.lastUpdateTime = 0; // Last write time this.lastWriteDate = 0; // Stalleness this.staleness = 0; }; inherits(Server, EventEmitter); Object.assign(Server.prototype, SessionMixins); Object.defineProperty(Server.prototype, 'type', { enumerable: true, get: function() { return this._type; } }); Object.defineProperty(Server.prototype, 'parserType', { enumerable: true, get: function() { return BSON.native ? 'c++' : 'js'; } }); Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { enumerable: true, get: function() { if (!this.ismaster) return null; return this.ismaster.logicalSessionTimeoutMinutes || null; } }); // In single server deployments we track the clusterTime directly on the topology, however // in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the // tracking objects so we can ensure we are gossiping the maximum time received from the // server. Object.defineProperty(Server.prototype, 'clusterTime', { enumerable: true, set: function(clusterTime) { const settings = this.s.parent ? this.s.parent : this.s; resolveClusterTime(settings, clusterTime); }, get: function() { const settings = this.s.parent ? this.s.parent : this.s; return settings.clusterTime || null; } }); Server.enableServerAccounting = function() { serverAccounting = true; servers = {}; }; Server.disableServerAccounting = function() { serverAccounting = false; }; Server.servers = function() { return servers; }; Object.defineProperty(Server.prototype, 'name', { enumerable: true, get: function() { return this.s.options.host + ':' + this.s.options.port; } }); function isSupportedServer(response) { return response && typeof response.maxWireVersion === 'number' && response.maxWireVersion >= 2; } function configureWireProtocolHandler(self, ismaster) { // 3.2 wire protocol handler if (ismaster.maxWireVersion >= 4) { return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); } // default to 2.6 wire protocol handler return new TwoSixWireProtocolSupport(); } function disconnectHandler(self, type, ns, cmd, options, callback) { // Topology is not connected, save the call in the provided store to be // Executed at some point when the handler deems it's reconnected if ( !self.s.pool.isConnected() && self.s.options.reconnect && self.s.disconnectHandler != null && !options.monitoring ) { self.s.disconnectHandler.add(type, ns, cmd, options, callback); return true; } // If we have no connection error if (!self.s.pool.isConnected()) { callback(new MongoError(f('no connection available to server %s', self.name))); return true; } } function monitoringProcess(self) { return function() { // Pool was destroyed do not continue process if (self.s.pool.isDestroyed()) return; // Emit monitoring Process event self.emit('monitoring', self); // Perform ismaster call // Query options var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; // Create a query instance var query = new Query(self.s.bson, 'admin.$cmd', { ismaster: true }, queryOptions); // Get start time var start = new Date().getTime(); // Execute the ismaster query self.s.pool.write( query, { socketTimeout: typeof self.s.options.connectionTimeout !== 'number' ? 2000 : self.s.options.connectionTimeout, monitoring: true }, function(err, result) { // Set initial lastIsMasterMS self.lastIsMasterMS = new Date().getTime() - start; if (self.s.pool.isDestroyed()) return; // Update the ismaster view if we have a result if (result) { self.ismaster = result.result; } // Re-schedule the monitoring process self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); } ); }; } var eventHandler = function(self, event) { return function(err) { // Log information of received information if in info mode if (self.s.logger.isInfo()) { var object = err instanceof MongoError ? JSON.stringify(err) : {}; self.s.logger.info( f('server %s fired event %s out with message %s', self.name, event, object) ); } // Handle connect event if (event === 'connect') { // Issue an ismaster command at connect // Query options var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; // Create a query instance var compressors = self.s.compression && self.s.compression.compressors ? self.s.compression.compressors : []; var query = new Query( self.s.bson, 'admin.$cmd', { ismaster: true, client: self.clientInfo, compression: compressors }, queryOptions ); // Get start time var start = new Date().getTime(); // Execute the ismaster query self.s.pool.write( query, { socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, result) { // Set initial lastIsMasterMS self.lastIsMasterMS = new Date().getTime() - start; if (err) { self.destroy(); return self.emit('error', err); } if (!isSupportedServer(result.result)) { self.destroy(); const latestSupportedVersion = '2.6'; const message = 'Server at ' + self.s.options.host + ':' + self.s.options.port + ' reports wire version ' + (result.result.maxWireVersion || 0) + ', but this version of Node.js Driver requires at least 2 (MongoDB' + latestSupportedVersion + ').'; return self.emit('error', new MongoError(message), self); } // Determine whether the server is instructing us to use a compressor if (result.result && result.result.compression) { for (var i = 0; i < self.s.compression.compressors.length; i++) { if (result.result.compression.indexOf(self.s.compression.compressors[i]) > -1) { self.s.pool.options.agreedCompressor = self.s.compression.compressors[i]; break; } } if (self.s.compression.zlibCompressionLevel) { self.s.pool.options.zlibCompressionLevel = self.s.compression.zlibCompressionLevel; } } // Ensure no error emitted after initial connect when reconnecting self.initialConnect = false; // Save the ismaster self.ismaster = result.result; // It's a proxy change the type so // the wireprotocol will send $readPreference if (self.ismaster.msg === 'isdbgrid') { self._type = 'mongos'; } // Add the correct wire protocol handler self.wireProtocolHandler = configureWireProtocolHandler(self, self.ismaster); // Have we defined self monitoring if (self.s.monitoring) { self.monitoringProcessId = setTimeout( monitoringProcess(self), self.s.monitoringInterval ); } // Emit server description changed if something listening sdam.emitServerDescriptionChanged(self, { address: self.name, arbiters: [], hosts: [], passives: [], type: sdam.getTopologyType(self) }); if (!self.s.inTopology) { // Emit topology description changed if something listening sdam.emitTopologyDescriptionChanged(self, { topologyType: 'Single', servers: [ { address: self.name, arbiters: [], hosts: [], passives: [], type: sdam.getTopologyType(self) } ] }); } // Log the ismaster if available if (self.s.logger.isInfo()) { self.s.logger.info( f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) ); } // Emit connect self.emit('connect', self); } ); } else if ( event === 'error' || event === 'parseError' || event === 'close' || event === 'timeout' || event === 'reconnect' || event === 'attemptReconnect' || 'reconnectFailed' ) { // Remove server instance from accounting if ( serverAccounting && ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 ) { // Emit toplogy opening event if not in topology if (!self.s.inTopology) { self.emit('topologyOpening', { topologyId: self.id }); } delete servers[self.id]; } if (event === 'close') { // Closing emits a server description changed event going to unknown. sdam.emitServerDescriptionChanged(self, { address: self.name, arbiters: [], hosts: [], passives: [], type: 'Unknown' }); } // Reconnect failed return error if (event === 'reconnectFailed') { self.emit('reconnectFailed', err); // Emit error if any listeners if (self.listeners('error').length > 0) { self.emit('error', err); } // Terminate return; } // On first connect fail if ( self.s.pool.state === 'disconnected' && self.initialConnect && ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 ) { self.initialConnect = false; return self.emit( 'error', new MongoNetworkError( f('failed to connect to server [%s] on first connect [%s]', self.name, err) ) ); } // Reconnect event, emit the server if (event === 'reconnect') { // Reconnecting emits a server description changed event going from unknown to the // current server type. sdam.emitServerDescriptionChanged(self, { address: self.name, arbiters: [], hosts: [], passives: [], type: sdam.getTopologyType(self) }); return self.emit(event, self); } // Emit the event self.emit(event, err); } }; }; /** * Initiate server connect * @method * @param {array} [options.auth=null] Array of auth options to apply on connect */ Server.prototype.connect = function(options) { var self = this; options = options || {}; // Set the connections if (serverAccounting) servers[this.id] = this; // Do not allow connect to be called on anything that's not disconnected if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); } // Create a pool self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); // Set up listeners self.s.pool.on('close', eventHandler(self, 'close')); self.s.pool.on('error', eventHandler(self, 'error')); self.s.pool.on('timeout', eventHandler(self, 'timeout')); self.s.pool.on('parseError', eventHandler(self, 'parseError')); self.s.pool.on('connect', eventHandler(self, 'connect')); self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); // Emit toplogy opening event if not in topology if (!self.s.inTopology) { this.emit('topologyOpening', { topologyId: self.id }); } // Emit opening server event self.emit('serverOpening', { topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, address: self.name }); // Connect with optional auth settings if (options.auth) { self.s.pool.connect.apply(self.s.pool, options.auth); } else { self.s.pool.connect(); } }; /** * Get the server description * @method * @return {object} */ Server.prototype.getDescription = function() { var ismaster = this.ismaster || {}; var description = { type: sdam.getTopologyType(this), address: this.name }; // Add fields if available if (ismaster.hosts) description.hosts = ismaster.hosts; if (ismaster.arbiters) description.arbiters = ismaster.arbiters; if (ismaster.passives) description.passives = ismaster.passives; if (ismaster.setName) description.setName = ismaster.setName; return description; }; /** * Returns the last known ismaster document for this server * @method * @return {object} */ Server.prototype.lastIsMaster = function() { return this.ismaster; }; /** * Unref all connections belong to this server * @method */ Server.prototype.unref = function() { this.s.pool.unref(); }; /** * Figure out if the server is connected * @method * @return {boolean} */ Server.prototype.isConnected = function() { if (!this.s.pool) return false; return this.s.pool.isConnected(); }; /** * Figure out if the server instance was destroyed by calling destroy * @method * @return {boolean} */ Server.prototype.isDestroyed = function() { if (!this.s.pool) return false; return this.s.pool.isDestroyed(); }; function basicWriteValidations(self) { if (!self.s.pool) return new MongoError('server instance is not connected'); if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); } function basicReadValidations(self, options) { basicWriteValidations(self, options); if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { throw new Error('readPreference must be an instance of ReadPreference'); } } /** * Execute a command * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object} cmd The command hash * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ Server.prototype.command = function(ns, cmd, options, callback) { var self = this; if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } var result = basicReadValidations(self, options); if (result) return callback(result); // Clone the options options = Object.assign({}, options, { wireProtocolCommand: false }); // Debug log if (self.s.logger.isDebug()) self.s.logger.debug( f( 'executing command [%s] against %s', JSON.stringify({ ns: ns, cmd: cmd, options: debugOptions(debugFields, options) }), self.name ) ); // If we are not connected or have a disconnectHandler specified if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; // Check if we have collation support if (this.ismaster && this.ismaster.maxWireVersion < 5 && cmd.collation) { return callback(new MongoError(f('server %s does not support collation', this.name))); } // Are we executing against a specific topology var topology = options.topology || {}; // Create the query object var query = self.wireProtocolHandler.command(self.s.bson, ns, cmd, {}, topology, options); // Set slave OK of the query query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false; // Write options var writeOptions = { raw: typeof options.raw === 'boolean' ? options.raw : false, promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, command: true, monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, requestId: query.requestId, socketTimeout: typeof options.socketTimeout === 'number' ? options.socketTimeout : null, session: options.session || null }; // Write the operation to the pool self.s.pool.write(query, writeOptions, callback); }; /** * Insert one or more documents * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of documents to insert * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ Server.prototype.insert = function(ns, ops, options, callback) { var self = this; if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } var result = basicWriteValidations(self, options); if (result) return callback(result); // If we are not connected or have a disconnectHandler specified if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; // Setup the docs as an array ops = Array.isArray(ops) ? ops : [ops]; // Execute write return self.wireProtocolHandler.insert( self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback ); }; /** * Perform one or more update operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of updates * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ Server.prototype.update = function(ns, ops, options, callback) { var self = this; if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } var result = basicWriteValidations(self, options); if (result) return callback(result); // If we are not connected or have a disconnectHandler specified if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; // Check if we have collation support if (this.ismaster && this.ismaster.maxWireVersion < 5 && options.collation) { return callback(new MongoError(f('server %s does not support collation', this.name))); } // Setup the docs as an array ops = Array.isArray(ops) ? ops : [ops]; // Execute write return self.wireProtocolHandler.update( self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback ); }; /** * Perform one or more remove operations * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {array} ops An array of removes * @param {boolean} [options.ordered=true] Execute in order or out of order * @param {object} [options.writeConcern={}] Write concern for the operation * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {opResultCallback} callback A callback function */ Server.prototype.remove = function(ns, ops, options, callback) { var self = this; if (typeof options === 'function') { (callback = options), (options = {}), (options = options || {}); } var result = basicWriteValidations(self, options); if (result) return callback(result); // If we are not connected or have a disconnectHandler specified if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; // Check if we have collation support if (this.ismaster && this.ismaster.maxWireVersion < 5 && options.collation) { return callback(new MongoError(f('server %s does not support collation', this.name))); } // Setup the docs as an array ops = Array.isArray(ops) ? ops : [ops]; // Execute write return self.wireProtocolHandler.remove( self.s.pool, self.ismaster, ns, self.s.bson, ops, options, callback ); }; /** * Get a new cursor * @method * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId * @param {object} [options] Options for the cursor * @param {object} [options.batchSize=0] Batchsize for the operation * @param {array} [options.documents=[]] Initial documents list for cursor * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session=null] Session to use for the operation * @param {object} [options.topology] The internal topology of the created cursor * @returns {Cursor} */ Server.prototype.cursor = function(ns, cmd, options) { options = options || {}; const topology = options.topology || this; // Set up final cursor type var FinalCursor = options.cursorFactory || this.s.Cursor; // Return the cursor return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); }; /** * Logout from a database * @method * @param {string} db The db we are logging out from * @param {authResultCallback} callback A callback function */ Server.prototype.logout = function(dbName, callback) { this.s.pool.logout(dbName, callback); }; /** * Authenticate using a specified mechanism * @method * @param {string} mechanism The Auth mechanism we are invoking * @param {string} db The db we are invoking the mechanism against * @param {...object} param Parameters for the specific mechanism * @param {authResultCallback} callback A callback function */ Server.prototype.auth = function(mechanism, db) { var self = this; // If we have the default mechanism we pick mechanism based on the wire // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr if (mechanism === 'default' && self.ismaster && self.ismaster.maxWireVersion >= 3) { mechanism = 'scram-sha-1'; } else if (mechanism === 'default') { mechanism = 'mongocr'; } // Slice all the arguments off var args = Array.prototype.slice.call(arguments, 0); // Set the mechanism args[0] = mechanism; // Get the callback var callback = args[args.length - 1]; // If we are not connected or have a disconnectHandler specified if (disconnectHandler(self, 'auth', db, args, {}, callback)) { return; } // Do not authenticate if we are an arbiter if (this.lastIsMaster() && this.lastIsMaster().arbiterOnly) { return callback(null, true); } // Apply the arguments to the pool self.s.pool.auth.apply(self.s.pool, args); }; /** * Compare two server instances * @method * @param {Server} server Server to compare equality against * @return {boolean} */ Server.prototype.equals = function(server) { if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); return false; }; /** * All raw connections * @method * @return {Connection[]} */ Server.prototype.connections = function() { return this.s.pool.allConnections(); }; /** * Get server * @method * @return {Server} */ Server.prototype.getServer = function() { return this; }; /** * Get connection * @method * @return {Connection} */ Server.prototype.getConnection = function() { return this.s.pool.get(); }; var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; /** * Destroy the server connection * @method * @param {boolean} [options.emitClose=false] Emit close event on destroy * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy * @param {boolean} [options.force=false] Force destroy the pool */ Server.prototype.destroy = function(options) { options = options || {}; var self = this; // Set the connections if (serverAccounting) delete servers[this.id]; // Destroy the monitoring process if any if (this.monitoringProcessId) { clearTimeout(this.monitoringProcessId); } // No pool, return if (!self.s.pool) return; // Emit close event if (options.emitClose) { self.emit('close', self); } // Emit destroy event if (options.emitDestroy) { self.emit('destroy', self); } // Remove all listeners listeners.forEach(function(event) { self.s.pool.removeAllListeners(event); }); // Emit opening server event if (self.listeners('serverClosed').length > 0) self.emit('serverClosed', { topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, address: self.name }); // Emit toplogy opening event if not in topology if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { self.emit('topologyClosed', { topologyId: self.id }); } if (self.s.logger.isDebug()) { self.s.logger.debug(f('destroy called on server %s', self.name)); } // Destroy the pool this.s.pool.destroy(options.force); }; /** * A server connect event, used to verify that the connection is up and running * * @event Server#connect * @type {Server} */ /** * A server reconnect event, used to verify that the server topology has reconnected * * @event Server#reconnect * @type {Server} */ /** * A server opening SDAM monitoring event * * @event Server#serverOpening * @type {object} */ /** * A server closed SDAM monitoring event * * @event Server#serverClosed * @type {object} */ /** * A server description SDAM change monitoring event * * @event Server#serverDescriptionChanged * @type {object} */ /** * A topology open SDAM event * * @event Server#topologyOpening * @type {object} */ /** * A topology closed SDAM event * * @event Server#topologyClosed * @type {object} */ /** * A topology structure SDAM change event * * @event Server#topologyDescriptionChanged * @type {object} */ /** * Server reconnect failed * * @event Server#reconnectFailed * @type {Error} */ /** * Server connection pool closed * * @event Server#close * @type {object} */ /** * Server connection pool caused an error * * @event Server#error * @type {Error} */ /** * Server destroyed was called * * @event Server#destroy * @type {Server} */ module.exports = Server; },{"../connection/commands":353,"../connection/logger":355,"../connection/pool":356,"../connection/utils":357,"../cursor":358,"../error":359,"../wireprotocol/2_6_support":369,"../wireprotocol/3_2_support":370,"./read_preference":362,"./shared":366,"events":316,"util":563}],366:[function(require,module,exports){ (function (process,Buffer){ 'use strict'; const os = require('os'), f = require('util').format, ReadPreference = require('./read_preference'), retrieveBSON = require('../connection/utils').retrieveBSON; const BSON = retrieveBSON(); /** * Emit event if it exists * @method */ function emitSDAMEvent(self, event, description) { if (self.listeners(event).length > 0) { self.emit(event, description); } } // Get package.json variable var driverVersion = require('../../package.json').version; var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); var type = os.type(); var name = process.platform; var architecture = process.arch; var release = os.release(); function createClientInfo(options) { // Build default client information var clientInfo = options.clientInfo ? clone(options.clientInfo) : { driver: { name: 'nodejs-core', version: driverVersion }, os: { type: type, name: name, architecture: architecture, version: release } }; // Is platform specified if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); } else if (!clientInfo.platform) { clientInfo.platform = nodejsversion; } // Do we have an application specific string if (options.appname) { // Cut at 128 bytes var buffer = new Buffer(options.appname); // Return the truncated appname var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; // Add to the clientInfo clientInfo.application = { name: appname }; } return clientInfo; } function createCompressionInfo(options) { if (!options.compression || !options.compression.compressors) { return []; } // Check that all supplied compressors are valid options.compression.compressors.forEach(function(compressor) { if (compressor !== 'snappy' && compressor !== 'zlib') { throw new Error('compressors must be at least one of snappy or zlib'); } }); return options.compression.compressors; } function clone(object) { return JSON.parse(JSON.stringify(object)); } var getPreviousDescription = function(self) { if (!self.s.serverDescription) { self.s.serverDescription = { address: self.name, arbiters: [], hosts: [], passives: [], type: 'Unknown' }; } return self.s.serverDescription; }; var emitServerDescriptionChanged = function(self, description) { if (self.listeners('serverDescriptionChanged').length > 0) { // Emit the server description changed events self.emit('serverDescriptionChanged', { topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, address: self.name, previousDescription: getPreviousDescription(self), newDescription: description }); self.s.serverDescription = description; } }; var getPreviousTopologyDescription = function(self) { if (!self.s.topologyDescription) { self.s.topologyDescription = { topologyType: 'Unknown', servers: [ { address: self.name, arbiters: [], hosts: [], passives: [], type: 'Unknown' } ] }; } return self.s.topologyDescription; }; var emitTopologyDescriptionChanged = function(self, description) { if (self.listeners('topologyDescriptionChanged').length > 0) { // Emit the server description changed events self.emit('topologyDescriptionChanged', { topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, address: self.name, previousDescription: getPreviousTopologyDescription(self), newDescription: description }); self.s.serverDescription = description; } }; var changedIsMaster = function(self, currentIsmaster, ismaster) { var currentType = getTopologyType(self, currentIsmaster); var newType = getTopologyType(self, ismaster); if (newType !== currentType) return true; return false; }; var getTopologyType = function(self, ismaster) { if (!ismaster) { ismaster = self.ismaster; } if (!ismaster) return 'Unknown'; if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; if (ismaster.ismaster) return 'RSPrimary'; if (ismaster.secondary) return 'RSSecondary'; if (ismaster.arbiterOnly) return 'RSArbiter'; return 'Unknown'; }; var inquireServerState = function(self) { return function(callback) { if (self.s.state === 'destroyed') return; // Record response time var start = new Date().getTime(); // emitSDAMEvent emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); // Attempt to execute ismaster command self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { if (!err) { // Legacy event sender self.emit('ismaster', r, self); // Calculate latencyMS var latencyMS = new Date().getTime() - start; // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: self.name }); // Did the server change if (changedIsMaster(self, self.s.ismaster, r.result)) { // Emit server description changed if something listening emitServerDescriptionChanged(self, { address: self.name, arbiters: [], hosts: [], passives: [], type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) }); } // Updat ismaster view self.s.ismaster = r.result; // Set server response time self.s.isMasterLatencyMS = latencyMS; } else { emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: self.name }); } // Peforming an ismaster monitoring callback operation if (typeof callback === 'function') { return callback(err, r); } // Perform another sweep self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); }); }; }; // // Clone the options var cloneOptions = function(options) { var opts = {}; for (var name in options) { opts[name] = options[name]; } return opts; }; function Interval(fn, time) { var timer = false; this.start = function() { if (!this.isRunning()) { timer = setInterval(fn, time); } return this; }; this.stop = function() { clearInterval(timer); timer = false; return this; }; this.isRunning = function() { return timer !== false; }; } function Timeout(fn, time) { var timer = false; this.start = function() { if (!this.isRunning()) { timer = setTimeout(fn, time); } return this; }; this.stop = function() { clearTimeout(timer); timer = false; return this; }; this.isRunning = function() { if (timer && timer._called) return false; return timer !== false; }; } function diff(previous, current) { // Difference document var diff = { servers: [] }; // Previous entry if (!previous) { previous = { servers: [] }; } // Check if we have any previous servers missing in the current ones for (var i = 0; i < previous.servers.length; i++) { var found = false; for (var j = 0; j < current.servers.length; j++) { if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { found = true; break; } } if (!found) { // Add to the diff diff.servers.push({ address: previous.servers[i].address, from: previous.servers[i].type, to: 'Unknown' }); } } // Check if there are any severs that don't exist for (j = 0; j < current.servers.length; j++) { found = false; // Go over all the previous servers for (i = 0; i < previous.servers.length; i++) { if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { found = true; break; } } // Add the server to the diff if (!found) { diff.servers.push({ address: current.servers[j].address, from: 'Unknown', to: current.servers[j].type }); } } // Got through all the servers for (i = 0; i < previous.servers.length; i++) { var prevServer = previous.servers[i]; // Go through all current servers for (j = 0; j < current.servers.length; j++) { var currServer = current.servers[j]; // Matching server if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { // We had a change in state if (prevServer.type !== currServer.type) { diff.servers.push({ address: prevServer.address, from: prevServer.type, to: currServer.type }); } } } } // Return difference return diff; } /** * Shared function to determine clusterTime for a given topology * * @param {*} topology * @param {*} clusterTime */ function resolveClusterTime(topology, $clusterTime) { if (topology.clusterTime == null) { topology.clusterTime = $clusterTime; } else { if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { topology.clusterTime = $clusterTime; } } } // NOTE: this is a temporary move until the topologies can be more formally refactored // to share code. const SessionMixins = { endSessions: function(sessions, callback) { if (this.isConnected()) { if (typeof callback === 'function') callback(); return; } if (!Array.isArray(sessions)) { sessions = [sessions]; } // TODO: // When connected to a sharded cluster the endSessions command // can be sent to any mongos. When connected to a replica set the // endSessions command MUST be sent to the primary if the primary // is available, otherwise it MUST be sent to any available secondary. // Is it enough to use: ReadPreference.primaryPreferred ? this.command( 'admin.$cmd', { endSessions: sessions.map(s => s.id) }, { readPreference: ReadPreference.primaryPreferred }, () => { // intentionally ignored, per spec if (typeof callback === 'function') callback(); } ); } }; const RETRYABLE_WIRE_VERSION = 6; /** * Determines whether the provided topology supports retryable writes * * @param {Mongos|Replset} topology */ const isRetryableWritesSupported = function(topology) { const maxWireVersion = topology.lastIsMaster().maxWireVersion; if (maxWireVersion < RETRYABLE_WIRE_VERSION) { return false; } if (!topology.logicalSessionTimeoutMinutes) { return false; } return true; }; /** * Increment the transaction number on the ServerSession contained by the provided ClientSession * * @param {ClientSession} session */ const getNextTransactionNumber = function(session) { session.serverSession.txnNumber++; return BSON.Long.fromNumber(session.serverSession.txnNumber); }; module.exports.SessionMixins = SessionMixins; module.exports.resolveClusterTime = resolveClusterTime; module.exports.inquireServerState = inquireServerState; module.exports.getTopologyType = getTopologyType; module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; module.exports.cloneOptions = cloneOptions; module.exports.createClientInfo = createClientInfo; module.exports.createCompressionInfo = createCompressionInfo; module.exports.clone = clone; module.exports.diff = diff; module.exports.Interval = Interval; module.exports.Timeout = Timeout; module.exports.isRetryableWritesSupported = isRetryableWritesSupported; module.exports.getNextTransactionNumber = getNextTransactionNumber; }).call(this,require('_process'),require("buffer").Buffer) },{"../../package.json":373,"../connection/utils":357,"./read_preference":362,"_process":507,"buffer":144,"os":483,"util":563}],367:[function(require,module,exports){ 'use strict'; const URL = require('url'); const qs = require('querystring'); const dns = require('dns'); const MongoParseError = require('./error').MongoParseError; /** * The following regular expression validates a connection string and breaks the * provide string into the following capture groups: [protocol, username, password, hosts] */ const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; /** * Determines whether a provided address matches the provided parent domain in order * to avoid certain attack vectors. * * @param {String} srvAddress The address to check against a domain * @param {String} parentDomain The domain to check the provided address against * @return {Boolean} Whether the provided address matches the parent domain */ function matchesParentDomain(srvAddress, parentDomain) { const regex = /^.*?\./; const srv = `.${srvAddress.replace(regex, '')}`; const parent = `.${parentDomain.replace(regex, '')}`; return srv.endsWith(parent); } /** * Lookup an `mongodb+srv` connection string, combine the parts and reparse it as a normal * connection string. * * @param {string} uri The connection string to parse * @param {object} options Optional user provided connection string options * @param {function} callback */ function parseSrvConnectionString(uri, options, callback) { const result = URL.parse(uri, true); if (result.hostname.split('.').length < 3) { return callback(new MongoParseError('URI does not have hostname, domain name and tld')); } result.domainLength = result.hostname.split('.').length; if (result.pathname && result.pathname.match(',')) { return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); } if (result.port) { return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); } let srvAddress = `_mongodb._tcp.${result.host}`; dns.resolveSrv(srvAddress, (err, addresses) => { if (err) return callback(err); if (addresses.length === 0) { return callback(new MongoParseError('No addresses found at host')); } for (let i = 0; i < addresses.length; i++) { if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { return callback( new MongoParseError('Server record does not share hostname with parent URI') ); } } let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; let connectionStrings = addresses.map( (address, i) => i === 0 ? `${base}${address.name}:${address.port}` : `${address.name}:${address.port}` ); let connectionString = connectionStrings.join(',') + '/'; let connectionStringOptions = []; // Default to SSL true if (!options.ssl && (!result.search || !result.query.hasOwnProperty('ssl'))) { connectionStringOptions.push('ssl=true'); } // Keep original uri options if (result.search) { connectionStringOptions.push(result.search.replace('?', '')); } dns.resolveTxt(result.host, (err, record) => { if (err) { if (err.code !== 'ENODATA') { return callback(err); } record = null; } if (record) { if (record.length > 1) { return callback(new MongoParseError('Multiple text records not allowed')); } record = record[0]; record = record.length > 1 ? record.join('') : record[0]; if (!record.includes('authSource') && !record.includes('replicaSet')) { return callback( new MongoParseError('Text record must only set `authSource` or `replicaSet`') ); } connectionStringOptions.push(record); } // Add any options to the connection string if (connectionStringOptions.length) { connectionString += `?${connectionStringOptions.join('&')}`; } parseConnectionString(connectionString, callback); }); }); } /** * Parses a query string item according to the connection string spec * * @param {Array|String} value The value to parse * @return {Array|Object|String} The parsed value */ function parseQueryStringItemValue(value) { if (Array.isArray(value)) { // deduplicate and simplify arrays value = value.filter((value, idx) => value.indexOf(value) === idx); if (value.length === 1) value = value[0]; } else if (value.indexOf(':') > 0) { value = value.split(',').reduce((result, pair) => { const parts = pair.split(':'); result[parts[0]] = parseQueryStringItemValue(parts[1]); return result; }, {}); } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { value = value.toLowerCase() === 'true'; } else if (!Number.isNaN(value)) { const numericValue = parseFloat(value); if (!Number.isNaN(numericValue)) { value = parseFloat(value); } } return value; } /** * Parses a query string according the connection string spec. * * @param {String} query The query string to parse * @return {Object|Error} The parsed query string as an object, or an error if one was encountered */ function parseQueryString(query) { const result = {}; let parsedQueryString = qs.parse(query); for (const key in parsedQueryString) { const value = parsedQueryString[key]; if (value === '' || value == null) { return new MongoParseError('Incomplete key value pair for option'); } result[key.toLowerCase()] = parseQueryStringItemValue(value); } // special cases for known deprecated options if (result.wtimeout && result.wtimeoutms) { delete result.wtimeout; console.warn('Unsupported option `wtimeout` specified'); } return Object.keys(result).length ? result : null; } const PROTOCOL_MONGODB = 'mongodb'; const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; /** * Parses a MongoDB connection string * * @param {*} uri the MongoDB connection string to parse * @param {object} [options] Optional settings. * @param {parseCallback} callback */ function parseConnectionString(uri, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; const cap = uri.match(HOSTS_RX); if (!cap) { return callback(new MongoParseError('Invalid connection string')); } const protocol = cap[1]; if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { return callback(new MongoParseError('Invalid protocol provided')); } if (protocol === PROTOCOL_MONGODB_SRV) { return parseSrvConnectionString(uri, options, callback); } const dbAndQuery = cap[4].split('?'); const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; let parsedOptions = parseQueryString(query); if (parsedOptions instanceof MongoParseError) { return callback(parsedOptions); } parsedOptions = Object.assign({}, parsedOptions, options); const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; if (cap[4].split('?')[0].indexOf('@') !== -1) { return callback(new MongoParseError('Unescaped slash in userinfo section')); } const authorityParts = cap[3].split('@'); if (authorityParts.length > 2) { return callback(new MongoParseError('Unescaped at-sign in authority section')); } if (authorityParts.length > 1) { const authParts = authorityParts.shift().split(':'); if (authParts.length > 2) { return callback(new MongoParseError('Unescaped colon in authority section')); } auth.username = qs.unescape(authParts[0]); auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; } let hostParsingError = null; const hosts = authorityParts .shift() .split(',') .map(host => { let parsedHost = URL.parse(`mongodb://${host}`); if (parsedHost.path === '/:') { hostParsingError = new MongoParseError('Double colon in host identifier'); return null; } // heuristically determine if we're working with a domain socket if (host.match(/\.sock/)) { parsedHost.hostname = qs.unescape(host); parsedHost.port = null; } if (Number.isNaN(parsedHost.port)) { hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); return; } const result = { host: parsedHost.hostname, port: parsedHost.port ? parseInt(parsedHost.port) : null }; if (result.port === 0) { hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); return; } if (result.port > 65535) { hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); return; } if (result.port < 0) { hostParsingError = new MongoParseError('Invalid port (negative number)'); return; } return result; }) .filter(host => !!host); if (hostParsingError) { return callback(hostParsingError); } if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { return callback(new MongoParseError('No hostname or hostnames provided in connection string')); } callback(null, { hosts: hosts, auth: auth.db || auth.username ? auth : null, options: Object.keys(parsedOptions).length ? parsedOptions : null }); } module.exports = parseConnectionString; },{"./error":359,"dns":123,"querystring":517,"url":558}],368:[function(require,module,exports){ 'use strict'; const crypto = require('crypto'); const uuidV4 = () => { const result = crypto.randomBytes(16); result[6] = (result[6] & 0x0f) | 0x40; result[8] = (result[8] & 0x3f) | 0x80; return result; }; module.exports = { uuidV4: uuidV4 }; },{"crypto":287}],369:[function(require,module,exports){ 'use strict'; var copy = require('../connection/utils').copy, retrieveBSON = require('../connection/utils').retrieveBSON, KillCursor = require('../connection/commands').KillCursor, GetMore = require('../connection/commands').GetMore, Query = require('../connection/commands').Query, f = require('util').format, MongoError = require('../error').MongoError, getReadPreference = require('./shared').getReadPreference; var BSON = retrieveBSON(), Long = BSON.Long; var WireProtocol = function() {}; // // Execute a write operation var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { if (ops.length === 0) throw new MongoError('insert must contain at least one document'); if (typeof options === 'function') { callback = options; options = {}; options = options || {}; } // Split the ns up to get db and collection var p = ns.split('.'); var d = p.shift(); // Options var ordered = typeof options.ordered === 'boolean' ? options.ordered : true; var writeConcern = options.writeConcern; // return skeleton var writeCommand = {}; writeCommand[type] = p.join('.'); writeCommand[opsField] = ops; writeCommand.ordered = ordered; // Did we specify a write concern if (writeConcern && Object.keys(writeConcern).length > 0) { writeCommand.writeConcern = writeConcern; } // Do we have bypassDocumentValidation set, then enable it on the write command if (typeof options.bypassDocumentValidation === 'boolean') { writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; } // Options object var opts = { command: true }; if (typeof options.session !== 'undefined') opts.session = options.session; var queryOptions = { checkKeys: false, numberToSkip: 0, numberToReturn: 1 }; if (type === 'insert') queryOptions.checkKeys = false; if (typeof options.checkKeys === 'boolean') queryOptions.checkKeys = options.checkKeys; // Ensure we support serialization of functions if (options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; // Do not serialize the undefined fields if (options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; try { // Create write command var cmd = new Query(bson, f('%s.$cmd', d), writeCommand, queryOptions); // Execute command pool.write(cmd, opts, callback); } catch (err) { callback(err); } }; // // Needs to support legacy mass insert as well as ordered/unordered legacy // emulation // WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); }; WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); }; WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); }; WireProtocol.prototype.killCursor = function(bson, ns, cursorState, pool, callback) { var cursorId = cursorState.cursorId; // Create a kill cursor command var killCursor = new KillCursor(bson, [cursorId]); // Build killCursor options const options = { immediateRelease: true, noResponse: true }; if (typeof cursorState.session === 'object') { options.session = cursorState.session; } // Execute the kill cursor command if (pool && pool.isConnected()) { try { pool.write(killCursor, options, callback); } catch (err) { callback(err, null); } } // Callback if (typeof callback === 'function') callback(null, null); }; WireProtocol.prototype.getMore = function( bson, ns, cursorState, batchSize, raw, connection, options, callback ) { // Create getMore command var getMore = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); // Query callback var queryCallback = function(err, result) { if (err) return callback(err); // Get the raw message var r = result.message; // If we have a timed out query or a cursor that was killed if ((r.responseFlags & (1 << 0)) !== 0) { return callback(new MongoError('cursor does not exist, was killed or timed out'), null); } // Ensure we have a Long valie cursor id var cursorId = typeof r.cursorId === 'number' ? Long.fromNumber(r.cursorId) : r.cursorId; // Set all the values cursorState.documents = r.documents; cursorState.cursorId = cursorId; // Return callback(null, null, r.connection); }; // Contains any query options var queryOptions = {}; // If we have a raw query decorate the function if (raw) { queryOptions.raw = raw; } // Check if we need to promote longs if (typeof cursorState.promoteLongs === 'boolean') { queryOptions.promoteLongs = cursorState.promoteLongs; } if (typeof cursorState.promoteValues === 'boolean') { queryOptions.promoteValues = cursorState.promoteValues; } if (typeof cursorState.promoteBuffers === 'boolean') { queryOptions.promoteBuffers = cursorState.promoteBuffers; } if (typeof cursorState.session === 'object') { queryOptions.session = cursorState.session; } // Write out the getMore command connection.write(getMore, queryOptions, queryCallback); }; WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { // Establish type of command if (cmd.find) { return setupClassicFind(bson, ns, cmd, cursorState, topology, options); } else if (cursorState.cursorId != null) { return; } else if (cmd) { return setupCommand(bson, ns, cmd, cursorState, topology, options); } else { throw new MongoError(f('command %s does not return a cursor', JSON.stringify(cmd))); } }; // // Execute a find command var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { // Ensure we have at least some options options = options || {}; // Get the readPreference var readPreference = getReadPreference(cmd, options); // Set the optional batchSize cursorState.batchSize = cmd.batchSize || cursorState.batchSize; var numberToReturn = 0; // Unpack the limit and batchSize values if (cursorState.limit === 0) { numberToReturn = cursorState.batchSize; } else if ( cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize === 0) ) { numberToReturn = cursorState.limit; } else { numberToReturn = cursorState.batchSize; } var numberToSkip = cursorState.skip || 0; // Build actual find command var findCmd = {}; // Using special modifier var usesSpecialModifier = false; // We have a Mongos topology, check if we need to add a readPreference if (topology.type === 'mongos' && readPreference) { findCmd['$readPreference'] = readPreference.toJSON(); usesSpecialModifier = true; } // Add special modifiers to the query if (cmd.sort) (findCmd['orderby'] = cmd.sort), (usesSpecialModifier = true); if (cmd.hint) (findCmd['$hint'] = cmd.hint), (usesSpecialModifier = true); if (cmd.snapshot) (findCmd['$snapshot'] = cmd.snapshot), (usesSpecialModifier = true); if (cmd.returnKey) (findCmd['$returnKey'] = cmd.returnKey), (usesSpecialModifier = true); if (cmd.maxScan) (findCmd['$maxScan'] = cmd.maxScan), (usesSpecialModifier = true); if (cmd.min) (findCmd['$min'] = cmd.min), (usesSpecialModifier = true); if (cmd.max) (findCmd['$max'] = cmd.max), (usesSpecialModifier = true); if (cmd.showDiskLoc) (findCmd['$showDiskLoc'] = cmd.showDiskLoc), (usesSpecialModifier = true); if (cmd.comment) (findCmd['$comment'] = cmd.comment), (usesSpecialModifier = true); if (cmd.maxTimeMS) (findCmd['$maxTimeMS'] = cmd.maxTimeMS), (usesSpecialModifier = true); if (cmd.explain) { // nToReturn must be 0 (match all) or negative (match N and close cursor) // nToReturn > 0 will give explain results equivalent to limit(0) numberToReturn = -Math.abs(cmd.limit || 0); usesSpecialModifier = true; findCmd['$explain'] = true; } // If we have a special modifier if (usesSpecialModifier) { findCmd['$query'] = cmd.query; } else { findCmd = cmd.query; } // Throw on majority readConcern passed in if (cmd.readConcern && cmd.readConcern.level !== 'local') { throw new MongoError( f('server find command does not support a readConcern level of %s', cmd.readConcern.level) ); } // Remove readConcern, ensure no failing commands if (cmd.readConcern) { cmd = copy(cmd); delete cmd['readConcern']; } // Serialize functions var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; // Build Query object var query = new Query(bson, ns, findCmd, { numberToSkip: numberToSkip, numberToReturn: numberToReturn, checkKeys: false, returnFieldSelector: cmd.fields, serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined }); // Set query flags query.slaveOk = readPreference.slaveOk(); // Set up the option bits for wire protocol if (typeof cmd.tailable === 'boolean') { query.tailable = cmd.tailable; } if (typeof cmd.oplogReplay === 'boolean') { query.oplogReplay = cmd.oplogReplay; } if (typeof cmd.noCursorTimeout === 'boolean') { query.noCursorTimeout = cmd.noCursorTimeout; } if (typeof cmd.awaitData === 'boolean') { query.awaitData = cmd.awaitData; } if (typeof cmd.partial === 'boolean') { query.partial = cmd.partial; } // Return the query return query; }; // // Set up a command cursor var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { // Set empty options object options = options || {}; // Get the readPreference var readPreference = getReadPreference(cmd, options); // Final query var finalCmd = {}; for (var name in cmd) { finalCmd[name] = cmd[name]; } // Build command namespace var parts = ns.split(/\./); // Serialize functions var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; // Throw on majority readConcern passed in if (cmd.readConcern && cmd.readConcern.level !== 'local') { throw new MongoError( f( 'server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level ) ); } // Remove readConcern, ensure no failing commands if (cmd.readConcern) delete cmd['readConcern']; // We have a Mongos topology, check if we need to add a readPreference if (topology.type === 'mongos' && readPreference && readPreference.preference !== 'primary') { finalCmd = { $query: finalCmd, $readPreference: readPreference.toJSON() }; } // Build Query object var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { numberToSkip: 0, numberToReturn: -1, checkKeys: false, serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined }); // Set query flags query.slaveOk = readPreference.slaveOk(); // Return the query return query; }; module.exports = WireProtocol; },{"../connection/commands":353,"../connection/utils":357,"../error":359,"./shared":372,"util":563}],370:[function(require,module,exports){ 'use strict'; var Query = require('../connection/commands').Query, retrieveBSON = require('../connection/utils').retrieveBSON, f = require('util').format, MongoError = require('../error').MongoError, MongoNetworkError = require('../error').MongoNetworkError, getReadPreference = require('./shared').getReadPreference; var BSON = retrieveBSON(), Long = BSON.Long; var WireProtocol = function(legacyWireProtocol) { this.legacyWireProtocol = legacyWireProtocol; }; // // Execute a write operation var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { if (ops.length === 0) throw new MongoError('insert must contain at least one document'); if (typeof options === 'function') { callback = options; options = {}; options = options || {}; } // Split the ns up to get db and collection var p = ns.split('.'); var d = p.shift(); // Options var ordered = typeof options.ordered === 'boolean' ? options.ordered : true; var writeConcern = options.writeConcern; // return skeleton var writeCommand = {}; writeCommand[type] = p.join('.'); writeCommand[opsField] = ops; writeCommand.ordered = ordered; // Did we specify a write concern if (writeConcern && Object.keys(writeConcern).length > 0) { writeCommand.writeConcern = writeConcern; } // If we have collation passed in if (options.collation) { for (var i = 0; i < writeCommand[opsField].length; i++) { if (!writeCommand[opsField][i].collation) { writeCommand[opsField][i].collation = options.collation; } } } // Do we have bypassDocumentValidation set, then enable it on the write command if (typeof options.bypassDocumentValidation === 'boolean') { writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; } // optionally add a `txnNumber` if retryable writes are being attempted if (typeof options.txnNumber !== 'undefined') { writeCommand.txnNumber = options.txnNumber; } // Options object var opts = { command: true }; if (typeof options.session !== 'undefined') opts.session = options.session; var queryOptions = { checkKeys: false, numberToSkip: 0, numberToReturn: 1 }; if (type === 'insert') queryOptions.checkKeys = false; if (typeof options.checkKeys === 'boolean') queryOptions.checkKeys = options.checkKeys; // Ensure we support serialization of functions if (options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; // Do not serialize the undefined fields if (options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; try { // Create write command var cmd = new Query(bson, f('%s.$cmd', d), writeCommand, queryOptions); // Execute command pool.write(cmd, opts, callback); } catch (err) { callback(err); } }; // // Needs to support legacy mass insert as well as ordered/unordered legacy // emulation // WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); }; WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); }; WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) { executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); }; WireProtocol.prototype.killCursor = function(bson, ns, cursorState, pool, callback) { // Build command namespace var parts = ns.split(/\./); // Command namespace var commandns = f('%s.$cmd', parts.shift()); const cursorId = cursorState.cursorId; // Create killCursor command var killcursorCmd = { killCursors: parts.join('.'), cursors: [cursorId] }; // Build Query object var query = new Query(bson, commandns, killcursorCmd, { numberToSkip: 0, numberToReturn: -1, checkKeys: false, returnFieldSelector: null }); // Set query flags query.slaveOk = true; // Kill cursor callback var killCursorCallback = function(err, result) { if (err) { if (typeof callback !== 'function') return; return callback(err); } // Result var r = result.message; // If we have a timed out query or a cursor that was killed if ((r.responseFlags & (1 << 0)) !== 0) { if (typeof callback !== 'function') return; return callback(new MongoNetworkError('cursor killed or timed out'), null); } if (!Array.isArray(r.documents) || r.documents.length === 0) { if (typeof callback !== 'function') return; return callback( new MongoError(f('invalid killCursors result returned for cursor id %s', cursorId)) ); } // Return the result if (typeof callback === 'function') { callback(null, r.documents[0]); } }; const options = { command: true }; if (typeof cursorState.session === 'object') { options.session = cursorState.session; } // Execute the kill cursor command if (pool && pool.isConnected()) { try { pool.write(query, options, killCursorCallback); } catch (err) { killCursorCallback(err, null); } return; } // Callback if (typeof callback === 'function') callback(null, null); }; WireProtocol.prototype.getMore = function( bson, ns, cursorState, batchSize, raw, connection, options, callback ) { options = options || {}; // Build command namespace var parts = ns.split(/\./); // Command namespace var commandns = f('%s.$cmd', parts.shift()); // Create getMore command var getMoreCmd = { getMore: cursorState.cursorId, collection: parts.join('.'), batchSize: Math.abs(batchSize) }; if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; } // Build Query object var query = new Query(bson, commandns, getMoreCmd, { numberToSkip: 0, numberToReturn: -1, checkKeys: false, returnFieldSelector: null }); // Set query flags query.slaveOk = true; // Query callback var queryCallback = function(err, result) { if (err) return callback(err); // Get the raw message var r = result.message; // If we have a timed out query or a cursor that was killed if ((r.responseFlags & (1 << 0)) !== 0) { return callback(new MongoNetworkError('cursor killed or timed out'), null); } // Raw, return all the extracted documents if (raw) { cursorState.documents = r.documents; cursorState.cursorId = r.cursorId; return callback(null, r.documents); } // We have an error detected if (r.documents[0].ok === 0) { return callback(new MongoError(r.documents[0])); } // Ensure we have a Long valid cursor id var cursorId = typeof r.documents[0].cursor.id === 'number' ? Long.fromNumber(r.documents[0].cursor.id) : r.documents[0].cursor.id; // Set all the values cursorState.documents = r.documents[0].cursor.nextBatch; cursorState.cursorId = cursorId; // Return the result callback(null, r.documents[0], r.connection); }; // Query options var queryOptions = { command: true }; // If we have a raw query decorate the function if (raw) { queryOptions.raw = raw; } // Add the result field needed queryOptions.documentsReturnedIn = 'nextBatch'; // Check if we need to promote longs if (typeof cursorState.promoteLongs === 'boolean') { queryOptions.promoteLongs = cursorState.promoteLongs; } if (typeof cursorState.promoteValues === 'boolean') { queryOptions.promoteValues = cursorState.promoteValues; } if (typeof cursorState.promoteBuffers === 'boolean') { queryOptions.promoteBuffers = cursorState.promoteBuffers; } if (typeof cursorState.session === 'object') { queryOptions.session = cursorState.session; } // Write out the getMore command connection.write(query, queryOptions, queryCallback); }; WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { options = options || {}; // Check if this is a wire protocol command or not var wireProtocolCommand = typeof options.wireProtocolCommand === 'boolean' ? options.wireProtocolCommand : true; // Establish type of command if (cmd.find && wireProtocolCommand) { // Create the find command var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options); // Mark the cmd as virtual cmd.virtual = false; // Signal the documents are in the firstBatch value query.documentsReturnedIn = 'firstBatch'; // Return the query return query; } else if (cursorState.cursorId != null) { return; } else if (cmd) { return setupCommand(bson, ns, cmd, cursorState, topology, options); } else { throw new MongoError(f('command %s does not return a cursor', JSON.stringify(cmd))); } }; // // Command // { // find: ns // , query: // , limit: // , fields: // , skip: // , hint: // , explain: // , snapshot: // , batchSize: // , returnKey: // , maxScan: // , min: // , max: // , showDiskLoc: // , comment: // , maxTimeMS: // , raw: // , readPreference: // , tailable: // , oplogReplay: // , noCursorTimeout: // , awaitdata: // , exhaust: // , partial: // } // FIND/GETMORE SPEC // { // “find”: , // “filter”: { ... }, // “sort”: { ... }, // “projection”: { ... }, // “hint”: { ... }, // “skip”: , // “limit”: , // “batchSize”: , // “singleBatch”: , // “comment”: , // “maxScan”: , // “maxTimeMS”: , // “max”: { ... }, // “min”: { ... }, // “returnKey”: , // “showRecordId”: , // “snapshot”: , // “tailable”: , // “oplogReplay”: , // “noCursorTimeout”: , // “awaitData”: , // “partial”: , // “$readPreference”: { ... } // } // // Execute a find command var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { // Ensure we have at least some options options = options || {}; // Get the readPreference var readPreference = getReadPreference(cmd, options); // Set the optional batchSize cursorState.batchSize = cmd.batchSize || cursorState.batchSize; // Build command namespace var parts = ns.split(/\./); // Command namespace var commandns = f('%s.$cmd', parts.shift()); // Build actual find command var findCmd = { find: parts.join('.') }; // I we provided a filter if (cmd.query) { // Check if the user is passing in the $query parameter if (cmd.query['$query']) { findCmd.filter = cmd.query['$query']; } else { findCmd.filter = cmd.query; } } // Sort value var sortValue = cmd.sort; // Handle issue of sort being an Array if (Array.isArray(sortValue)) { var sortObject = {}; if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { var sortDirection = sortValue[1]; // Translate the sort order text if (sortDirection === 'asc') { sortDirection = 1; } else if (sortDirection === 'desc') { sortDirection = -1; } // Set the sort order sortObject[sortValue[0]] = sortDirection; } else { for (var i = 0; i < sortValue.length; i++) { sortDirection = sortValue[i][1]; // Translate the sort order text if (sortDirection === 'asc') { sortDirection = 1; } else if (sortDirection === 'desc') { sortDirection = -1; } // Set the sort order sortObject[sortValue[i][0]] = sortDirection; } } sortValue = sortObject; } // Add sort to command if (cmd.sort) findCmd.sort = sortValue; // Add a projection to the command if (cmd.fields) findCmd.projection = cmd.fields; // Add a hint to the command if (cmd.hint) findCmd.hint = cmd.hint; // Add a skip if (cmd.skip) findCmd.skip = cmd.skip; // Add a limit if (cmd.limit) findCmd.limit = cmd.limit; // Check if we wish to have a singleBatch if (cmd.limit < 0) { findCmd.limit = Math.abs(cmd.limit); findCmd.singleBatch = true; } // Add a batchSize if (typeof cmd.batchSize === 'number') { if (cmd.batchSize < 0) { if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { findCmd.limit = Math.abs(cmd.batchSize); } findCmd.singleBatch = true; } findCmd.batchSize = Math.abs(cmd.batchSize); } // If we have comment set if (cmd.comment) findCmd.comment = cmd.comment; // If we have maxScan if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; // If we have maxTimeMS set if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; // If we have min if (cmd.min) findCmd.min = cmd.min; // If we have max if (cmd.max) findCmd.max = cmd.max; // If we have returnKey set if (cmd.returnKey) findCmd.returnKey = cmd.returnKey; // If we have showDiskLoc set if (cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; // If we have snapshot set if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; // If we have tailable set if (cmd.tailable) findCmd.tailable = cmd.tailable; // If we have oplogReplay set if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; // If we have noCursorTimeout set if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; // If we have awaitData set if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; // If we have partial set if (cmd.partial) findCmd.partial = cmd.partial; // If we have collation passed in if (cmd.collation) findCmd.collation = cmd.collation; // If we have explain, we need to rewrite the find command // to wrap it in the explain command if (cmd.explain) { findCmd = { explain: findCmd }; } // Did we provide a readConcern if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; // Set up the serialize and ignoreUndefined fields var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; // We have a Mongos topology, check if we need to add a readPreference if (topology.type === 'mongos' && readPreference && readPreference.preference !== 'primary') { findCmd = { $query: findCmd, $readPreference: readPreference.toJSON() }; } // Build Query object var query = new Query(bson, commandns, findCmd, { numberToSkip: 0, numberToReturn: 1, checkKeys: false, returnFieldSelector: null, serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined }); // Set query flags query.slaveOk = readPreference.slaveOk(); // Return the query return query; }; // // Set up a command cursor var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { // Set empty options object options = options || {}; // Get the readPreference var readPreference = getReadPreference(cmd, options); // Final query var finalCmd = {}; for (var name in cmd) { finalCmd[name] = cmd[name]; } // Build command namespace var parts = ns.split(/\./); // Serialize functions var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; // Set up the serialize and ignoreUndefined fields var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; // We have a Mongos topology, check if we need to add a readPreference if (topology.type === 'mongos' && readPreference && readPreference.preference !== 'primary') { finalCmd = { $query: finalCmd, $readPreference: readPreference.toJSON() }; } // Build Query object var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { numberToSkip: 0, numberToReturn: -1, checkKeys: false, serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined }); // Set query flags query.slaveOk = readPreference.slaveOk(); // Return the query return query; }; module.exports = WireProtocol; },{"../connection/commands":353,"../connection/utils":357,"../error":359,"./shared":372,"util":563}],371:[function(require,module,exports){ 'use strict'; var Snappy = require('../connection/utils').retrieveSnappy(), zlib = require('zlib'); var compressorIDs = { snappy: 1, zlib: 2 }; var uncompressibleCommands = [ 'ismaster', 'saslStart', 'saslContinue', 'getnonce', 'authenticate', 'createUser', 'updateUser', 'copydbSaslStart', 'copydbgetnonce', 'copydb' ]; // Facilitate compressing a message using an agreed compressor var compress = function(self, dataToBeCompressed, callback) { switch (self.options.agreedCompressor) { case 'snappy': Snappy.compress(dataToBeCompressed, callback); break; case 'zlib': // Determine zlibCompressionLevel var zlibOptions = {}; if (self.options.zlibCompressionLevel) { zlibOptions.level = self.options.zlibCompressionLevel; } zlib.deflate(dataToBeCompressed, zlibOptions, callback); break; default: throw new Error( 'Attempt to compress message using unknown compressor "' + self.options.agreedCompressor + '".' ); } }; // Decompress a message using the given compressor var decompress = function(compressorID, compressedData, callback) { if (compressorID < 0 || compressorID > compressorIDs.length) { throw new Error( 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + compressorID + ')' ); } switch (compressorID) { case compressorIDs.snappy: Snappy.uncompress(compressedData, callback); break; case compressorIDs.zlib: zlib.inflate(compressedData, callback); break; default: callback(null, compressedData); } }; module.exports = { compressorIDs: compressorIDs, uncompressibleCommands: uncompressibleCommands, compress: compress, decompress: decompress }; },{"../connection/utils":357,"zlib":122}],372:[function(require,module,exports){ 'use strict'; var ReadPreference = require('../topologies/read_preference'), MongoError = require('../error').MongoError; var MESSAGE_HEADER_SIZE = 16; // OPCODE Numbers // Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes var opcodes = { OP_REPLY: 1, OP_UPDATE: 2001, OP_INSERT: 2002, OP_QUERY: 2004, OP_GETMORE: 2005, OP_DELETE: 2006, OP_KILL_CURSORS: 2007, OP_COMPRESSED: 2012 }; var getReadPreference = function(cmd, options) { // Default to command version of the readPreference var readPreference = cmd.readPreference || new ReadPreference('primary'); // If we have an option readPreference override the command one if (options.readPreference) { readPreference = options.readPreference; } if (typeof readPreference === 'string') { readPreference = new ReadPreference(readPreference); } if (!(readPreference instanceof ReadPreference)) { throw new MongoError('readPreference must be a ReadPreference instance'); } return readPreference; }; // Parses the header of a wire protocol message var parseHeader = function(message) { return { length: message.readInt32LE(0), requestId: message.readInt32LE(4), responseTo: message.readInt32LE(8), opCode: message.readInt32LE(12) }; }; module.exports = { getReadPreference: getReadPreference, MESSAGE_HEADER_SIZE: MESSAGE_HEADER_SIZE, opcodes: opcodes, parseHeader: parseHeader }; },{"../error":359,"../topologies/read_preference":362}],373:[function(require,module,exports){ module.exports={ "name": "mongodb-core", "version": "3.0.2", "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", "main": "index.js", "scripts": { "test": "npm run lint && mongodb-test-runner -t 60000 test/tests/functional", "coverage": "node_modules/.bin/nyc node test/runner.js -t functional -l && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", "lint": "eslint index.js lib test", "format": "prettier --print-width 100 --tab-width 2 --single-quote --write index.js 'test/**/*.js' 'lib/**/*.js'", "changelog": "conventional-changelog -p angular -i HISTORY.md -s" }, "repository": { "type": "git", "url": "git://github.com/mongodb-js/mongodb-core.git" }, "keywords": [ "mongodb", "core" ], "dependencies": { "bson": "~1.0.4", "require_optional": "^1.0.1" }, "devDependencies": { "chai": "^4.1.2", "co": "^4.6.0", "conventional-changelog-cli": "^1.3.5", "eslint": "^4.6.1", "eslint-plugin-prettier": "^2.2.0", "jsdoc": "3.5.4", "mongodb-mock-server": "^1.0.0", "mongodb-test-runner": "^1.1.18", "prettier": "^1.6.1", "snappy": "^6.0.1" }, "peerOptionalDependencies": { "kerberos": "^0.0.23", "snappy": "^6.0.1", "bson-ext": "1.0.5" }, "author": "Christian Kvalheim", "license": "Apache-2.0", "bugs": { "url": "https://github.com/mongodb-js/mongodb-core/issues" }, "homepage": "https://github.com/mongodb-js/mongodb-core" } },{}],374:[function(require,module,exports){ 'use strict'; // Core module var core = require('mongodb-core'), Instrumentation = require('./lib/apm'); // Set up the connect function var connect = require('./lib/mongo_client').connect; // Expose error class connect.MongoError = core.MongoError; // Actual driver classes exported connect.Admin = require('./lib/admin'); connect.MongoClient = require('./lib/mongo_client'); connect.Db = require('./lib/db'); connect.Collection = require('./lib/collection'); connect.Server = require('./lib/topologies/server'); connect.ReplSet = require('./lib/topologies/replset'); connect.Mongos = require('./lib/topologies/mongos'); connect.ReadPreference = require('mongodb-core').ReadPreference; connect.GridStore = require('./lib/gridfs/grid_store'); connect.Chunk = require('./lib/gridfs/chunk'); connect.Logger = core.Logger; connect.Cursor = require('./lib/cursor'); connect.GridFSBucket = require('./lib/gridfs-stream'); // Exported to be used in tests not to be used anywhere else connect.CoreServer = require('mongodb-core').Server; connect.CoreConnection = require('mongodb-core').Connection; // BSON types exported connect.Binary = core.BSON.Binary; connect.Code = core.BSON.Code; connect.Map = core.BSON.Map; connect.DBRef = core.BSON.DBRef; connect.Double = core.BSON.Double; connect.Int32 = core.BSON.Int32; connect.Long = core.BSON.Long; connect.MinKey = core.BSON.MinKey; connect.MaxKey = core.BSON.MaxKey; connect.ObjectID = core.BSON.ObjectID; connect.ObjectId = core.BSON.ObjectID; connect.Symbol = core.BSON.Symbol; connect.Timestamp = core.BSON.Timestamp; connect.BSONRegExp = core.BSON.BSONRegExp; connect.Decimal128 = core.BSON.Decimal128; // Add connect method connect.connect = connect; // Set up the instrumentation method connect.instrument = function(options, callback) { if (typeof options === 'function') { callback = options; options = {}; } return new Instrumentation(core, options, callback); }; // Set our exports to be the connect function module.exports = connect; },{"./lib/admin":375,"./lib/apm":377,"./lib/collection":383,"./lib/cursor":385,"./lib/db":386,"./lib/gridfs-stream":388,"./lib/gridfs/chunk":390,"./lib/gridfs/grid_store":391,"./lib/mongo_client":393,"./lib/topologies/mongos":394,"./lib/topologies/replset":395,"./lib/topologies/server":396,"mongodb-core":345}],375:[function(require,module,exports){ 'use strict'; var toError = require('./utils').toError, Define = require('./metadata'), shallowClone = require('./utils').shallowClone, executeOperation = require('./utils').executeOperation; /** * @fileOverview The **Admin** class is an internal class that allows convenient access to * the admin functionality and commands for MongoDB. * * **ADMIN Cannot directly be instantiated** * @example * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * // Use the admin database for the operation * const adminDb = client.db(dbName).admin(); * * // List all the available databases * adminDb.listDatabases(function(err, dbs) { * test.equal(null, err); * test.ok(dbs.databases.length > 0); * client.close(); * }); * }); */ /** * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) * @class * @return {Admin} a collection instance. */ var Admin = function(db, topology, promiseLibrary) { if (!(this instanceof Admin)) return new Admin(db, topology); // Internal state this.s = { db: db, topology: topology, promiseLibrary: promiseLibrary }; }; var define = (Admin.define = new Define('Admin', Admin, false)); /** * The callback format for results * @callback Admin~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object} result The result object if the command was executed successfully. */ /** * Execute a command * @method * @param {object} command The command hash * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. * @param {Admin~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Admin.prototype.command = function(command, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() : {}; return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [ command, options, callback ]); }; define.classMethod('command', { callback: true, promise: true }); /** * Retrieve the server information for the current * instance of the db client * * @param {Object} [options] optional parameters for this operation * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Admin.prototype.buildInfo = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; const cmd = { buildinfo: 1 }; return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [ cmd, options, callback ]); }; define.classMethod('buildInfo', { callback: true, promise: true }); /** * Retrieve the server information for the current * instance of the db client * * @param {Object} [options] optional parameters for this operation * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Admin.prototype.serverInfo = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; const cmd = { buildinfo: 1 }; return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [ cmd, options, callback ]); }; define.classMethod('serverInfo', { callback: true, promise: true }); /** * Retrieve this db's server status. * * @param {Object} [options] optional parameters for this operation * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Admin.prototype.serverStatus = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.db.s.topology, serverStatus, [this, options, callback]); }; var serverStatus = function(self, options, callback) { self.s.db.executeDbAdminCommand({ serverStatus: 1 }, options, function(err, doc) { if (err == null && doc.ok === 1) { callback(null, doc); } else { if (err) return callback(err, false); return callback(toError(doc), false); } }); }; define.classMethod('serverStatus', { callback: true, promise: true }); /** * Ping the MongoDB server and retrieve results * * @param {Object} [options] optional parameters for this operation * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Admin.prototype.ping = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; const cmd = { ping: 1 }; return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [ cmd, options, callback ]); }; define.classMethod('ping', { callback: true, promise: true }); // Get write concern var writeConcern = function(options, db) { options = shallowClone(options); // If options already contain write concerns return it if (options.w || options.wtimeout || options.j || options.fsync) { return options; } // Set db write concern if available if (db.writeConcern) { if (options.w) options.w = db.writeConcern.w; if (options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; if (options.j) options.j = db.writeConcern.j; if (options.fsync) options.fsync = db.writeConcern.fsync; } // Return modified options return options; }; /** * Add a user to the database. * @method * @param {string} username The username. * @param {string} password The password. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.fsync=false] Specify a file sync write concern. * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Admin.prototype.addUser = function(username, password, options, callback) { var self = this; var args = Array.prototype.slice.call(arguments, 2); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() : {}; options = options || {}; // Get the options options = writeConcern(options, self.s.db); // Set the db name to admin options.dbName = 'admin'; return executeOperation(this.s.db.s.topology, this.s.db.addUser.bind(this.s.db), [ username, password, options, callback ]); }; define.classMethod('addUser', { callback: true, promise: true }); /** * Remove a user from a database * @method * @param {string} username The username. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.fsync=false] Specify a file sync write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Admin.prototype.removeUser = function(username, options, callback) { var self = this; var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() : {}; options = options || {}; // Get the options options = writeConcern(options, self.s.db); // Set the db name options.dbName = 'admin'; return executeOperation(this.s.db.s.topology, this.s.db.removeUser.bind(this.s.db), [ username, options, callback ]); }; define.classMethod('removeUser', { callback: true, promise: true }); /** * Validate an existing collection * * @param {string} collectionName The name of the collection to validate. * @param {object} [options=null] Optional settings. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback. * @return {Promise} returns Promise if no callback passed */ Admin.prototype.validateCollection = function(collectionName, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.db.s.topology, validateCollection, [ this, collectionName, options, callback ]); }; var validateCollection = function(self, collectionName, options, callback) { var command = { validate: collectionName }; var keys = Object.keys(options); // Decorate command with extra options for (var i = 0; i < keys.length; i++) { if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { command[keys[i]] = options[keys[i]]; } } self.s.db.command(command, options, function(err, doc) { if (err != null) return callback(err, null); if (doc.ok === 0) return callback(new Error('Error with validate command'), null); if (doc.result != null && doc.result.constructor !== String) return callback(new Error('Error with validation data'), null); if (doc.result != null && doc.result.match(/exception|corrupt/) != null) return callback(new Error('Error: invalid collection ' + collectionName), null); if (doc.valid != null && !doc.valid) return callback(new Error('Error: invalid collection ' + collectionName), null); return callback(null, doc); }); }; define.classMethod('validateCollection', { callback: true, promise: true }); /** * List the available databases * * @param {object} [options=null] Optional settings. * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback. * @return {Promise} returns Promise if no callback passed */ Admin.prototype.listDatabases = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; var cmd = { listDatabases: 1 }; if (options.nameOnly) cmd.nameOnly = Number(cmd.nameOnly); return executeOperation(this.s.db.s.topology, this.s.db.executeDbAdminCommand.bind(this.s.db), [ cmd, options, callback ]); }; define.classMethod('listDatabases', { callback: true, promise: true }); /** * Get ReplicaSet status * * @param {Object} [options] optional parameters for this operation * @param {ClientSession} [options.session] optional session to use for this operation * @param {Admin~resultCallback} [callback] The command result callback. * @return {Promise} returns Promise if no callback passed */ Admin.prototype.replSetGetStatus = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.db.s.topology, replSetGetStatus, [this, options, callback]); }; var replSetGetStatus = function(self, options, callback) { self.s.db.executeDbAdminCommand({ replSetGetStatus: 1 }, options, function(err, doc) { if (err == null && doc.ok === 1) return callback(null, doc); if (err) return callback(err, false); callback(toError(doc), false); }); }; define.classMethod('replSetGetStatus', { callback: true, promise: true }); module.exports = Admin; },{"./metadata":392,"./utils":399}],376:[function(require,module,exports){ 'use strict'; var inherits = require('util').inherits, MongoError = require('mongodb-core').MongoError, Readable = require('stream').Readable, Define = require('./metadata'), CoreCursor = require('./cursor'); /** * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB * allowing for iteration over the results returned from the underlying query. It supports * one by one document iteration, conversion to an array or can be iterated as a Node 4.X * or higher stream * * **AGGREGATIONCURSOR Cannot directly be instantiated** * @example * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * // Create a collection we want to drop later * const col = client.db(dbName).collection('createIndexExample1'); * // Insert a bunch of documents * col.insert([{a:1, b:1} * , {a:2, b:2}, {a:3, b:3} * , {a:4, b:4}], {w:1}, function(err, result) { * test.equal(null, err); * // Show that duplicate records got dropped * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { * test.equal(null, err); * test.equal(4, items.length); * client.close(); * }); * }); * }); */ /** * Namespace provided by the browser. * @external Readable */ /** * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) * @class AggregationCursor * @extends external:Readable * @fires AggregationCursor#data * @fires AggregationCursor#end * @fires AggregationCursor#close * @fires AggregationCursor#readable * @return {AggregationCursor} an AggregationCursor instance. */ var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); var state = AggregationCursor.INIT; var streamOptions = {}; // MaxTimeMS var maxTimeMS = null; // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Set up Readable.call(this, { objectMode: true }); // Internal state this.s = { // MaxTimeMS maxTimeMS: maxTimeMS, // State state: state, // Stream options streamOptions: streamOptions, // BSON bson: bson, // Namespace ns: ns, // Command cmd: cmd, // Options options: options, // Topology topology: topology, // Topology Options topologyOptions: topologyOptions, // Promise library promiseLibrary: promiseLibrary }; }; /** * AggregationCursor stream data event, fired for each document in the cursor. * * @event AggregationCursor#data * @type {object} */ /** * AggregationCursor stream end event * * @event AggregationCursor#end * @type {null} */ /** * AggregationCursor stream close event * * @event AggregationCursor#close * @type {null} */ /** * AggregationCursor stream readable event * * @event AggregationCursor#readable * @type {null} */ // Inherit from Readable inherits(AggregationCursor, Readable); // Extend the Cursor for (var name in CoreCursor.prototype) { AggregationCursor.prototype[name] = CoreCursor.prototype[name]; } var define = (AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true)); /** * Set the batch size for the cursor. * @method * @param {number} value The batchSize for the cursor. * @throws {MongoError} * @return {AggregationCursor} */ AggregationCursor.prototype.batchSize = function(value) { if (this.s.state === AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({ message: 'Cursor is closed', driver: true }); if (typeof value !== 'number') throw MongoError.create({ message: 'batchSize requires an integer', drvier: true }); if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; this.setCursorBatchSize(value); return this; }; define.classMethod('batchSize', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a geoNear stage to the aggregation pipeline * @method * @param {object} document The geoNear stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.geoNear = function(document) { this.s.cmd.pipeline.push({ $geoNear: document }); return this; }; define.classMethod('geoNear', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a group stage to the aggregation pipeline * @method * @param {object} document The group stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.group = function(document) { this.s.cmd.pipeline.push({ $group: document }); return this; }; define.classMethod('group', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a limit stage to the aggregation pipeline * @method * @param {number} value The state limit value. * @return {AggregationCursor} */ AggregationCursor.prototype.limit = function(value) { this.s.cmd.pipeline.push({ $limit: value }); return this; }; define.classMethod('limit', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a match stage to the aggregation pipeline * @method * @param {object} document The match stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.match = function(document) { this.s.cmd.pipeline.push({ $match: document }); return this; }; define.classMethod('match', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a maxTimeMS stage to the aggregation pipeline * @method * @param {number} value The state maxTimeMS value. * @return {AggregationCursor} */ AggregationCursor.prototype.maxTimeMS = function(value) { if (this.s.topology.lastIsMaster().minWireVersion > 2) { this.s.cmd.maxTimeMS = value; } return this; }; define.classMethod('maxTimeMS', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a out stage to the aggregation pipeline * @method * @param {number} destination The destination name. * @return {AggregationCursor} */ AggregationCursor.prototype.out = function(destination) { this.s.cmd.pipeline.push({ $out: destination }); return this; }; define.classMethod('out', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a project stage to the aggregation pipeline * @method * @param {object} document The project stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.project = function(document) { this.s.cmd.pipeline.push({ $project: document }); return this; }; define.classMethod('project', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a lookup stage to the aggregation pipeline * @method * @param {object} document The lookup stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.lookup = function(document) { this.s.cmd.pipeline.push({ $lookup: document }); return this; }; define.classMethod('lookup', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a redact stage to the aggregation pipeline * @method * @param {object} document The redact stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.redact = function(document) { this.s.cmd.pipeline.push({ $redact: document }); return this; }; define.classMethod('redact', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a skip stage to the aggregation pipeline * @method * @param {number} value The state skip value. * @return {AggregationCursor} */ AggregationCursor.prototype.skip = function(value) { this.s.cmd.pipeline.push({ $skip: value }); return this; }; define.classMethod('skip', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a sort stage to the aggregation pipeline * @method * @param {object} document The sort stage document. * @return {AggregationCursor} */ AggregationCursor.prototype.sort = function(document) { this.s.cmd.pipeline.push({ $sort: document }); return this; }; define.classMethod('sort', { callback: false, promise: false, returns: [AggregationCursor] }); /** * Add a unwind stage to the aggregation pipeline * @method * @param {number} field The unwind field name. * @return {AggregationCursor} */ AggregationCursor.prototype.unwind = function(field) { this.s.cmd.pipeline.push({ $unwind: field }); return this; }; define.classMethod('unwind', { callback: false, promise: false, returns: [AggregationCursor] }); AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; // Inherited methods define.classMethod('toArray', { callback: true, promise: true }); define.classMethod('each', { callback: true, promise: false }); define.classMethod('forEach', { callback: true, promise: false }); define.classMethod('hasNext', { callback: true, promise: true }); define.classMethod('next', { callback: true, promise: true }); define.classMethod('close', { callback: true, promise: true }); define.classMethod('isClosed', { callback: false, promise: false, returns: [Boolean] }); define.classMethod('rewind', { callback: false, promise: false }); define.classMethod('bufferedCount', { callback: false, promise: false, returns: [Number] }); define.classMethod('readBufferedDocuments', { callback: false, promise: false, returns: [Array] }); /** * Get the next available document from the cursor, returns null if no more documents are available. * @function AggregationCursor.prototype.next * @param {AggregationCursor~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * Check if there is any document still available in the cursor * @function AggregationCursor.prototype.hasNext * @param {AggregationCursor~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * The callback format for results * @callback AggregationCursor~toArrayResultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object[]} documents All the documents the satisfy the cursor. */ /** * Returns an array of documents. The caller is responsible for making sure that there * is enough memory to store the results. Note that the array only contain partial * results when this cursor had been previouly accessed. In that case, * cursor.rewind() can be used to reset the cursor. * @method AggregationCursor.prototype.toArray * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * The callback format for results * @callback AggregationCursor~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {(object|null)} result The result object if the command was executed successfully. */ /** * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, * not all of the elements will be iterated if this cursor had been previouly accessed. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements * at any given time if batch size is specified. Otherwise, the caller is responsible * for making sure that the entire result can fit the memory. * @method AggregationCursor.prototype.each * @param {AggregationCursor~resultCallback} callback The result callback. * @throws {MongoError} * @return {null} */ /** * Close the cursor, sending a AggregationCursor command and emitting close. * @method AggregationCursor.prototype.close * @param {AggregationCursor~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ /** * Is the cursor closed * @method AggregationCursor.prototype.isClosed * @return {boolean} */ /** * Execute the explain for the cursor * @method AggregationCursor.prototype.explain * @param {AggregationCursor~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ /** * Clone the cursor * @function AggregationCursor.prototype.clone * @return {AggregationCursor} */ /** * Resets the cursor * @function AggregationCursor.prototype.rewind * @return {AggregationCursor} */ /** * The callback format for the forEach iterator method * @callback AggregationCursor~iteratorCallback * @param {Object} doc An emitted document for the iterator */ /** * The callback error format for the forEach iterator method * @callback AggregationCursor~endCallback * @param {MongoError} error An error instance representing the error during the execution. */ /* * Iterates over all the documents for this cursor using the iterator, callback pattern. * @method AggregationCursor.prototype.forEach * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. * @param {AggregationCursor~endCallback} callback The end callback. * @throws {MongoError} * @return {null} */ AggregationCursor.INIT = 0; AggregationCursor.OPEN = 1; AggregationCursor.CLOSED = 2; module.exports = AggregationCursor; },{"./cursor":385,"./metadata":392,"mongodb-core":345,"stream":548,"util":563}],377:[function(require,module,exports){ 'use strict'; var EventEmitter = require('events').EventEmitter, inherits = require('util').inherits; // Get prototypes var AggregationCursor = require('./aggregation_cursor'), CommandCursor = require('./command_cursor'), OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, GridStore = require('./gridfs/grid_store'), Cursor = require('./cursor'), Collection = require('./collection'), Db = require('./db'); var basicOperationIdGenerator = { operationId: 1, next: function() { return this.operationId++; } }; var basicTimestampGenerator = { current: function() { return new Date().getTime(); }, duration: function(start, end) { return end - start; } }; var senstiveCommands = [ 'authenticate', 'saslStart', 'saslContinue', 'getnonce', 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb' ]; var Instrumentation = function(core, options, callback) { options = options || {}; // Optional id generators var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; // Optional timestamp generator var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; // Extend with event emitter functionality EventEmitter.call(this); // Contains all the instrumentation overloads this.overloads = []; // --------------------------------------------------------- // // Instrument prototype // // --------------------------------------------------------- var instrumentPrototype = function(callback) { var instrumentations = []; // Classes to support var classes = [ GridStore, OrderedBulkOperation, UnorderedBulkOperation, CommandCursor, AggregationCursor, Cursor, Collection, Db ]; // Add instrumentations to the available list for (var i = 0; i < classes.length; i++) { if (classes[i].define) { instrumentations.push(classes[i].define.generate()); } } // Return the list of instrumentation points callback(null, instrumentations); }; // Did the user want to instrument the prototype if (typeof callback === 'function') { instrumentPrototype(callback); } // --------------------------------------------------------- // // Server // // --------------------------------------------------------- // Reference var self = this; // Names of methods we need to wrap var methods = ['command', 'insert', 'update', 'remove']; // Prototype var proto = core.Server.prototype; // Core server method we are going to wrap methods.forEach(function(x) { var func = proto[x]; // Add to overloaded methods self.overloads.push({ proto: proto, name: x, func: func }); // The actual prototype proto[x] = function() { var requestId = core.Query.nextRequestId(); // Get the aruments var args = Array.prototype.slice.call(arguments, 0); var ns = args[0]; var commandObj = args[1]; var options = args[2] || {}; var keys = Object.keys(commandObj); var commandName = keys[0]; var db = ns.split('.')[0]; // Get the collection var col = ns.split('.'); col.shift(); col = col.join('.'); // Do we have a legacy insert/update/remove command if (x === 'insert') { //} && !this.lastIsMaster().maxWireVersion) { commandName = 'insert'; // Re-write the command commandObj = { insert: col, documents: commandObj }; if (options.writeConcern && Object.keys(options.writeConcern).length > 0) { commandObj.writeConcern = options.writeConcern; } commandObj.ordered = options.ordered !== undefined ? options.ordered : true; } else if (x === 'update') { // && !this.lastIsMaster().maxWireVersion) { commandName = 'update'; // Re-write the command commandObj = { update: col, updates: commandObj }; if (options.writeConcern && Object.keys(options.writeConcern).length > 0) { commandObj.writeConcern = options.writeConcern; } commandObj.ordered = options.ordered !== undefined ? options.ordered : true; } else if (x === 'remove') { //&& !this.lastIsMaster().maxWireVersion) { commandName = 'delete'; // Re-write the command commandObj = { delete: col, deletes: commandObj }; if (options.writeConcern && Object.keys(options.writeConcern).length > 0) { commandObj.writeConcern = options.writeConcern; } commandObj.ordered = options.ordered !== undefined ? options.ordered : true; } // Get the callback var callback = args.pop(); // Set current callback operation id from the current context or create // a new one var ourOpId = callback.operationId || operationIdGenerator.next(); // Get a connection reference for this server instance var connection = this.s.pool.get(); // Emit the start event for the command var command = { // Returns the command. command: commandObj, // Returns the database name. databaseName: db, // Returns the command name. commandName: commandName, // Returns the driver generated request id. requestId: requestId, // Returns the driver generated operation id. // This is used to link events together such as bulk write operations. OPTIONAL. operationId: ourOpId, // Returns the connection id for the command. For languages that do not have this, // this MUST return the driver equivalent which MUST include the server address and port. // The name of this field is flexible to match the object that is returned from the driver. connectionId: connection }; // Filter out any sensitive commands if (senstiveCommands.indexOf(commandName.toLowerCase()) !== -1) { command.commandObj = {}; command.commandObj[commandName] = true; } // Emit the started event self.emit('started', command); // Start time var startTime = timestampGenerator.current(); // Push our handler callback args.push(function(err, r) { var endTime = timestampGenerator.current(); var command = { duration: timestampGenerator.duration(startTime, endTime), commandName: commandName, requestId: requestId, operationId: ourOpId, connectionId: connection }; // If we have an error if (err || (r && r.result && r.result.ok === 0)) { command.failure = err || r.result.writeErrors || r.result; // Filter out any sensitive commands if (senstiveCommands.indexOf(commandName.toLowerCase()) !== -1) { command.failure = {}; } self.emit('failed', command); } else if (commandObj && commandObj.writeConcern && commandObj.writeConcern.w === 0) { // If we have write concern 0 command.reply = { ok: 1 }; self.emit('succeeded', command); } else { command.reply = r && r.result ? r.result : r; // Filter out any sensitive commands if (senstiveCommands.indexOf(commandName.toLowerCase()) !== -1) { command.reply = {}; } self.emit('succeeded', command); } // Return to caller callback(err, r); }); // Apply the call func.apply(this, args); }; }); // --------------------------------------------------------- // // Bulk Operations // // --------------------------------------------------------- // Inject ourselves into the Bulk methods methods = ['execute']; var prototypes = [ require('./bulk/ordered').Bulk.prototype, require('./bulk/unordered').Bulk.prototype ]; prototypes.forEach(function(proto) { // Core server method we are going to wrap methods.forEach(function(x) { var func = proto[x]; // Add to overloaded methods self.overloads.push({ proto: proto, name: x, func: func }); // The actual prototype proto[x] = function() { // Get the aruments var args = Array.prototype.slice.call(arguments, 0); // Set an operation Id on the bulk object this.operationId = operationIdGenerator.next(); // Get the callback var callback = args.pop(); // If we have a callback use this if (typeof callback === 'function') { args.push(function(err, r) { // Return to caller callback(err, r); }); // Apply the call func.apply(this, args); } else { return func.apply(this, args); } }; }); }); // --------------------------------------------------------- // // Cursor // // --------------------------------------------------------- // Inject ourselves into the Cursor methods methods = ['_find', '_getmore', '_killcursor']; prototypes = [ require('./cursor').prototype, require('./command_cursor').prototype, require('./aggregation_cursor').prototype ]; // Command name translation var commandTranslation = { _find: 'find', _getmore: 'getMore', _killcursor: 'killCursors', _explain: 'explain' }; prototypes.forEach(function(proto) { // Core server method we are going to wrap methods.forEach(function(x) { var func = proto[x]; // Add to overloaded methods self.overloads.push({ proto: proto, name: x, func: func }); // The actual prototype proto[x] = function() { var cursor = this; var requestId = core.Query.nextRequestId(); var ourOpId = operationIdGenerator.next(); var parts = this.ns.split('.'); var db = parts[0]; // Get the collection parts.shift(); var collection = parts.join('.'); // Set the command var command = this.query; var cmd = this.s.cmd; // If we have a find method, set the operationId on the cursor if (x === '_find') { cursor.operationId = ourOpId; } // Do we have a find command rewrite it if (x === '_getmore') { command = { getMore: this.cursorState.cursorId, collection: collection, batchSize: cmd.batchSize }; if (cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; } else if (x === '_killcursor') { command = { killCursors: collection, cursors: [this.cursorState.cursorId] }; } else if (cmd.find) { command = { find: collection, filter: cmd.query }; if (cmd.sort) command.sort = cmd.sort; if (cmd.fields) command.projection = cmd.fields; if (cmd.limit && cmd.limit < 0) { command.limit = Math.abs(cmd.limit); command.singleBatch = true; } else if (cmd.limit) { command.limit = Math.abs(cmd.limit); } // Options if (cmd.skip) command.skip = cmd.skip; if (cmd.hint) command.hint = cmd.hint; if (cmd.batchSize) command.batchSize = cmd.batchSize; if (typeof cmd.returnKey === 'boolean') command.returnKey = cmd.returnKey; if (cmd.comment) command.comment = cmd.comment; if (cmd.min) command.min = cmd.min; if (cmd.max) command.max = cmd.max; if (cmd.maxScan) command.maxScan = cmd.maxScan; if (cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; // Flags if (typeof cmd.awaitData === 'boolean') command.awaitData = cmd.awaitData; if (typeof cmd.snapshot === 'boolean') command.snapshot = cmd.snapshot; if (typeof cmd.tailable === 'boolean') command.tailable = cmd.tailable; if (typeof cmd.oplogReplay === 'boolean') command.oplogReplay = cmd.oplogReplay; if (typeof cmd.noCursorTimeout === 'boolean') command.noCursorTimeout = cmd.noCursorTimeout; if (typeof cmd.partial === 'boolean') command.partial = cmd.partial; if (typeof cmd.showDiskLoc === 'boolean') command.showRecordId = cmd.showDiskLoc; // Read Concern if (cmd.readConcern) command.readConcern = cmd.readConcern; // Override method if (cmd.explain) command.explain = cmd.explain; if (cmd.exhaust) command.exhaust = cmd.exhaust; // If we have a explain flag if (cmd.explain) { // Create fake explain command command = { explain: command, verbosity: 'allPlansExecution' }; // Set readConcern on the command if available if (cmd.readConcern) command.readConcern = cmd.readConcern; // Set up the _explain name for the command x = '_explain'; } } else { command = cmd; } // Set up the connection var connectionId = null; // Set local connection if (this.connection) connectionId = this.connection; if (!connectionId && this.topology && this.topology.getConnection) connectionId = this.topology.getConnection(); // Get the command Name var commandName = x === '_find' ? Object.keys(command)[0] : commandTranslation[x]; // Emit the start event for the command command = { // Returns the command. command: command, // Returns the database name. databaseName: db, // Returns the command name. commandName: commandName, // Returns the driver generated request id. requestId: requestId, // Returns the driver generated operation id. // This is used to link events together such as bulk write operations. OPTIONAL. operationId: this.operationId, // Returns the connection id for the command. For languages that do not have this, // this MUST return the driver equivalent which MUST include the server address and port. // The name of this field is flexible to match the object that is returned from the driver. connectionId: connectionId }; // Get the aruments var args = Array.prototype.slice.call(arguments, 0); // Get the callback var callback = args.pop(); // We do not have a callback but a Promise if (typeof callback === 'function' || command.commandName === 'killCursors') { var startTime = timestampGenerator.current(); // Emit the started event self.emit('started', command); // Emit succeeded event with killcursor if we have a legacy protocol if ( command.commandName === 'killCursors' && this.topology.lastIsMaster() && this.topology.lastIsMaster().maxWireVersion < 4 ) { // Emit the succeeded command command = { duration: timestampGenerator.duration(startTime, timestampGenerator.current()), commandName: commandName, requestId: requestId, operationId: cursor.operationId, connectionId: cursor.topology.getConnection(), reply: [{ ok: 1 }] }; // Apply callback to the list of args args.push(callback); // Apply the call func.apply(this, args); // Emit the command return self.emit('succeeded', command); } // Add our callback handler args.push(function(err, r) { if (err) { // Command var command = { duration: timestampGenerator.duration(startTime, timestampGenerator.current()), commandName: commandName, requestId: requestId, operationId: ourOpId, connectionId: cursor.topology.getConnection(), failure: err }; // Emit the command self.emit('failed', command); } else { if (r && r.documents) { r = r.documents[0]; } if (commandName.toLowerCase() === 'getmore' && (r == null || r.cursor == null)) { r = { cursor: { id: cursor.cursorState.cursorId, ns: cursor.ns, nextBatch: cursor.cursorState.documents }, ok: 1 }; } else if ( (commandName.toLowerCase() === 'find' || commandName.toLowerCase() === 'aggregate' || commandName.toLowerCase() === 'listcollections') && (r == null || r.cursor == null) ) { r = { cursor: { id: cursor.cursorState.cursorId, ns: cursor.ns, firstBatch: cursor.cursorState.documents }, ok: 1 }; } else if (commandName.toLowerCase() === 'killcursors' && r == null) { r = { cursorsUnknown: [cursor.cursorState.lastCursorId], ok: 1 }; } // cursor id is zero, we can issue success command command = { duration: timestampGenerator.duration(startTime, timestampGenerator.current()), commandName: commandName, requestId: requestId, operationId: cursor.operationId, connectionId: cursor.topology.getConnection(), reply: r && r.result ? r.result : r }; // Emit the command self.emit('succeeded', command); } // Return if (!callback) return; // Return to caller callback(err, r); }); // Apply the call func.apply(this, args); } else { // Assume promise, push back the missing value args.push(callback); // Get the promise var promise = func.apply(this, args); // Return a new promise return new cursor.s.promiseLibrary(function(resolve, reject) { var startTime = timestampGenerator.current(); // Emit the started event self.emit('started', command); // Execute the function promise .then(function() { // cursor id is zero, we can issue success command var command = { duration: timestampGenerator.duration(startTime, timestampGenerator.current()), commandName: commandName, requestId: requestId, operationId: cursor.operationId, connectionId: cursor.topology.getConnection(), reply: cursor.cursorState.documents }; // Emit the command self.emit('succeeded', command); }) .catch(function(err) { // Command var command = { duration: timestampGenerator.duration(startTime, timestampGenerator.current()), commandName: commandName, requestId: requestId, operationId: ourOpId, connectionId: cursor.topology.getConnection(), failure: err }; // Emit the command self.emit('failed', command); // reject the promise reject(err); }); }); } }; }); }); }; inherits(Instrumentation, EventEmitter); Instrumentation.prototype.uninstrument = function() { for (var i = 0; i < this.overloads.length; i++) { var obj = this.overloads[i]; obj.proto[obj.name] = obj.func; } // Remove all listeners this.removeAllListeners('started'); this.removeAllListeners('succeeded'); this.removeAllListeners('failed'); }; module.exports = Instrumentation; },{"./aggregation_cursor":376,"./bulk/ordered":380,"./bulk/unordered":381,"./collection":383,"./command_cursor":384,"./cursor":385,"./db":386,"./gridfs/grid_store":391,"events":316,"util":563}],378:[function(require,module,exports){ (function (process){ 'use strict'; var shallowClone = require('./utils').shallowClone, handleCallback = require('./utils').handleCallback, MongoError = require('mongodb-core').MongoError, f = require('util').format; var authenticate = function(client, username, password, options, callback) { // Did the user destroy the topology if (client.topology && client.topology.isDestroyed()) return callback(new MongoError('topology was destroyed')); // the default db to authenticate against is 'self' // if authententicate is called from a retry context, it may be another one, like admin var authdb = options.dbName; authdb = options.authdb ? options.authdb : authdb; authdb = options.authSource ? options.authSource : authdb; // Callback var _callback = function(err, result) { if (client.listeners('authenticated').length > 0) { client.emit('authenticated', err, result); } // Return to caller handleCallback(callback, err, result); }; // authMechanism var authMechanism = options.authMechanism || ''; authMechanism = authMechanism.toUpperCase(); // If classic auth delegate to auth command if (authMechanism === 'MONGODB-CR') { client.topology.auth('mongocr', authdb, username, password, function(err) { if (err) return handleCallback(callback, err, false); _callback(null, true); }); } else if (authMechanism === 'PLAIN') { client.topology.auth('plain', authdb, username, password, function(err) { if (err) return handleCallback(callback, err, false); _callback(null, true); }); } else if (authMechanism === 'MONGODB-X509') { client.topology.auth('x509', authdb, username, password, function(err) { if (err) return handleCallback(callback, err, false); _callback(null, true); }); } else if (authMechanism === 'SCRAM-SHA-1') { client.topology.auth('scram-sha-1', authdb, username, password, function(err) { if (err) return handleCallback(callback, err, false); _callback(null, true); }); } else if (authMechanism === 'GSSAPI') { if (process.platform === 'win32') { client.topology.auth('sspi', authdb, username, password, options, function(err) { if (err) return handleCallback(callback, err, false); _callback(null, true); }); } else { client.topology.auth('gssapi', authdb, username, password, options, function(err) { if (err) return handleCallback(callback, err, false); _callback(null, true); }); } } else if (authMechanism === 'DEFAULT') { client.topology.auth('default', authdb, username, password, function(err) { if (err) return handleCallback(callback, err, false); _callback(null, true); }); } else { handleCallback( callback, MongoError.create({ message: f('authentication mechanism %s not supported', options.authMechanism), driver: true }) ); } }; module.exports = function(self, username, password, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Shallow copy the options options = shallowClone(options); // Set default mechanism if (!options.authMechanism) { options.authMechanism = 'DEFAULT'; } else if ( options.authMechanism !== 'GSSAPI' && options.authMechanism !== 'DEFAULT' && options.authMechanism !== 'MONGODB-CR' && options.authMechanism !== 'MONGODB-X509' && options.authMechanism !== 'SCRAM-SHA-1' && options.authMechanism !== 'PLAIN' ) { return handleCallback( callback, MongoError.create({ message: 'only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism', driver: true }) ); } // If we have a callback fallback if (typeof callback === 'function') return authenticate(self, username, password, options, function(err, r) { // Support failed auth method if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; // Reject error if (err) return callback(err, r); callback(null, r); }); // Return a promise return new self.s.promiseLibrary(function(resolve, reject) { authenticate(self, username, password, options, function(err, r) { // Support failed auth method if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; // Reject error if (err) return reject(err); resolve(r); }); }); }; }).call(this,require('_process')) },{"./utils":399,"_process":507,"mongodb-core":345,"util":563}],379:[function(require,module,exports){ 'use strict'; var Long = require('mongodb-core').BSON.Long, MongoError = require('mongodb-core').MongoError, util = require('util'); // Error codes var UNKNOWN_ERROR = 8; var INVALID_BSON_ERROR = 22; var WRITE_CONCERN_ERROR = 64; var MULTIPLE_ERROR = 65; // Insert types var INSERT = 1; var UPDATE = 2; var REMOVE = 3; // Get write concern var writeConcern = function(target, col, options) { var writeConcern = {}; // Collection level write concern if (col.writeConcern && col.writeConcern.w != null) writeConcern.w = col.writeConcern.w; if (col.writeConcern && col.writeConcern.j != null) writeConcern.j = col.writeConcern.j; if (col.writeConcern && col.writeConcern.fsync != null) writeConcern.fsync = col.writeConcern.fsync; if (col.writeConcern && col.writeConcern.wtimeout != null) writeConcern.wtimeout = col.writeConcern.wtimeout; // Options level write concern if (options && options.w != null) writeConcern.w = options.w; if (options && options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; if (options && options.j != null) writeConcern.j = options.j; if (options && options.fsync != null) writeConcern.fsync = options.fsync; // Return write concern return writeConcern; }; /** * Helper function to define properties * @ignore */ var defineReadOnlyProperty = function(self, name, value) { Object.defineProperty(self, name, { enumerable: true, get: function() { return value; } }); }; /** * Keeps the state of a unordered batch so we can rewrite the results * correctly after command execution * @ignore */ var Batch = function(batchType, originalZeroIndex) { this.originalZeroIndex = originalZeroIndex; this.currentIndex = 0; this.originalIndexes = []; this.batchType = batchType; this.operations = []; this.size = 0; this.sizeBytes = 0; }; /** * Wraps a legacy operation so we can correctly rewrite it's error * @ignore */ var LegacyOp = function(batchType, operation, index) { this.batchType = batchType; this.index = index; this.operation = operation; }; /** * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) * * @class * @property {boolean} ok Did bulk operation correctly execute * @property {number} nInserted number of inserted documents * @property {number} nUpdated number of documents updated logically * @property {number} nUpserted Number of upserted documents * @property {number} nModified Number of documents updated physically on disk * @property {number} nRemoved Number of removed documents * @return {BulkWriteResult} a BulkWriteResult instance */ var BulkWriteResult = function(bulkResult) { defineReadOnlyProperty(this, 'ok', bulkResult.ok); defineReadOnlyProperty(this, 'nInserted', bulkResult.nInserted); defineReadOnlyProperty(this, 'nUpserted', bulkResult.nUpserted); defineReadOnlyProperty(this, 'nMatched', bulkResult.nMatched); defineReadOnlyProperty(this, 'nModified', bulkResult.nModified); defineReadOnlyProperty(this, 'nRemoved', bulkResult.nRemoved); /** * Return an array of inserted ids * * @return {object[]} */ this.getInsertedIds = function() { return bulkResult.insertedIds; }; /** * Return an array of upserted ids * * @return {object[]} */ this.getUpsertedIds = function() { return bulkResult.upserted; }; /** * Return the upserted id at position x * * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index * @return {object} */ this.getUpsertedIdAt = function(index) { return bulkResult.upserted[index]; }; /** * Return raw internal result * * @return {object} */ this.getRawResponse = function() { return bulkResult; }; /** * Returns true if the bulk operation contains a write error * * @return {boolean} */ this.hasWriteErrors = function() { return bulkResult.writeErrors.length > 0; }; /** * Returns the number of write errors off the bulk operation * * @return {number} */ this.getWriteErrorCount = function() { return bulkResult.writeErrors.length; }; /** * Returns a specific write error object * * @param {number} index of the write error to return, returns null if there is no result for passed in index * @return {WriteError} */ this.getWriteErrorAt = function(index) { if (index < bulkResult.writeErrors.length) { return bulkResult.writeErrors[index]; } return null; }; /** * Retrieve all write errors * * @return {object[]} */ this.getWriteErrors = function() { return bulkResult.writeErrors; }; /** * Retrieve lastOp if available * * @return {object} */ this.getLastOp = function() { return bulkResult.lastOp; }; /** * Retrieve the write concern error if any * * @return {WriteConcernError} */ this.getWriteConcernError = function() { if (bulkResult.writeConcernErrors.length === 0) { return null; } else if (bulkResult.writeConcernErrors.length === 1) { // Return the error return bulkResult.writeConcernErrors[0]; } else { // Combine the errors var errmsg = ''; for (var i = 0; i < bulkResult.writeConcernErrors.length; i++) { var err = bulkResult.writeConcernErrors[i]; errmsg = errmsg + err.errmsg; // TODO: Something better if (i === 0) errmsg = errmsg + ' and '; } return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); } }; this.toJSON = function() { return bulkResult; }; this.toString = function() { return 'BulkWriteResult(' + this.toJSON(bulkResult) + ')'; }; this.isOk = function() { return bulkResult.ok === 1; }; }; /** * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) * * @class * @property {number} code Write concern error code. * @property {string} errmsg Write concern error message. * @return {WriteConcernError} a WriteConcernError instance */ var WriteConcernError = function(err) { if (!(this instanceof WriteConcernError)) return new WriteConcernError(err); // Define properties defineReadOnlyProperty(this, 'code', err.code); defineReadOnlyProperty(this, 'errmsg', err.errmsg); this.toJSON = function() { return { code: err.code, errmsg: err.errmsg }; }; this.toString = function() { return 'WriteConcernError(' + err.errmsg + ')'; }; }; /** * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) * * @class * @property {number} code Write concern error code. * @property {number} index Write concern error original bulk operation index. * @property {string} errmsg Write concern error message. * @return {WriteConcernError} a WriteConcernError instance */ var WriteError = function(err) { if (!(this instanceof WriteError)) return new WriteError(err); // Define properties defineReadOnlyProperty(this, 'code', err.code); defineReadOnlyProperty(this, 'index', err.index); defineReadOnlyProperty(this, 'errmsg', err.errmsg); // // Define access methods this.getOperation = function() { return err.op; }; this.toJSON = function() { return { code: err.code, index: err.index, errmsg: err.errmsg, op: err.op }; }; this.toString = function() { return 'WriteError(' + JSON.stringify(this.toJSON()) + ')'; }; }; /** * Merges results into shared data structure * @ignore */ var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { // If we have an error set the result to be the err object if (err) { result = err; } else if (result && result.result) { result = result.result; } else if (result == null) { return; } // Do we have a top level error stop processing and return if (result.ok === 0 && bulkResult.ok === 1) { bulkResult.ok = 0; var writeError = { index: 0, code: result.code || 0, errmsg: result.message, op: batch.operations[0] }; bulkResult.writeErrors.push(new WriteError(writeError)); return; } else if (result.ok === 0 && bulkResult.ok === 0) { return; } // Deal with opTime if available if (result.opTime || result.lastOp) { var opTime = result.lastOp || result.opTime; var lastOpTS = null; var lastOpT = null; // We have a time stamp if (opTime && opTime._bsontype === 'Timestamp') { if (bulkResult.lastOp == null) { bulkResult.lastOp = opTime; } else if (opTime.greaterThan(bulkResult.lastOp)) { bulkResult.lastOp = opTime; } } else { // Existing TS if (bulkResult.lastOp) { lastOpTS = typeof bulkResult.lastOp.ts === 'number' ? Long.fromNumber(bulkResult.lastOp.ts) : bulkResult.lastOp.ts; lastOpT = typeof bulkResult.lastOp.t === 'number' ? Long.fromNumber(bulkResult.lastOp.t) : bulkResult.lastOp.t; } // Current OpTime TS var opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; var opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; // Compare the opTime's if (bulkResult.lastOp == null) { bulkResult.lastOp = opTime; } else if (opTimeTS.greaterThan(lastOpTS)) { bulkResult.lastOp = opTime; } else if (opTimeTS.equals(lastOpTS)) { if (opTimeT.greaterThan(lastOpT)) { bulkResult.lastOp = opTime; } } } } // If we have an insert Batch type if (batch.batchType === INSERT && result.n) { bulkResult.nInserted = bulkResult.nInserted + result.n; } // If we have an insert Batch type if (batch.batchType === REMOVE && result.n) { bulkResult.nRemoved = bulkResult.nRemoved + result.n; } var nUpserted = 0; // We have an array of upserted values, we need to rewrite the indexes if (Array.isArray(result.upserted)) { nUpserted = result.upserted.length; for (var i = 0; i < result.upserted.length; i++) { bulkResult.upserted.push({ index: result.upserted[i].index + batch.originalZeroIndex, _id: result.upserted[i]._id }); } } else if (result.upserted) { nUpserted = 1; bulkResult.upserted.push({ index: batch.originalZeroIndex, _id: result.upserted }); } // If we have an update Batch type if (batch.batchType === UPDATE && result.n) { var nModified = result.nModified; bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); if (typeof nModified === 'number') { bulkResult.nModified = bulkResult.nModified + nModified; } else { bulkResult.nModified = null; } } if (Array.isArray(result.writeErrors)) { for (i = 0; i < result.writeErrors.length; i++) { writeError = { index: batch.originalZeroIndex + result.writeErrors[i].index, code: result.writeErrors[i].code, errmsg: result.writeErrors[i].errmsg, op: batch.operations[result.writeErrors[i].index] }; bulkResult.writeErrors.push(new WriteError(writeError)); } } if (result.writeConcernError) { bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); } }; // // Clone the options var cloneOptions = function(options) { var clone = {}; var keys = Object.keys(options); for (var i = 0; i < keys.length; i++) { clone[keys[i]] = options[keys[i]]; } return clone; }; /** * Creates a new BulkWriteError * * @class * @param {Error|string|object} message The error message * @param {BulkWriteResult} result The result of the bulk write operation * @return {BulkWriteError} A BulkWriteError instance * @extends {MongoError} */ const BulkWriteError = function(error, result) { var message = error.err || error.errmsg || error.errMessage || error; MongoError.call(this, message); var keys = typeof error === 'object' ? Object.keys(error) : []; for (var i = 0; i < keys.length; i++) { this[keys[i]] = error[keys[i]]; } this.name = 'BulkWriteError'; this.result = result; }; util.inherits(BulkWriteError, MongoError); // Exports symbols exports.BulkWriteError = BulkWriteError; exports.BulkWriteResult = BulkWriteResult; exports.WriteError = WriteError; exports.Batch = Batch; exports.LegacyOp = LegacyOp; exports.mergeBatchResults = mergeBatchResults; exports.cloneOptions = cloneOptions; exports.writeConcern = writeConcern; exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; exports.MULTIPLE_ERROR = MULTIPLE_ERROR; exports.UNKNOWN_ERROR = UNKNOWN_ERROR; exports.INSERT = INSERT; exports.UPDATE = UPDATE; exports.REMOVE = REMOVE; },{"mongodb-core":345,"util":563}],380:[function(require,module,exports){ 'use strict'; var common = require('./common'), utils = require('../utils'), toError = require('../utils').toError, handleCallback = require('../utils').handleCallback, shallowClone = utils.shallowClone, BulkWriteResult = common.BulkWriteResult, ObjectID = require('mongodb-core').BSON.ObjectID, Define = require('../metadata'), BSON = require('mongodb-core').BSON, Batch = common.Batch, mergeBatchResults = common.mergeBatchResults, executeOperation = require('../utils').executeOperation, BulkWriteError = require('./common').BulkWriteError; var bson = new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]); /** * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) * @class * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. */ var FindOperatorsOrdered = function(self) { this.s = self.s; }; /** * Add a single update document to the bulk operation * * @method * @param {object} doc update operations * @throws {MongoError} * @return {OrderedBulkOperation} */ FindOperatorsOrdered.prototype.update = function(updateDocument) { // Perform upsert var upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; // Establish the update command var document = { q: this.s.currentOp.selector, u: updateDocument, multi: true, upsert: upsert }; // Clear out current Op this.s.currentOp = null; // Add the update document to the list return addToOperationsList(this, common.UPDATE, document); }; /** * Add a single update one document to the bulk operation * * @method * @param {object} doc update operations * @throws {MongoError} * @return {OrderedBulkOperation} */ FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { // Perform upsert var upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; // Establish the update command var document = { q: this.s.currentOp.selector, u: updateDocument, multi: false, upsert: upsert }; // Clear out current Op this.s.currentOp = null; // Add the update document to the list return addToOperationsList(this, common.UPDATE, document); }; /** * Add a replace one operation to the bulk operation * * @method * @param {object} doc the new document to replace the existing one with * @throws {MongoError} * @return {OrderedBulkOperation} */ FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { this.updateOne(updateDocument); }; /** * Upsert modifier for update bulk operation * * @method * @throws {MongoError} * @return {FindOperatorsOrdered} */ FindOperatorsOrdered.prototype.upsert = function() { this.s.currentOp.upsert = true; return this; }; /** * Add a remove one operation to the bulk operation * * @method * @throws {MongoError} * @return {OrderedBulkOperation} */ FindOperatorsOrdered.prototype.deleteOne = function() { // Establish the update command var document = { q: this.s.currentOp.selector, limit: 1 }; // Clear out current Op this.s.currentOp = null; // Add the remove document to the list return addToOperationsList(this, common.REMOVE, document); }; // Backward compatibility FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; /** * Add a remove operation to the bulk operation * * @method * @throws {MongoError} * @return {OrderedBulkOperation} */ FindOperatorsOrdered.prototype.delete = function() { // Establish the update command var document = { q: this.s.currentOp.selector, limit: 0 }; // Clear out current Op this.s.currentOp = null; // Add the remove document to the list return addToOperationsList(this, common.REMOVE, document); }; // Backward compatibility FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; // Add to internal list of documents var addToOperationsList = function(_self, docType, document) { // Get the bsonSize var bsonSize = bson.calculateObjectSize(document, { checkKeys: false }); // Throw error if the doc is bigger than the max BSON size if (bsonSize >= _self.s.maxBatchSizeBytes) { throw toError('document is larger than the maximum size ' + _self.s.maxBatchSizeBytes); } // Create a new batch object if we don't have a current one if (_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); // Check if we need to create a new batch if ( _self.s.currentBatchSize + 1 >= _self.s.maxWriteBatchSize || _self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes >= _self.s.maxBatchSizeBytes || _self.s.currentBatch.batchType !== docType ) { // Save the batch to the execution stack _self.s.batches.push(_self.s.currentBatch); // Create a new batch _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); // Reset the current size trackers _self.s.currentBatchSize = 0; _self.s.currentBatchSizeBytes = 0; } else { // Update current batch size _self.s.currentBatchSize = _self.s.currentBatchSize + 1; _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; } if (docType === common.INSERT) { _self.s.bulkResult.insertedIds.push({ index: _self.s.currentIndex, _id: document._id }); } // We have an array of documents if (Array.isArray(document)) { throw toError('operation passed in cannot be an Array'); } else { _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); _self.s.currentBatch.operations.push(document); _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; _self.s.currentIndex = _self.s.currentIndex + 1; } // Return self return _self; }; /** * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) * @class * @property {number} length Get the number of operations in the bulk. * @return {OrderedBulkOperation} a OrderedBulkOperation instance. */ function OrderedBulkOperation(topology, collection, options) { options = options == null ? {} : options; // TODO Bring from driver information in isMaster var executed = false; // Current item var currentOp = null; // Handle to the bson serializer, used to calculate running sizes var bson = topology.bson; // Namespace for the operation var namespace = collection.collectionName; // Set max byte size var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize ? topology.isMasterDoc.maxBsonObjectSize : 1024 * 1025 * 16; var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize ? topology.isMasterDoc.maxWriteBatchSize : 1000; // Get the write concern var writeConcern = common.writeConcern(shallowClone(options), collection, options); // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Final results var bulkResult = { ok: 1, writeErrors: [], writeConcernErrors: [], insertedIds: [], nInserted: 0, nUpserted: 0, nMatched: 0, nModified: 0, nRemoved: 0, upserted: [] }; // Internal state this.s = { // Final result bulkResult: bulkResult, // Current batch state currentBatch: null, currentIndex: 0, currentBatchSize: 0, currentBatchSizeBytes: 0, batches: [], // Write concern writeConcern: writeConcern, // Max batch size options maxBatchSizeBytes: maxBatchSizeBytes, maxWriteBatchSize: maxWriteBatchSize, // Namespace namespace: namespace, // BSON bson: bson, // Topology topology: topology, // Options options: options, // Current operation currentOp: currentOp, // Executed executed: executed, // Collection collection: collection, // Promise Library promiseLibrary: promiseLibrary, // Fundamental error err: null, // Bypass validation bypassDocumentValidation: typeof options.bypassDocumentValidation === 'boolean' ? options.bypassDocumentValidation : false, // check keys checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true }; } var define = (OrderedBulkOperation.define = new Define( 'OrderedBulkOperation', OrderedBulkOperation, false )); OrderedBulkOperation.prototype.raw = function(op) { var key = Object.keys(op)[0]; // Set up the force server object id var forceServerObjectId = typeof this.s.options.forceServerObjectId === 'boolean' ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; // Update operations if ( (op.updateOne && op.updateOne.q) || (op.updateMany && op.updateMany.q) || (op.replaceOne && op.replaceOne.q) ) { op[key].multi = op.updateOne || op.replaceOne ? false : true; return addToOperationsList(this, common.UPDATE, op[key]); } // Crud spec update format if (op.updateOne || op.updateMany || op.replaceOne) { var multi = op.updateOne || op.replaceOne ? false : true; var operation = { q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi }; operation.upsert = op[key].upsert ? true : false; if (op.collation) operation.collation = op.collation; if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; return addToOperationsList(this, common.UPDATE, operation); } // Remove operations if ( op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || (op.deleteMany && op.deleteMany.q) ) { op[key].limit = op.removeOne ? 1 : 0; return addToOperationsList(this, common.REMOVE, op[key]); } // Crud spec delete operations, less efficient if (op.deleteOne || op.deleteMany) { var limit = op.deleteOne ? 1 : 0; operation = { q: op[key].filter, limit: limit }; if (op.collation) operation.collation = op.collation; return addToOperationsList(this, common.REMOVE, operation); } // Insert operations if (op.insertOne && op.insertOne.document == null) { if (forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); return addToOperationsList(this, common.INSERT, op.insertOne); } else if (op.insertOne && op.insertOne.document) { if (forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); return addToOperationsList(this, common.INSERT, op.insertOne.document); } if (op.insertMany) { for (var i = 0; i < op.insertMany.length; i++) { if (forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); addToOperationsList(this, common.INSERT, op.insertMany[i]); } return; } // No valid type of operation throw toError( 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' ); }; /** * Add a single insert document to the bulk operation * * @param {object} doc the document to insert * @throws {MongoError} * @return {OrderedBulkOperation} */ OrderedBulkOperation.prototype.insert = function(document) { if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); return addToOperationsList(this, common.INSERT, document); }; /** * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne * * @method * @param {object} selector The selector for the bulk operation. * @throws {MongoError} * @return {FindOperatorsOrdered} */ OrderedBulkOperation.prototype.find = function(selector) { if (!selector) { throw toError('Bulk find operation must specify a selector'); } // Save a current selector this.s.currentOp = { selector: selector }; return new FindOperatorsOrdered(this); }; Object.defineProperty(OrderedBulkOperation.prototype, 'length', { enumerable: true, get: function() { return this.s.currentIndex; } }); // // Execute next write command in a chain var executeCommands = function(self, options, callback) { if (self.s.batches.length === 0) { return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); } // Ordered execution of the command var batch = self.s.batches.shift(); var resultHandler = function(err, result) { // Error is a driver related error not a bulk op error, terminate if ((err && err.driver) || (err && err.message)) { return handleCallback(callback, err); } // If we have and error if (err) err.ok = 0; // Merge the results together var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); const writeResult = new BulkWriteResult(self.s.bulkResult); if (mergeResult != null) { return handleCallback(callback, null, writeResult); } // If we are ordered and have errors and they are // not all replication errors terminate the operation if (self.s.bulkResult.writeErrors.length > 0) { if (self.s.bulkResult.writeErrors.length === 1) { return handleCallback( callback, new BulkWriteError(toError(self.s.bulkResult.writeErrors[0]), writeResult), null ); } return handleCallback( callback, new BulkWriteError( toError({ message: 'write operation failed', code: self.s.bulkResult.writeErrors[0].code, writeErrors: self.s.bulkResult.writeErrors }), writeResult ), null ); } else if (writeResult.getWriteConcernError()) { return handleCallback( callback, new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), null ); } // Execute the next command in line executeCommands(self, options, callback); }; var finalOptions = Object.assign({ ordered: true }, options); if (self.s.writeConcern != null) { finalOptions.writeConcern = self.s.writeConcern; } // Set an operationIf if provided if (self.operationId) { resultHandler.operationId = self.operationId; } // Serialize functions if (self.s.options.serializeFunctions) { finalOptions.serializeFunctions = true; } // Ignore undefined if (self.s.options.ignoreUndefined) { finalOptions.ignoreUndefined = true; } // Is the bypassDocumentValidation options specific if (self.s.bypassDocumentValidation === true) { finalOptions.bypassDocumentValidation = true; } // Is the checkKeys option disabled if (self.s.checkKeys === false) { finalOptions.checkKeys = false; } try { if (batch.batchType === common.INSERT) { self.s.topology.insert( self.s.collection.namespace, batch.operations, finalOptions, resultHandler ); } else if (batch.batchType === common.UPDATE) { self.s.topology.update( self.s.collection.namespace, batch.operations, finalOptions, resultHandler ); } else if (batch.batchType === common.REMOVE) { self.s.topology.remove( self.s.collection.namespace, batch.operations, finalOptions, resultHandler ); } } catch (err) { // Force top level error err.ok = 0; // Merge top level error and return handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); } }; /** * The callback format for results * @callback OrderedBulkOperation~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {BulkWriteResult} result The bulk write result. */ /** * Execute the ordered bulk operation * * @method * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.fsync=false] Specify a file sync write concern. * @param {OrderedBulkOperation~resultCallback} [callback] The result callback * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ OrderedBulkOperation.prototype.execute = function(_writeConcern, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; if (this.s.executed) { var executedError = toError('batch cannot be re-executed'); return typeof callback === 'function' ? callback(executedError, null) : this.s.promiseLibrary.reject(executedError); } if (typeof _writeConcern === 'function') { callback = _writeConcern; } else if (_writeConcern && typeof _writeConcern === 'object') { this.s.writeConcern = _writeConcern; } // If we have current batch if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); // If we have no operations in the bulk raise an error if (this.s.batches.length === 0) { var emptyBatchError = toError('Invalid Operation, no operations specified'); return typeof callback === 'function' ? callback(emptyBatchError, null) : this.s.promiseLibrary.reject(emptyBatchError); } return executeOperation(this.s.topology, executeCommands, [this, options, callback]); }; define.classMethod('execute', { callback: true, promise: false }); /** * Returns an unordered batch object * @ignore */ var initializeOrderedBulkOp = function(topology, collection, options) { return new OrderedBulkOperation(topology, collection, options); }; initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; module.exports = initializeOrderedBulkOp; module.exports.Bulk = OrderedBulkOperation; },{"../metadata":392,"../utils":399,"./common":379,"mongodb-core":345}],381:[function(require,module,exports){ 'use strict'; var common = require('./common'), utils = require('../utils'), toError = require('../utils').toError, handleCallback = require('../utils').handleCallback, shallowClone = utils.shallowClone, BulkWriteResult = common.BulkWriteResult, ObjectID = require('mongodb-core').BSON.ObjectID, BSON = require('mongodb-core').BSON, Define = require('../metadata'), Batch = common.Batch, mergeBatchResults = common.mergeBatchResults, executeOperation = require('../utils').executeOperation, BulkWriteError = require('./common').BulkWriteError; var bson = new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]); /** * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) * @class * @property {number} length Get the number of operations in the bulk. * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. */ var FindOperatorsUnordered = function(self) { this.s = self.s; }; /** * Add a single update document to the bulk operation * * @method * @param {object} updateDocument update operations * @throws {MongoError} * @return {FindOperatorsUnordered} */ FindOperatorsUnordered.prototype.update = function(updateDocument) { // Perform upsert var upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; // Establish the update command var document = { q: this.s.currentOp.selector, u: updateDocument, multi: true, upsert: upsert }; // Clear out current Op this.s.currentOp = null; // Add the update document to the list return addToOperationsList(this, common.UPDATE, document); }; /** * Add a single update one document to the bulk operation * * @method * @param {object} updateDocument update operations * @throws {MongoError} * @return {FindOperatorsUnordered} */ FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { // Perform upsert var upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; // Establish the update command var document = { q: this.s.currentOp.selector, u: updateDocument, multi: false, upsert: upsert }; // Clear out current Op this.s.currentOp = null; // Add the update document to the list return addToOperationsList(this, common.UPDATE, document); }; /** * Add a replace one operation to the bulk operation * * @method * @param {object} updateDocument the new document to replace the existing one with * @throws {MongoError} * @return {FindOperatorsUnordered} */ FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { this.updateOne(updateDocument); }; /** * Upsert modifier for update bulk operation * * @method * @throws {MongoError} * @return {FindOperatorsUnordered} */ FindOperatorsUnordered.prototype.upsert = function() { this.s.currentOp.upsert = true; return this; }; /** * Add a remove one operation to the bulk operation * * @method * @throws {MongoError} * @return {FindOperatorsUnordered} */ FindOperatorsUnordered.prototype.removeOne = function() { // Establish the update command var document = { q: this.s.currentOp.selector, limit: 1 }; // Clear out current Op this.s.currentOp = null; // Add the remove document to the list return addToOperationsList(this, common.REMOVE, document); }; /** * Add a remove operation to the bulk operation * * @method * @throws {MongoError} * @return {FindOperatorsUnordered} */ FindOperatorsUnordered.prototype.remove = function() { // Establish the update command var document = { q: this.s.currentOp.selector, limit: 0 }; // Clear out current Op this.s.currentOp = null; // Add the remove document to the list return addToOperationsList(this, common.REMOVE, document); }; // // Add to the operations list // var addToOperationsList = function(_self, docType, document) { // Get the bsonSize var bsonSize = bson.calculateObjectSize(document, { checkKeys: false }); // Throw error if the doc is bigger than the max BSON size if (bsonSize >= _self.s.maxBatchSizeBytes) throw toError('document is larger than the maximum size ' + _self.s.maxBatchSizeBytes); // Holds the current batch _self.s.currentBatch = null; // Get the right type of batch if (docType === common.INSERT) { _self.s.currentBatch = _self.s.currentInsertBatch; } else if (docType === common.UPDATE) { _self.s.currentBatch = _self.s.currentUpdateBatch; } else if (docType === common.REMOVE) { _self.s.currentBatch = _self.s.currentRemoveBatch; } // Create a new batch object if we don't have a current one if (_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); // Check if we need to create a new batch if ( _self.s.currentBatch.size + 1 >= _self.s.maxWriteBatchSize || _self.s.currentBatch.sizeBytes + bsonSize >= _self.s.maxBatchSizeBytes || _self.s.currentBatch.batchType !== docType ) { // Save the batch to the execution stack _self.s.batches.push(_self.s.currentBatch); // Create a new batch _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); } // We have an array of documents if (Array.isArray(document)) { throw toError('operation passed in cannot be an Array'); } else { _self.s.currentBatch.operations.push(document); _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); _self.s.currentIndex = _self.s.currentIndex + 1; } // Save back the current Batch to the right type if (docType === common.INSERT) { _self.s.currentInsertBatch = _self.s.currentBatch; _self.s.bulkResult.insertedIds.push({ index: _self.s.bulkResult.insertedIds.length, _id: document._id }); } else if (docType === common.UPDATE) { _self.s.currentUpdateBatch = _self.s.currentBatch; } else if (docType === common.REMOVE) { _self.s.currentRemoveBatch = _self.s.currentBatch; } // Update current batch size _self.s.currentBatch.size = _self.s.currentBatch.size + 1; _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; // Return self return _self; }; /** * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) * @class * @property {number} length Get the number of operations in the bulk. * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. */ var UnorderedBulkOperation = function(topology, collection, options) { options = options == null ? {} : options; // Get the namesspace for the write operations var namespace = collection.collectionName; // Used to mark operation as executed var executed = false; // Current item // var currentBatch = null; var currentOp = null; // Handle to the bson serializer, used to calculate running sizes var bson = topology.bson; // Set max byte size var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize ? topology.isMasterDoc.maxBsonObjectSize : 1024 * 1025 * 16; var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize ? topology.isMasterDoc.maxWriteBatchSize : 1000; // Get the write concern var writeConcern = common.writeConcern(shallowClone(options), collection, options); // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Final results var bulkResult = { ok: 1, writeErrors: [], writeConcernErrors: [], insertedIds: [], nInserted: 0, nUpserted: 0, nMatched: 0, nModified: 0, nRemoved: 0, upserted: [] }; // Internal state this.s = { // Final result bulkResult: bulkResult, // Current batch state currentInsertBatch: null, currentUpdateBatch: null, currentRemoveBatch: null, currentBatch: null, currentIndex: 0, batches: [], // Write concern writeConcern: writeConcern, // Max batch size options maxBatchSizeBytes: maxBatchSizeBytes, maxWriteBatchSize: maxWriteBatchSize, // Namespace namespace: namespace, // BSON bson: bson, // Topology topology: topology, // Options options: options, // Current operation currentOp: currentOp, // Executed executed: executed, // Collection collection: collection, // Promise Library promiseLibrary: promiseLibrary, // Bypass validation bypassDocumentValidation: typeof options.bypassDocumentValidation === 'boolean' ? options.bypassDocumentValidation : false, // check keys checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true }; }; var define = (UnorderedBulkOperation.define = new Define( 'UnorderedBulkOperation', UnorderedBulkOperation, false )); /** * Add a single insert document to the bulk operation * * @param {object} document the document to insert * @throws {MongoError} * @return {UnorderedBulkOperation} */ UnorderedBulkOperation.prototype.insert = function(document) { if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); return addToOperationsList(this, common.INSERT, document); }; /** * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne * * @method * @param {object} selector The selector for the bulk operation. * @throws {MongoError} * @return {FindOperatorsUnordered} */ UnorderedBulkOperation.prototype.find = function(selector) { if (!selector) { throw toError('Bulk find operation must specify a selector'); } // Save a current selector this.s.currentOp = { selector: selector }; return new FindOperatorsUnordered(this); }; Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { enumerable: true, get: function() { return this.s.currentIndex; } }); UnorderedBulkOperation.prototype.raw = function(op) { var key = Object.keys(op)[0]; // Set up the force server object id var forceServerObjectId = typeof this.s.options.forceServerObjectId === 'boolean' ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; // Update operations if ( (op.updateOne && op.updateOne.q) || (op.updateMany && op.updateMany.q) || (op.replaceOne && op.replaceOne.q) ) { op[key].multi = op.updateOne || op.replaceOne ? false : true; return addToOperationsList(this, common.UPDATE, op[key]); } // Crud spec update format if (op.updateOne || op.updateMany || op.replaceOne) { var multi = op.updateOne || op.replaceOne ? false : true; var operation = { q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi }; if (op[key].upsert) operation.upsert = true; if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; return addToOperationsList(this, common.UPDATE, operation); } // Remove operations if ( op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || (op.deleteMany && op.deleteMany.q) ) { op[key].limit = op.removeOne ? 1 : 0; return addToOperationsList(this, common.REMOVE, op[key]); } // Crud spec delete operations, less efficient if (op.deleteOne || op.deleteMany) { var limit = op.deleteOne ? 1 : 0; operation = { q: op[key].filter, limit: limit }; return addToOperationsList(this, common.REMOVE, operation); } // Insert operations if (op.insertOne && op.insertOne.document == null) { if (forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); return addToOperationsList(this, common.INSERT, op.insertOne); } else if (op.insertOne && op.insertOne.document) { if (forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); return addToOperationsList(this, common.INSERT, op.insertOne.document); } if (op.insertMany) { for (var i = 0; i < op.insertMany.length; i++) { if (forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); addToOperationsList(this, common.INSERT, op.insertMany[i]); } return; } // No valid type of operation throw toError( 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' ); }; // // Execute the command var executeBatch = function(self, batch, options, callback) { var finalOptions = Object.assign({ ordered: false }, options); if (self.s.writeConcern != null) { finalOptions.writeConcern = self.s.writeConcern; } var resultHandler = function(err, result) { // Error is a driver related error not a bulk op error, terminate if ((err && err.driver) || (err && err.message)) { return handleCallback(callback, err); } // If we have and error if (err) err.ok = 0; handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); }; // Set an operationIf if provided if (self.operationId) { resultHandler.operationId = self.operationId; } // Serialize functions if (self.s.options.serializeFunctions) { finalOptions.serializeFunctions = true; } // Ignore undefined if (self.s.options.ignoreUndefined) { finalOptions.ignoreUndefined = true; } // Is the bypassDocumentValidation options specific if (self.s.bypassDocumentValidation === true) { finalOptions.bypassDocumentValidation = true; } // Is the checkKeys option disabled if (self.s.checkKeys === false) { finalOptions.checkKeys = false; } try { if (batch.batchType === common.INSERT) { self.s.topology.insert( self.s.collection.namespace, batch.operations, finalOptions, resultHandler ); } else if (batch.batchType === common.UPDATE) { self.s.topology.update( self.s.collection.namespace, batch.operations, finalOptions, resultHandler ); } else if (batch.batchType === common.REMOVE) { self.s.topology.remove( self.s.collection.namespace, batch.operations, finalOptions, resultHandler ); } } catch (err) { // Force top level error err.ok = 0; // Merge top level error and return handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); } }; // // Execute all the commands var executeBatches = function(self, options, callback) { var numberOfCommandsToExecute = self.s.batches.length; // Execute over all the batches for (var i = 0; i < self.s.batches.length; i++) { executeBatch(self, self.s.batches[i], options, function(err) { // Count down the number of commands left to execute numberOfCommandsToExecute = numberOfCommandsToExecute - 1; // Execute if (numberOfCommandsToExecute === 0) { // Driver level error if (err) return handleCallback(callback, err); const writeResult = new BulkWriteResult(self.s.bulkResult); if (self.s.bulkResult.writeErrors.length > 0) { if (self.s.bulkResult.writeErrors.length === 1) { return handleCallback( callback, new BulkWriteError(toError(self.s.bulkResult.writeErrors[0]), writeResult), null ); } return handleCallback( callback, new BulkWriteError( toError({ message: 'write operation failed', code: self.s.bulkResult.writeErrors[0].code, writeErrors: self.s.bulkResult.writeErrors }), writeResult ), null ); } else if (writeResult.getWriteConcernError()) { return handleCallback( callback, new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), null ); } return handleCallback(callback, null, writeResult); } }); } }; /** * The callback format for results * @callback UnorderedBulkOperation~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {BulkWriteResult} result The bulk write result. */ /** * Execute the ordered bulk operation * * @method * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.fsync=false] Specify a file sync write concern. * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ UnorderedBulkOperation.prototype.execute = function(_writeConcern, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; if (this.s.executed) { var executedError = toError('batch cannot be re-executed'); return typeof callback === 'function' ? callback(executedError, null) : this.s.promiseLibrary.reject(executedError); } if (typeof _writeConcern === 'function') { callback = _writeConcern; } else if (_writeConcern && typeof _writeConcern === 'object') { this.s.writeConcern = _writeConcern; } // If we have current batch if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); // If we have no operations in the bulk raise an error if (this.s.batches.length === 0) { var emptyBatchError = toError('Invalid Operation, no operations specified'); return typeof callback === 'function' ? callback(emptyBatchError, null) : this.s.promiseLibrary.reject(emptyBatchError); } return executeOperation(this.s.topology, executeBatches, [this, options, callback]); }; define.classMethod('execute', { callback: true, promise: false }); /** * Returns an unordered batch object * @ignore */ var initializeUnorderedBulkOp = function(topology, collection, options) { return new UnorderedBulkOperation(topology, collection, options); }; initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; module.exports = initializeUnorderedBulkOp; module.exports.Bulk = UnorderedBulkOperation; },{"../metadata":392,"../utils":399,"./common":379,"mongodb-core":345}],382:[function(require,module,exports){ 'use strict'; var EventEmitter = require('events'), inherits = require('util').inherits, MongoNetworkError = require('mongodb-core').MongoNetworkError; var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference']; /** * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. * @class ChangeStream * @since 3.0.0 * @param {(Db|Collection)} changeDomain The collection against which to create the change stream * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents * @param {object} [options=null] Optional settings * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query * @param {object} [options.resumeAfter=null] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. * @param {number} [options.batchSize=null] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. * @param {object} [options.collation=null] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. * @param {ReadPreference} [options.readPreference=null] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. * @fires ChangeStream#close * @fires ChangeStream#change * @fires ChangeStream#end * @fires ChangeStream#error * @return {ChangeStream} a ChangeStream instance. */ var ChangeStream = function(collection, pipeline, options) { var Collection = require('./collection'); // Ensure the provided collection is actually a collection if (!(collection instanceof Collection)) { throw new Error( 'collection provided to ChangeStream constructor is not an instance of Collection' ); } var self = this; self.pipeline = pipeline || []; self.options = options || {}; self.promiseLibrary = collection.s.promiseLibrary; // Extract namespace and serverConfig from the collection self.namespace = { collection: collection.collectionName, database: collection.s.db.databaseName }; self.serverConfig = collection.s.db.serverConfig; // Determine correct read preference self.options.readPreference = self.options.readPreference || collection.s.readPreference; // Create contained Change Stream cursor self.cursor = createChangeStreamCursor(self); // Listen for any `change` listeners being added to ChangeStream self.on('newListener', function(eventName) { if (eventName === 'change' && self.cursor && self.cursor.listenerCount('change') === 0) { self.cursor.on('data', function(change) { processNewChange(self, null, change); }); } }); // Listen for all `change` listeners being removed from ChangeStream self.on('removeListener', function(eventName) { if (eventName === 'change' && self.listenerCount('change') === 0 && self.cursor) { self.cursor.removeAllListeners('data'); } }); }; inherits(ChangeStream, EventEmitter); // Create a new change stream cursor based on self's configuration var createChangeStreamCursor = function(self) { if (self.resumeToken) { self.options.resumeAfter = self.resumeToken; } var changeStreamCursor = buildChangeStreamAggregationCommand( self.serverConfig, self.namespace, self.pipeline, self.resumeToken, self.options ); /** * Fired for each new matching change in the specified namespace. Attaching a `change` event listener to a Change Stream will switch the stream into flowing mode. Data will then be passed as soon as it is available. * * @event ChangeStream#change * @type {object} */ if (self.listenerCount('change') > 0) { changeStreamCursor.on('data', function(change) { processNewChange(self, null, change); }); } /** * Change stream close event * * @event ChangeStream#close * @type {null} */ changeStreamCursor.on('close', function() { self.emit('close'); }); /** * Change stream end event * * @event ChangeStream#end * @type {null} */ changeStreamCursor.on('end', function() { self.emit('end'); }); /** * Fired when the stream encounters an error. * * @event ChangeStream#error * @type {Error} */ changeStreamCursor.on('error', function(error) { self.emit('error', error); }); return changeStreamCursor; }; var buildChangeStreamAggregationCommand = function( serverConfig, namespace, pipeline, resumeToken, options ) { var changeStreamStageOptions = {}; if (options.fullDocument) { changeStreamStageOptions.fullDocument = options.fullDocument; } if (resumeToken || options.resumeAfter) { changeStreamStageOptions.resumeAfter = resumeToken || options.resumeAfter; } // Map cursor options var cursorOptions = {}; cursorOptionNames.forEach(function(optionName) { if (options[optionName]) { cursorOptions[optionName] = options[optionName]; } }); var changeStreamPipeline = [{ $changeStream: changeStreamStageOptions }]; changeStreamPipeline = changeStreamPipeline.concat(pipeline); var command = { aggregate: namespace.collection, pipeline: changeStreamPipeline, readConcern: { level: 'majority' }, cursor: { batchSize: options.batchSize || 1 } }; // Create and return the cursor return serverConfig.cursor( namespace.database + '.' + namespace.collection, command, cursorOptions ); }; /** * Check if there is any document still available in the Change Stream * @function ChangeStream.prototype.hasNext * @param {ChangeStream~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ ChangeStream.prototype.hasNext = function(callback) { return this.cursor.hasNext(callback); }; /** * Get the next available document from the Change Stream, returns null if no more documents are available. * @function ChangeStream.prototype.next * @param {ChangeStream~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ ChangeStream.prototype.next = function(callback) { var self = this; if (this.isClosed()) { if (callback) return callback(new Error('Change Stream is not open.'), null); return self.promiseLibrary.reject(new Error('Change Stream is not open.')); } return this.cursor .next() .then(function(change) { return processNewChange(self, null, change, callback); }) .catch(function(err) { return processNewChange(self, err, null, callback); }); }; /** * Is the cursor closed * @method ChangeStream.prototype.isClosed * @return {boolean} */ ChangeStream.prototype.isClosed = function() { if (this.cursor) { return this.cursor.isClosed(); } return true; }; /** * Close the Change Stream * @method ChangeStream.prototype.close * @param {ChangeStream~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ ChangeStream.prototype.close = function(callback) { if (!this.cursor) { if (callback) return callback(); return this.promiseLibrary.resolve(); } // Tidy up the existing cursor var cursor = this.cursor; delete this.cursor; return cursor.close(callback); }; /** * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. * @method * @param {Writable} destination The destination for writing data * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} * @return {null} */ ChangeStream.prototype.pipe = function(destination, options) { if (!this.pipeDestinations) { this.pipeDestinations = []; } this.pipeDestinations.push(destination); return this.cursor.pipe(destination, options); }; /** * This method will remove the hooks set up for a previous pipe() call. * @param {Writable} [destination] The destination for writing data * @return {null} */ ChangeStream.prototype.unpipe = function(destination) { if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); } return this.cursor.unpipe(destination); }; /** * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. * @return {null} */ ChangeStream.prototype.pause = function() { return this.cursor.pause(); }; /** * This method will cause the readable stream to resume emitting data events. * @return {null} */ ChangeStream.prototype.resume = function() { return this.cursor.resume(); }; /** * Return a modified Readable stream including a possible transform method. * @method * @param {object} [options=null] Optional settings. * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. * @return {Cursor} */ ChangeStream.prototype.stream = function(options) { this.streamOptions = options; return this.cursor.stream(options); }; // Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. var processNewChange = function(self, err, change, callback) { // Handle errors if (err) { // Handle resumable MongoNetworkErrors if (err instanceof MongoNetworkError && !self.attemptingResume) { self.attemptingResume = true; return self.cursor.close(function(closeErr) { if (closeErr) { if (callback) return callback(err, null); return self.promiseLibrary.reject(err); } // Establish a new cursor self.cursor = createChangeStreamCursor(self); // Attempt to reconfigure piping if (self.pipeDestinations) { var cursorStream = self.cursor.stream(self.streamOptions); for (var pipeDestination in self.pipeDestinations) { cursorStream.pipe(pipeDestination); } } // Attempt the next() operation again if (callback) return self.next(callback); return self.next(); }); } if (typeof callback === 'function') return callback(err, null); if (self.listenerCount('error')) return self.emit('error', err); return self.promiseLibrary.reject(err); } self.attemptingResume = false; // Cache the resume token if it is present. If it is not present return an error. if (!change || !change._id) { var noResumeTokenError = new Error( 'A change stream document has been received that lacks a resume token (_id).' ); if (typeof callback === 'function') return callback(noResumeTokenError, null); if (self.listenerCount('error')) return self.emit('error', noResumeTokenError); return self.promiseLibrary.reject(noResumeTokenError); } self.resumeToken = change._id; // Return the change if (typeof callback === 'function') return callback(err, change); if (self.listenerCount('change')) return self.emit('change', change); return self.promiseLibrary.resolve(change); }; /** * The callback format for results * @callback ChangeStream~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {(object|null)} result The result object if the command was executed successfully. */ module.exports = ChangeStream; },{"./collection":383,"events":316,"mongodb-core":345,"util":563}],383:[function(require,module,exports){ (function (Buffer){ 'use strict'; var checkCollectionName = require('./utils').checkCollectionName, ObjectID = require('mongodb-core').BSON.ObjectID, Long = require('mongodb-core').BSON.Long, Code = require('mongodb-core').BSON.Code, f = require('util').format, AggregationCursor = require('./aggregation_cursor'), MongoError = require('mongodb-core').MongoError, shallowClone = require('./utils').shallowClone, isObject = require('./utils').isObject, toError = require('./utils').toError, normalizeHintField = require('./utils').normalizeHintField, handleCallback = require('./utils').handleCallback, decorateCommand = require('./utils').decorateCommand, formattedOrderClause = require('./utils').formattedOrderClause, ReadPreference = require('mongodb-core').ReadPreference, CommandCursor = require('./command_cursor'), Define = require('./metadata'), Cursor = require('./cursor'), unordered = require('./bulk/unordered'), ordered = require('./bulk/ordered'), ChangeStream = require('./change_stream'), executeOperation = require('./utils').executeOperation; /** * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection * allowing for insert/update/remove/find and other command operation on that MongoDB collection. * * **COLLECTION Cannot directly be instantiated** * @example * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * // Create a collection we want to drop later * const col = client.db(dbName).collection('createIndexExample1'); * // Show that duplicate records got dropped * col.find({}).toArray(function(err, items) { * test.equal(null, err); * test.equal(4, items.length); * client.close(); * }); * }); */ var mergeKeys = ['readPreference', 'ignoreUndefined']; /** * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) * @class * @property {string} collectionName Get the collection name. * @property {string} namespace Get the full collection namespace. * @property {object} writeConcern The current write concern values. * @property {object} readConcern The current read concern values. * @property {object} hint Get current index hint for collection. * @return {Collection} a Collection instance. */ var Collection = function(db, topology, dbName, name, pkFactory, options) { checkCollectionName(name); // Unpack variables var internalHint = null; var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; var serializeFunctions = options == null || options.serializeFunctions == null ? db.s.options.serializeFunctions : options.serializeFunctions; var raw = options == null || options.raw == null ? db.s.options.raw : options.raw; var promoteLongs = options == null || options.promoteLongs == null ? db.s.options.promoteLongs : options.promoteLongs; var promoteValues = options == null || options.promoteValues == null ? db.s.options.promoteValues : options.promoteValues; var promoteBuffers = options == null || options.promoteBuffers == null ? db.s.options.promoteBuffers : options.promoteBuffers; var readPreference = null; var collectionHint = null; var namespace = f('%s.%s', dbName, name); // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Assign the right collection level readPreference if (options && options.readPreference) { readPreference = options.readPreference; } else if (db.options.readPreference) { readPreference = db.options.readPreference; } // Set custom primary key factory if provided pkFactory = pkFactory == null ? ObjectID : pkFactory; // Internal state this.s = { // Set custom primary key factory if provided pkFactory: pkFactory, // Db db: db, // Topology topology: topology, // dbName dbName: dbName, // Options options: options, // Namespace namespace: namespace, // Read preference readPreference: readPreference, // SlaveOK slaveOk: slaveOk, // Serialize functions serializeFunctions: serializeFunctions, // Raw raw: raw, // promoteLongs promoteLongs: promoteLongs, // promoteValues promoteValues: promoteValues, // promoteBuffers promoteBuffers: promoteBuffers, // internalHint internalHint: internalHint, // collectionHint collectionHint: collectionHint, // Name name: name, // Promise library promiseLibrary: promiseLibrary, // Read Concern readConcern: options.readConcern }; }; var define = (Collection.define = new Define('Collection', Collection, false)); Object.defineProperty(Collection.prototype, 'dbName', { enumerable: true, get: function() { return this.s.dbName; } }); Object.defineProperty(Collection.prototype, 'collectionName', { enumerable: true, get: function() { return this.s.name; } }); Object.defineProperty(Collection.prototype, 'namespace', { enumerable: true, get: function() { return this.s.namespace; } }); Object.defineProperty(Collection.prototype, 'readConcern', { enumerable: true, get: function() { return this.s.readConcern || { level: 'local' }; } }); Object.defineProperty(Collection.prototype, 'writeConcern', { enumerable: true, get: function() { var ops = {}; if (this.s.options.w != null) ops.w = this.s.options.w; if (this.s.options.j != null) ops.j = this.s.options.j; if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync; if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; return ops; } }); /** * @ignore */ Object.defineProperty(Collection.prototype, 'hint', { enumerable: true, get: function() { return this.s.collectionHint; }, set: function(v) { this.s.collectionHint = normalizeHintField(v); } }); /** * Creates a cursor for a query that can be used to iterate over results from MongoDB * @method * @param {object} [query={}] The cursor query object. * @param {object} [options=null] Optional settings. * @param {number} [options.limit=0] Sets the limit of documents returned in the query. * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. * @param {object} [options.projection=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} * @param {object} [options.fields=null] **Deprecated** Use `options.projection` instead * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} * @param {boolean} [options.explain=false] Explain the query instead of returning the data. * @param {boolean} [options.snapshot=false] Snapshot query. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. * @param {boolean} [options.returnKey=false] Only return the index key. * @param {number} [options.maxScan=null] Limit the number of items to scan. * @param {number} [options.min=null] Set index bounds. * @param {number} [options.max=null] Set index bounds. * @param {boolean} [options.showDiskLoc=false] Show disk location of results. * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {ClientSession} [options.session] optional session to use for this operation * @throws {MongoError} * @return {Cursor} */ Collection.prototype.find = function(query, options, callback) { let selector = query; // figuring out arguments if (typeof callback !== 'function') { if (typeof options === 'function') { callback = options; options = undefined; } else if (options == null) { callback = typeof selector === 'function' ? selector : undefined; selector = typeof selector === 'object' ? selector : undefined; } } // Ensure selector is not null selector = selector == null ? {} : selector; // Validate correctness off the selector var object = selector; if (Buffer.isBuffer(object)) { var object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); if (object_size !== object.length) { var error = new Error( 'query selector raw message size does not match message header size [' + object.length + '] != [' + object_size + ']' ); error.name = 'MongoError'; throw error; } } // Check special case where we are using an objectId if (selector != null && selector._bsontype === 'ObjectID') { selector = { _id: selector }; } if (!options) options = {}; let projection = options.projection || options.fields; if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { projection = projection.length ? projection.reduce((result, field) => { result[field] = 1; return result; }, {}) : { _id: 1 }; } var newOptions = {}; // Make a shallow copy of the collection options for (var key in this.s.options) { if (mergeKeys.indexOf(key) !== -1) { newOptions[key] = this.s.options[key]; } } // Make a shallow copy of options for (var optKey in options) { newOptions[optKey] = options[optKey]; } // Unpack options newOptions.skip = options.skip ? options.skip : 0; newOptions.limit = options.limit ? options.limit : 0; newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; // // If we have overridden slaveOk otherwise use the default db setting newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; // Add read preference if needed newOptions = getReadPreference(this, newOptions, this.s.db); // Set slave ok to true if read preference different from primary if ( newOptions.readPreference != null && (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') ) { newOptions.slaveOk = true; } // Ensure the query is an object if (selector != null && typeof selector !== 'object') { throw MongoError.create({ message: 'query selector must be an object', driver: true }); } // Build the find command var findCommand = { find: this.s.namespace, limit: newOptions.limit, skip: newOptions.skip, query: selector }; // Ensure we use the right await data option if (typeof newOptions.awaitdata === 'boolean') { newOptions.awaitData = newOptions.awaitdata; } // Translate to new command option noCursorTimeout if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; // Merge in options to command for (var name in newOptions) { if (newOptions[name] != null && name !== 'session') { findCommand[name] = newOptions[name]; } } if (projection) findCommand.fields = projection; // Add db object to the new options newOptions.db = this.s.db; // Add the promise library newOptions.promiseLibrary = this.s.promiseLibrary; // Set raw if available at collection level if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; // Set promoteLongs if available at collection level if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') newOptions.promoteLongs = this.s.promoteLongs; if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') newOptions.promoteValues = this.s.promoteValues; if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') newOptions.promoteBuffers = this.s.promoteBuffers; // Sort options if (findCommand.sort) { findCommand.sort = formattedOrderClause(findCommand.sort); } // Set the readConcern decorateWithReadConcern(findCommand, this, options); // Decorate find command with collation options decorateWithCollation(findCommand, this, options); // Create the cursor if (typeof callback === 'function') return handleCallback( callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions) ); return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); }; define.classMethod('find', { callback: false, promise: false, returns: [Cursor] }); /** * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {object} doc Document to insert. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.insertOne = function(doc, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, insertOne, [this, doc, options, callback]); }; var insertOne = function(self, doc, options, callback) { if (Array.isArray(doc)) { return callback( MongoError.create({ message: 'doc parameter must be an object', driver: true }) ); } insertDocuments(self, [doc], options, function(err, r) { if (callback == null) return; if (err && callback) return callback(err); // Workaround for pre 2.6 servers if (r == null) return callback(null, { result: { ok: 1 } }); // Add values to top level to ensure crud spec compatibility r.insertedCount = r.result.n; r.insertedId = doc._id; if (callback) callback(null, r); }); }; var mapInserManyResults = function(docs, r) { var finalResult = { result: { ok: 1, n: r.insertedCount }, ops: docs, insertedCount: r.insertedCount, insertedIds: r.insertedIds }; if (r.getLastOp()) { finalResult.result.opTime = r.getLastOp(); } return finalResult; }; define.classMethod('insertOne', { callback: true, promise: true }); /** * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {object[]} docs Documents to insert. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~insertWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.insertMany = function(docs, options, callback) { var self = this; if (typeof options === 'function') (callback = options), (options = {}); options = options ? shallowClone(options) : { ordered: true }; if (!Array.isArray(docs) && typeof callback === 'function') { return callback( MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) ); } else if (!Array.isArray(docs)) { return new this.s.promiseLibrary(function(resolve, reject) { reject( MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) ); }); } // If keep going set unordered options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; // Set up the force server object id var forceServerObjectId = typeof options.forceServerObjectId === 'boolean' ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; // Do we want to force the server to assign the _id key if (forceServerObjectId !== true) { // Add _id if not specified for (var i = 0; i < docs.length; i++) { if (docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); } } // Generate the bulk write operations var operations = [ { insertMany: docs } ]; return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback], { resultMutator: result => mapInserManyResults(docs, result) }); }; define.classMethod('insertMany', { callback: true, promise: true }); /** * @typedef {Object} Collection~BulkWriteOpResult * @property {number} insertedCount Number of documents inserted. * @property {number} matchedCount Number of documents matched for update. * @property {number} modifiedCount Number of documents modified. * @property {number} deletedCount Number of documents deleted. * @property {number} upsertedCount Number of documents upserted. * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation * @property {object} result The command result object. */ /** * The callback format for inserts * @callback Collection~bulkWriteOpCallback * @param {BulkWriteError} error An error instance representing the error during the execution. * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. */ /** * Perform a bulkWrite operation without a fluent API * * Legal operation types are * * { insertOne: { document: { a: 1 } } } * * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } * * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } * * { deleteOne: { filter: {c:1} } } * * { deleteMany: { filter: {c:1} } } * * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} * * If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {object[]} operations Bulk operations to perform. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~bulkWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.bulkWrite = function(operations, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || { ordered: true }; if (!Array.isArray(operations)) { throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); } return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback]); }; var bulkWrite = function(self, operations, options, callback) { // Add ignoreUndfined if (self.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = self.s.options.ignoreUndefined; } // Create the bulk operation var bulk = options.ordered === true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); // Do we have a collation var collation = false; // for each op go through and add to the bulk try { for (var i = 0; i < operations.length; i++) { // Get the operation type var key = Object.keys(operations[i])[0]; // Check if we have a collation if (operations[i][key].collation) { collation = true; } // Pass to the raw bulk bulk.raw(operations[i]); } } catch (err) { return callback(err, null); } // Final options for write concern var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; var capabilities = self.s.topology.capabilities(); // Did the user pass in a collation, check if our write server supports it if (collation && capabilities && !capabilities.commandsTakeCollation) { return callback(new MongoError(f('server/primary/mongos does not support collation'))); } // Execute the bulk bulk.execute(writeCon, finalOptions, function(err, r) { // We have connection level error if (!r && err) { return callback(err, null); } r.insertedCount = r.nInserted; r.matchedCount = r.nMatched; r.modifiedCount = r.nModified || 0; r.deletedCount = r.nRemoved; r.upsertedCount = r.getUpsertedIds().length; r.upsertedIds = {}; r.insertedIds = {}; // Update the n r.n = r.insertedCount; // Inserted documents var inserted = r.getInsertedIds(); // Map inserted ids for (var i = 0; i < inserted.length; i++) { r.insertedIds[inserted[i].index] = inserted[i]._id; } // Upserted documents var upserted = r.getUpsertedIds(); // Map upserted ids for (i = 0; i < upserted.length; i++) { r.upsertedIds[upserted[i].index] = upserted[i]._id; } // Return the results callback(null, r); }); }; var insertDocuments = function(self, docs, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Ensure we are operating on an array op docs docs = Array.isArray(docs) ? docs : [docs]; // Get the write concern options var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); // If keep going set unordered if (finalOptions.keepGoing === true) finalOptions.ordered = false; finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; // Set up the force server object id var forceServerObjectId = typeof options.forceServerObjectId === 'boolean' ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; // Add _id if not specified if (forceServerObjectId !== true) { for (var i = 0; i < docs.length; i++) { if (docs[i]._id === void 0) docs[i]._id = self.s.pkFactory.createPk(); } } // File inserts self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { if (callback == null) return; if (err) return handleCallback(callback, err); if (result == null) return handleCallback(callback, null, null); if (result.result.code) return handleCallback(callback, toError(result.result)); if (result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); // Add docs to the list result.ops = docs; // Return the results handleCallback(callback, null, result); }); }; define.classMethod('bulkWrite', { callback: true, promise: true }); /** * @typedef {Object} Collection~WriteOpResult * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany * @property {object} connection The connection object used for the operation. * @property {object} result The command result object. */ /** * The callback format for inserts * @callback Collection~writeOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. */ /** * @typedef {Object} Collection~insertWriteOpResult * @property {Number} insertedCount The total amount of documents inserted. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. * @property {object} connection The connection object used for the operation. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). * @property {Number} result.ok Is 1 if the command executed correctly. * @property {Number} result.n The total count of documents inserted. */ /** * @typedef {Object} Collection~insertOneWriteOpResult * @property {Number} insertedCount The total amount of documents inserted. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. * @property {object} connection The connection object used for the operation. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). * @property {Number} result.ok Is 1 if the command executed correctly. * @property {Number} result.n The total count of documents inserted. */ /** * The callback format for inserts * @callback Collection~insertWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. */ /** * The callback format for inserts * @callback Collection~insertOneWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. */ /** * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {(object|object[])} docs Documents to insert. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~insertWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated Use insertOne, insertMany or bulkWrite */ Collection.prototype.insert = function(docs, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || { ordered: false }; docs = !Array.isArray(docs) ? [docs] : docs; if (options.keepGoing === true) { options.ordered = false; } return this.insertMany(docs, options, callback); }; define.classMethod('insert', { callback: true, promise: true }); /** * @typedef {Object} Collection~updateWriteOpResult * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. * @property {Number} result.ok Is 1 if the command executed correctly. * @property {Number} result.n The total count of documents scanned. * @property {Number} result.nModified The total count of documents modified. * @property {Object} connection The connection object used for the operation. * @property {Number} matchedCount The number of documents that matched the filter. * @property {Number} modifiedCount The number of documents that were modified. * @property {Number} upsertedCount The number of documents upserted. * @property {Object} upsertedId The upserted id. * @property {ObjectId} upsertedId._id The upserted _id returned from the server. */ /** * The callback format for inserts * @callback Collection~updateWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. */ /** * Update a single document on MongoDB * @method * @param {object} filter The Filter used to select the document to update * @param {object} update The update operations to be applied to the document * @param {object} [options=null] Optional settings. * @param {boolean} [options.upsert=false] Update operation is an upsert. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~updateWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.updateOne = function(filter, update, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; var err = checkForAtomicOperators(update); if (err) { if (typeof callback === 'function') return callback(err); return this.s.promiseLibrary.reject(err); } options = shallowClone(options); // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, updateOne, [this, filter, update, options, callback]); }; var checkForAtomicOperators = function(update) { var keys = Object.keys(update); // same errors as the server would give for update doc lacking atomic operators if (keys.length === 0) { return toError('The update operation document must contain at least one atomic operator.'); } if (keys[0][0] !== '$') { return toError('the update operation document must contain atomic operators.'); } }; var updateOne = function(self, filter, update, options, callback) { // Set single document update options.multi = false; // Execute update updateDocuments(self, filter, update, options, function(err, r) { if (callback == null) return; if (err && callback) return callback(err); if (r == null) return callback(null, { result: { ok: 1 } }); r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; if (callback) callback(null, r); }); }; define.classMethod('updateOne', { callback: true, promise: true }); /** * Replace a document on MongoDB * @method * @param {object} filter The Filter used to select the document to update * @param {object} doc The Document that replaces the matching document * @param {object} [options=null] Optional settings. * @param {boolean} [options.upsert=false] Update operation is an upsert. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~updateWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.replaceOne = function(filter, doc, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = shallowClone(options); // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, replaceOne, [this, filter, doc, options, callback]); }; var replaceOne = function(self, filter, doc, options, callback) { // Set single document update options.multi = false; // Execute update updateDocuments(self, filter, doc, options, function(err, r) { if (callback == null) return; if (err && callback) return callback(err); if (r == null) return callback(null, { result: { ok: 1 } }); r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; r.ops = [doc]; if (callback) callback(null, r); }); }; define.classMethod('replaceOne', { callback: true, promise: true }); /** * Update multiple documents on MongoDB * @method * @param {object} filter The Filter used to select the document to update * @param {object} update The update operations to be applied to the document * @param {object} [options=null] Optional settings. * @param {boolean} [options.upsert=false] Update operation is an upsert. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~updateWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.updateMany = function(filter, update, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; var err = checkForAtomicOperators(update); if (err) { if (typeof callback === 'function') return callback(err); return this.s.promiseLibrary.reject(err); } options = shallowClone(options); // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, updateMany, [this, filter, update, options, callback]); }; var updateMany = function(self, filter, update, options, callback) { // Set single document update options.multi = true; // Execute update updateDocuments(self, filter, update, options, function(err, r) { if (callback == null) return; if (err && callback) return callback(err); if (r == null) return callback(null, { result: { ok: 1 } }); r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; if (callback) callback(null, r); }); }; define.classMethod('updateMany', { callback: true, promise: true }); var updateDocuments = function(self, selector, document, options, callback) { if ('function' === typeof options) (callback = options), (options = null); if (options == null) options = {}; if (!('function' === typeof callback)) callback = null; // If we are not providing a selector or document throw if (selector == null || typeof selector !== 'object') return callback(toError('selector must be a valid JavaScript object')); if (document == null || typeof document !== 'object') return callback(toError('document must be a valid JavaScript object')); // Get the write concern options var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); // Do we return the actual result document // Either use override on the function, or go back to default on either the collection // level or db finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; // Execute the operation var op = { q: selector, u: document }; op.upsert = options.upsert !== void 0 ? !!options.upsert : false; op.multi = options.multi !== void 0 ? !!options.multi : false; if (finalOptions.arrayFilters) { op.arrayFilters = finalOptions.arrayFilters; delete finalOptions.arrayFilters; } // Have we specified collation decorateWithCollation(finalOptions, self, options); // Update options self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { if (callback == null) return; if (err) return handleCallback(callback, err, null); if (result == null) return handleCallback(callback, null, null); if (result.result.code) return handleCallback(callback, toError(result.result)); if (result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); // Return the results handleCallback(callback, null, result); }); }; /** * Updates documents. * @method * @param {object} selector The selector for the update operation. * @param {object} document The update document. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.upsert=false] Update operation is an upsert. * @param {boolean} [options.multi=false] Update one/all documents with operation. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~writeOpCallback} [callback] The command result callback * @throws {MongoError} * @return {Promise} returns Promise if no callback passed * @deprecated use updateOne, updateMany or bulkWrite */ Collection.prototype.update = function(selector, document, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, updateDocuments, [ this, selector, document, options, callback ]); }; define.classMethod('update', { callback: true, promise: true }); /** * @typedef {Object} Collection~deleteWriteOpResult * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. * @property {Number} result.ok Is 1 if the command executed correctly. * @property {Number} result.n The total count of documents deleted. * @property {Object} connection The connection object used for the operation. * @property {Number} deletedCount The number of documents deleted. */ /** * The callback format for inserts * @callback Collection~deleteWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. */ /** * Delete a document on MongoDB * @method * @param {object} filter The Filter used to select the document to remove * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~deleteWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.deleteOne = function(filter, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = shallowClone(options); // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, deleteOne, [this, filter, options, callback]); }; var deleteOne = function(self, filter, options, callback) { options.single = true; removeDocuments(self, filter, options, function(err, r) { if (callback == null) return; if (err && callback) return callback(err); if (r == null) return callback(null, { result: { ok: 1 } }); r.deletedCount = r.result.n; if (callback) callback(null, r); }); }; define.classMethod('deleteOne', { callback: true, promise: true }); Collection.prototype.removeOne = Collection.prototype.deleteOne; define.classMethod('removeOne', { callback: true, promise: true }); /** * Delete multiple documents on MongoDB * @method * @param {object} filter The Filter used to select the documents to remove * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~deleteWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.deleteMany = function(filter, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = shallowClone(options); // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, deleteMany, [this, filter, options, callback]); }; var deleteMany = function(self, filter, options, callback) { options.single = false; removeDocuments(self, filter, options, function(err, r) { if (callback == null) return; if (err && callback) return callback(err); if (r == null) return callback(null, { result: { ok: 1 } }); r.deletedCount = r.result.n; if (callback) callback(null, r); }); }; var removeDocuments = function(self, selector, options, callback) { if (typeof options === 'function') { (callback = options), (options = {}); } else if (typeof selector === 'function') { callback = selector; options = {}; selector = {}; } // Create an empty options object if the provided one is null options = options || {}; // Get the write concern options var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); // If selector is null set empty if (selector == null) selector = {}; // Build the op var op = { q: selector, limit: 0 }; if (options.single) op.limit = 1; // Have we specified collation decorateWithCollation(finalOptions, self, options); // Execute the remove self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { if (callback == null) return; if (err) return handleCallback(callback, err, null); if (result == null) return handleCallback(callback, null, null); if (result.result.code) return handleCallback(callback, toError(result.result)); if (result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); // Return the results handleCallback(callback, null, result); }); }; define.classMethod('deleteMany', { callback: true, promise: true }); Collection.prototype.removeMany = Collection.prototype.deleteMany; define.classMethod('removeMany', { callback: true, promise: true }); /** * Remove documents. * @method * @param {object} selector The selector for the update operation. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.single=false] Removes the first document found. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~writeOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated use deleteOne, deleteMany or bulkWrite */ Collection.prototype.remove = function(selector, options, callback) { // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, removeDocuments, [this, selector, options, callback]); }; define.classMethod('remove', { callback: true, promise: true }); /** * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic * operators and update instead for more efficient operations. * @method * @param {object} doc Document to save * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~writeOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated use insertOne, insertMany, updateOne or updateMany */ Collection.prototype.save = function(doc, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add ignoreUndfined if (this.s.options.ignoreUndefined) { options = shallowClone(options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation(this.s.topology, save, [this, doc, options, callback]); }; var save = function(self, doc, options, callback) { // Get the write concern options var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); // Establish if we need to perform an insert or update if (doc._id != null) { finalOptions.upsert = true; return updateDocuments(self, { _id: doc._id }, doc, finalOptions, callback); } // Insert the document insertDocuments(self, [doc], finalOptions, function(err, r) { if (callback == null) return; if (doc == null) return handleCallback(callback, null, null); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, r); }); }; define.classMethod('save', { callback: true, promise: true }); /** * The callback format for results * @callback Collection~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object} result The result object if the command was executed successfully. */ /** * The callback format for an aggregation call * @callback Collection~aggregationCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. */ /** * Fetches the first document that matches the query * @method * @param {object} query Query for find Operation * @param {object} [options=null] Optional settings. * @param {number} [options.limit=0] Sets the limit of documents returned in the query. * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. * @param {object} [options.projection=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} * @param {object} [options.fields=null] **Deprecated** Use `options.projection` instead * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} * @param {boolean} [options.explain=false] Explain the query instead of returning the data. * @param {boolean} [options.snapshot=false] Snapshot query. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. * @param {boolean} [options.returnKey=false] Only return the index key. * @param {number} [options.maxScan=null] Limit the number of items to scan. * @param {number} [options.min=null] Set index bounds. * @param {number} [options.max=null] Set index bounds. * @param {boolean} [options.showDiskLoc=false] Show disk location of results. * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.findOne = function(query, options, callback) { if (typeof query === 'function') (callback = query), (query = {}), (options = {}); if (typeof options === 'function') (callback = options), (options = {}); query = query || {}; options = options || {}; return executeOperation(this.s.topology, findOne, [this, query, options, callback]); }; var findOne = function(self, query, options, callback) { const cursor = self .find(query, options) .limit(-1) .batchSize(1); // Return the item cursor.next(function(err, item) { if (err != null) return handleCallback(callback, toError(err), null); handleCallback(callback, null, item); }); }; define.classMethod('findOne', { callback: true, promise: true }); /** * The callback format for the collection method, must be used if strict is specified * @callback Collection~collectionResultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection} collection The collection instance. */ /** * Rename the collection. * * @method * @param {string} newName New name of of the collection. * @param {object} [options=null] Optional settings. * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~collectionResultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.rename = function(newName, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); return executeOperation(this.s.topology, rename, [this, newName, options, callback]); }; var rename = function(self, newName, options, callback) { // Check the collection name checkCollectionName(newName); // Build the command var renameCollection = f('%s.%s', self.s.dbName, self.s.name); var toCollection = f('%s.%s', self.s.dbName, newName); var dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; var cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; // Decorate command with writeConcern if supported decorateWithWriteConcern(cmd, self, options); // Execute against admin self.s.db.admin().command(cmd, options, function(err, doc) { if (err) return handleCallback(callback, err, null); // We have an error if (doc.errmsg) return handleCallback(callback, toError(doc), null); try { return handleCallback( callback, null, new Collection( self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options ) ); } catch (err) { return handleCallback(callback, toError(err), null); } }); }; define.classMethod('rename', { callback: true, promise: true }); /** * Drop the collection from the database, removing it permanently. New accesses will create a new collection. * * @method * @param {object} [options=null] Optional settings. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.drop = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, this.s.db.dropCollection.bind(this.s.db), [ this.s.name, options, callback ]); }; define.classMethod('drop', { callback: true, promise: true }); /** * Returns the options of the collection. * * @method * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.options = function(opts, callback) { if (typeof opts === 'function') (callback = opts), (opts = {}); opts = opts || {}; return executeOperation(this.s.topology, options, [this, opts, callback]); }; var options = function(self, opts, callback) { self.s.db.listCollections({ name: self.s.name }, opts).toArray(function(err, collections) { if (err) return handleCallback(callback, err); if (collections.length === 0) { return handleCallback( callback, MongoError.create({ message: f('collection %s not found', self.s.namespace), driver: true }) ); } handleCallback(callback, err, collections[0].options || null); }); }; define.classMethod('options', { callback: true, promise: true }); /** * Returns if the collection is a capped collection * * @method * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.isCapped = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, isCapped, [this, options, callback]); }; var isCapped = function(self, options, callback) { self.options(options, function(err, document) { if (err) return handleCallback(callback, err); handleCallback(callback, null, document && document.capped); }); }; define.classMethod('isCapped', { callback: true, promise: true }); /** * Creates an index on the db and collection collection. * @method * @param {(string|object)} fieldOrSpec Defines the index. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.unique=false] Creates an unique index. * @param {boolean} [options.sparse=false] Creates a sparse index. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. * @param {number} [options.v=null] Specify the format version of the indexes. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) * @param {string} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, createIndex, [this, fieldOrSpec, options, callback]); }; var createIndex = function(self, fieldOrSpec, options, callback) { self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); }; define.classMethod('createIndex', { callback: true, promise: true }); /** * Creates multiple indexes in the collection, this method is only supported for * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. * @method * @param {array} indexSpecs An array of index specifications to be created * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.createIndexes = function(indexSpecs, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options ? shallowClone(options) : {}; if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; return executeOperation(this.s.topology, createIndexes, [this, indexSpecs, options, callback]); }; var createIndexes = function(self, indexSpecs, options, callback) { var capabilities = self.s.topology.capabilities(); // Ensure we generate the correct name if the parameter is not set for (var i = 0; i < indexSpecs.length; i++) { if (indexSpecs[i].name == null) { var keys = []; // Did the user pass in a collation, check if our write server supports it if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { return callback(new MongoError(f('server/primary/mongos does not support collation'))); } for (var name in indexSpecs[i].key) { keys.push(f('%s_%s', name, indexSpecs[i].key[name])); } // Set the name indexSpecs[i].name = keys.join('_'); } } options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); // Execute the index self.s.db.command( { createIndexes: self.s.name, indexes: indexSpecs }, options, callback ); }; define.classMethod('createIndexes', { callback: true, promise: true }); /** * Drops an index from this collection. * @method * @param {string} indexName Name of the index to drop. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.dropIndex = function(indexName, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() || {} : {}; // Run only against primary options.readPreference = ReadPreference.PRIMARY; return executeOperation(this.s.topology, dropIndex, [this, indexName, options, callback]); }; var dropIndex = function(self, indexName, options, callback) { // Delete index command var cmd = { dropIndexes: self.s.name, index: indexName }; // Decorate command with writeConcern if supported decorateWithWriteConcern(cmd, self, options); // Execute command self.s.db.command(cmd, options, function(err, result) { if (typeof callback !== 'function') return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result); }); }; define.classMethod('dropIndex', { callback: true, promise: true }); /** * Drops all indexes from this collection. * @method * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.dropIndexes = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options ? shallowClone(options) : {}; if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; return executeOperation(this.s.topology, dropIndexes, [this, options, callback]); }; var dropIndexes = function(self, options, callback) { self.dropIndex('*', options, function(err) { if (err) return handleCallback(callback, err, false); handleCallback(callback, null, true); }); }; define.classMethod('dropIndexes', { callback: true, promise: true }); /** * Drops all indexes from this collection. * @method * @deprecated use dropIndexes * @param {Collection~resultCallback} callback The command result callback * @return {Promise} returns Promise if no [callback] passed */ Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; define.classMethod('dropAllIndexes', { callback: true, promise: true }); /** * Reindex all indexes on the collection * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. * @method * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.reIndex = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, reIndex, [this, options, callback]); }; var reIndex = function(self, options, callback) { // Reindex var cmd = { reIndex: self.s.name }; // Execute the command self.s.db.command(cmd, options, function(err, result) { if (callback == null) return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }; define.classMethod('reIndex', { callback: true, promise: true }); /** * Get the list of all indexes information for the collection. * * @method * @param {object} [options=null] Optional settings. * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {ClientSession} [options.session] optional session to use for this operation * @return {CommandCursor} */ Collection.prototype.listIndexes = function(options) { options = options || {}; // Clone the options options = shallowClone(options); // Determine the read preference in the options. options = getReadPreference(this, options, this.s.db, this); // Set the CommandCursor constructor options.cursorFactory = CommandCursor; // Set the promiseLibrary options.promiseLibrary = this.s.promiseLibrary; if (!this.s.topology.capabilities()) { throw new MongoError('cannot connect to server'); } // We have a list collections command if (this.s.topology.capabilities().hasListIndexesCommand) { // Cursor options var cursor = options.batchSize ? { batchSize: options.batchSize } : {}; // Build the command var command = { listIndexes: this.s.name, cursor: cursor }; // Execute the cursor cursor = this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); // Do we have a readPreference, apply it if (options.readPreference) cursor.setReadPreference(options.readPreference); // Return the cursor return cursor; } // Get the namespace var ns = f('%s.system.indexes', this.s.dbName); // Get the query cursor = this.s.topology.cursor(ns, { find: ns, query: { ns: this.s.namespace } }, options); // Do we have a readPreference, apply it if (options.readPreference) cursor.setReadPreference(options.readPreference); // Set the passed in batch size if one was provided if (options.batchSize) cursor = cursor.batchSize(options.batchSize); // Return the cursor return cursor; }; define.classMethod('listIndexes', { callback: false, promise: false, returns: [CommandCursor] }); /** * Ensures that an index exists, if it does not it creates it * @method * @deprecated use createIndexes instead * @param {(string|object)} fieldOrSpec Defines the index. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.unique=false] Creates an unique index. * @param {boolean} [options.sparse=false] Creates a sparse index. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. * @param {number} [options.v=null] Specify the format version of the indexes. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, ensureIndex, [this, fieldOrSpec, options, callback]); }; var ensureIndex = function(self, fieldOrSpec, options, callback) { self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); }; define.classMethod('ensureIndex', { callback: true, promise: true }); /** * Checks if one or more indexes exist on the collection, fails on first non-existing index * @method * @param {(string|array)} indexes One or more index names to check. * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.indexExists = function(indexes, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, indexExists, [this, indexes, options, callback]); }; var indexExists = function(self, indexes, options, callback) { self.indexInformation(options, function(err, indexInformation) { // If we have an error return if (err != null) return handleCallback(callback, err, null); // Let's check for the index names if (!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); // Check in list of indexes for (var i = 0; i < indexes.length; i++) { if (indexInformation[indexes[i]] == null) { return handleCallback(callback, null, false); } } // All keys found return true return handleCallback(callback, null, true); }); }; define.classMethod('indexExists', { callback: true, promise: true }); /** * Retrieves this collections index info. * @method * @param {object} [options=null] Optional settings. * @param {boolean} [options.full=false] Returns the full raw index information. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.indexInformation = function(options, callback) { var args = Array.prototype.slice.call(arguments, 0); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, indexInformation, [this, options, callback]); }; var indexInformation = function(self, options, callback) { self.s.db.indexInformation(self.s.name, options, callback); }; define.classMethod('indexInformation', { callback: true, promise: true }); /** * The callback format for results * @callback Collection~countCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {number} result The count of documents that matched the query. */ /** * Count number of matching documents in the db to a query. * @method * @param {object} query The query for the count. * @param {object} [options=null] Optional settings. * @param {boolean} [options.limit=null] The limit of documents to count. * @param {boolean} [options.skip=null] The number of documents to skip for the count. * @param {string} [options.hint=null] An index name hint for the query. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~countCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.count = function(query, options, callback) { var args = Array.prototype.slice.call(arguments, 0); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; query = args.length ? args.shift() || {} : {}; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, count, [this, query, options, callback]); }; var count = function(self, query, options, callback) { var skip = options.skip; var limit = options.limit; var hint = options.hint; var maxTimeMS = options.maxTimeMS; // Final query var cmd = { count: self.s.name, query: query }; // Add limit, skip and maxTimeMS if defined if (typeof skip === 'number') cmd.skip = skip; if (typeof limit === 'number') cmd.limit = limit; if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; if (hint) cmd.hint = hint; options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(self, options, self.s.db); // Do we have a readConcern specified decorateWithReadConcern(cmd, self, options); // Have we specified collation decorateWithCollation(cmd, self, options); // Execute command self.s.db.command(cmd, options, function(err, result) { if (err) return handleCallback(callback, err); handleCallback(callback, null, result.n); }); }; define.classMethod('count', { callback: true, promise: true }); /** * The distinct command returns returns a list of distinct values for the given key across a collection. * @method * @param {string} key Field of the document to find distinct values for. * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.distinct = function(key, query, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; var queryOption = args.length ? args.shift() || {} : {}; var optionsOption = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, distinct, [ this, key, queryOption, optionsOption, callback ]); }; var distinct = function(self, key, query, options, callback) { // maxTimeMS option var maxTimeMS = options.maxTimeMS; // Distinct command var cmd = { distinct: self.s.name, key: key, query: query }; options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(self, options, self.s.db, self); // Add maxTimeMS if defined if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; // Do we have a readConcern specified decorateWithReadConcern(cmd, self, options); // Have we specified collation decorateWithCollation(cmd, self, options); // Execute the command self.s.db.command(cmd, options, function(err, result) { if (err) return handleCallback(callback, err); handleCallback(callback, null, result.values); }); }; define.classMethod('distinct', { callback: true, promise: true }); /** * Retrieve all the indexes on the collection. * @method * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.indexes = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, indexes, [this, options, callback]); }; var indexes = function(self, options, callback) { options = Object.assign({}, { full: true }, options); self.s.db.indexInformation(self.s.name, options, callback); }; define.classMethod('indexes', { callback: true, promise: true }); /** * Get all the collection statistics. * * @method * @param {object} [options=null] Optional settings. * @param {number} [options.scale=null] Divide the returned sizes by scale value. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The collection result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.stats = function(options, callback) { var args = Array.prototype.slice.call(arguments, 0); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, stats, [this, options, callback]); }; var stats = function(self, options, callback) { // Build command object var commandObject = { collStats: self.s.name }; // Check if we have the scale value if (options['scale'] != null) commandObject['scale'] = options['scale']; options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(self, options, self.s.db, self); // Execute the command self.s.db.command(commandObject, options, callback); }; define.classMethod('stats', { callback: true, promise: true }); /** * @typedef {Object} Collection~findAndModifyWriteOpResult * @property {object} value Document returned from findAndModify command. * @property {object} lastErrorObject The raw lastErrorObject returned from the command. * @property {Number} ok Is 1 if the command executed correctly. */ /** * The callback format for inserts * @callback Collection~findAndModifyCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. */ /** * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. * * @method * @param {object} filter Document selection filter. * @param {object} [options=null] Optional settings. * @param {object} [options.projection=null] Limits the fields to return for all matching documents. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~findAndModifyCallback} [callback] The collection result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.findOneAndDelete = function(filter, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Basic validation if (filter == null || typeof filter !== 'object') throw toError('filter parameter must be an object'); return executeOperation(this.s.topology, findOneAndDelete, [this, filter, options, callback]); }; var findOneAndDelete = function(self, filter, options, callback) { // Final options var finalOptions = shallowClone(options); finalOptions['fields'] = options.projection; finalOptions['remove'] = true; // Execute find and Modify self.findAndModify(filter, options.sort, null, finalOptions, callback); }; define.classMethod('findOneAndDelete', { callback: true, promise: true }); /** * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. * * @method * @param {object} filter Document selection filter. * @param {object} replacement Document replacing the matching document. * @param {object} [options=null] Optional settings. * @param {object} [options.projection=null] Limits the fields to return for all matching documents. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~findAndModifyCallback} [callback] The collection result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Basic validation if (filter == null || typeof filter !== 'object') throw toError('filter parameter must be an object'); if (replacement == null || typeof replacement !== 'object') throw toError('replacement parameter must be an object'); return executeOperation(this.s.topology, findOneAndReplace, [ this, filter, replacement, options, callback ]); }; var findOneAndReplace = function(self, filter, replacement, options, callback) { // Final options var finalOptions = shallowClone(options); finalOptions['fields'] = options.projection; finalOptions['update'] = true; finalOptions['new'] = options.returnOriginal !== void 0 ? !options.returnOriginal : false; finalOptions['upsert'] = options.upsert !== void 0 ? !!options.upsert : false; // Execute findAndModify self.findAndModify(filter, options.sort, replacement, finalOptions, callback); }; define.classMethod('findOneAndReplace', { callback: true, promise: true }); /** * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. * * @method * @param {object} filter Document selection filter. * @param {object} update Update operations to be performed on the document * @param {object} [options=null] Optional settings. * @param {object} [options.projection=null] Limits the fields to return for all matching documents. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~findAndModifyCallback} [callback] The collection result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Basic validation if (filter == null || typeof filter !== 'object') throw toError('filter parameter must be an object'); if (update == null || typeof update !== 'object') throw toError('update parameter must be an object'); return executeOperation(this.s.topology, findOneAndUpdate, [ this, filter, update, options, callback ]); }; var findOneAndUpdate = function(self, filter, update, options, callback) { // Final options var finalOptions = shallowClone(options); finalOptions['fields'] = options.projection; finalOptions['update'] = true; finalOptions['new'] = typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; finalOptions['upsert'] = typeof options.upsert === 'boolean' ? options.upsert : false; // Execute findAndModify self.findAndModify(filter, options.sort, update, finalOptions, callback); }; define.classMethod('findOneAndUpdate', { callback: true, promise: true }); /** * Find and update a document. * @method * @param {object} query Query object to locate the object to modify. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. * @param {object} doc The fields/vals to be updated. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.remove=false] Set to true to remove the object before returning. * @param {boolean} [options.upsert=false] Perform an upsert operation. * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. * @param {object} [options.projection=null] Object containing the field projection for the result returned from the operation. * @param {object} [options.fields=null] **Deprecated** Use `options.projection` instead * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~findAndModifyCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead */ Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; sort = args.length ? args.shift() || [] : []; doc = args.length ? args.shift() : null; options = args.length ? args.shift() || {} : {}; // Clone options options = shallowClone(options); // Force read preference primary options.readPreference = ReadPreference.PRIMARY; return executeOperation(this.s.topology, findAndModify, [ this, query, sort, doc, options, callback ]); }; var findAndModify = function(self, query, sort, doc, options, callback) { // Create findAndModify command object var queryObject = { findandmodify: self.s.name, query: query }; sort = formattedOrderClause(sort); if (sort) { queryObject.sort = sort; } queryObject.new = options.new ? true : false; queryObject.remove = options.remove ? true : false; queryObject.upsert = options.upsert ? true : false; const projection = options.projection || options.fields; if (projection) { queryObject.fields = projection; } if (options.arrayFilters) { queryObject.arrayFilters = options.arrayFilters; delete options.arrayFilters; } if (doc && !options.remove) { queryObject.update = doc; } if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; // Either use override on the function, or go back to default on either the collection // level or db if (options['serializeFunctions'] != null) { options['serializeFunctions'] = options['serializeFunctions']; } else { options['serializeFunctions'] = self.s.serializeFunctions; } // No check on the documents options.checkKeys = false; // Get the write concern settings var finalOptions = writeConcern(options, self.s.db, self, options); // Decorate the findAndModify command with the write Concern if (finalOptions.writeConcern) { queryObject.writeConcern = finalOptions.writeConcern; } // Have we specified bypassDocumentValidation if (typeof finalOptions.bypassDocumentValidation === 'boolean') { queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; } // Have we specified collation decorateWithCollation(queryObject, self, finalOptions); // Execute the command self.s.db.command(queryObject, finalOptions, function(err, result) { if (err) return handleCallback(callback, err, null); return handleCallback(callback, null, result); }); }; define.classMethod('findAndModify', { callback: true, promise: true }); /** * Find and remove a document. * @method * @param {object} query Query object to locate the object to modify. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated use findOneAndDelete instead */ Collection.prototype.findAndRemove = function(query, sort, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; sort = args.length ? args.shift() || [] : []; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, findAndRemove, [this, query, sort, options, callback]); }; var findAndRemove = function(self, query, sort, options, callback) { // Add the remove option options['remove'] = true; // Execute the callback self.findAndModify(query, sort, null, options, callback); }; define.classMethod('findAndRemove', { callback: true, promise: true }); function decorateWithWriteConcern(command, self, options) { // Do we support collation 3.4 and higher var capabilities = self.s.topology.capabilities(); // Do we support write concerns 3.4 and higher if (capabilities && capabilities.commandsTakeWriteConcern) { // Get the write concern settings var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); // Add the write concern to the command if (finalOptions.writeConcern) { command.writeConcern = finalOptions.writeConcern; } } } function decorateWithCollation(command, self, options) { // Do we support collation 3.4 and higher var capabilities = self.s.topology.capabilities(); // Do we support write concerns 3.4 and higher if (capabilities && capabilities.commandsTakeCollation) { if (options.collation && typeof options.collation === 'object') { command.collation = options.collation; } } } function decorateWithReadConcern(command, self, options) { let readConcern = Object.assign({}, command.readConcern || {}); if (self.s.readConcern) { Object.assign(readConcern, self.s.readConcern); } if ( options.session && options.session.supports.causalConsistency && options.session.operationTime ) { Object.assign(readConcern, { afterClusterTime: options.session.operationTime }); } if (Object.keys(readConcern).length > 0) { Object.assign(command, { readConcern: readConcern }); } } /** * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 * @method * @param {object} pipeline Array containing all the aggregation framework commands for the execution. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {string} [options.comment] Add a comment to an aggregation command * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~aggregationCallback} callback The command result callback * @return {(null|AggregationCursor)} */ Collection.prototype.aggregate = function(pipeline, options, callback) { var self = this; if (Array.isArray(pipeline)) { // Set up callback if one is provided if (typeof options === 'function') { callback = options; options = {}; } // If we have no options or callback we are doing // a cursor based aggregation if (options == null && callback == null) { options = {}; } } else { // Aggregation pipeline passed as arguments on the method var args = Array.prototype.slice.call(arguments, 0); // Get the callback callback = args.pop(); // Get the possible options object var opts = args[args.length - 1]; // If it contains any of the admissible options pop it of the args options = opts && (opts.readPreference || opts.explain || opts.cursor || opts.out || opts.maxTimeMS || opts.hint || opts.allowDiskUse) ? args.pop() : {}; // Left over arguments is the pipeline pipeline = args; } // Ignore readConcern option var ignoreReadConcern = false; // Build the command var command = { aggregate: this.s.name, pipeline: pipeline }; // If out was specified if (typeof options.out === 'string') { pipeline.push({ $out: options.out }); // Ignore read concern ignoreReadConcern = true; } else if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { ignoreReadConcern = true; } // Decorate command with writeConcern if out has been specified if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { decorateWithWriteConcern(command, self, options); } // Have we specified collation decorateWithCollation(command, self, options); // If we have bypassDocumentValidation set if (typeof options.bypassDocumentValidation === 'boolean') { command.bypassDocumentValidation = options.bypassDocumentValidation; } // Do we have a readConcern specified if (!ignoreReadConcern) { decorateWithReadConcern(command, self, options); } // If we have allowDiskUse defined if (options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS; // If we are giving a hint if (options.hint) command.hint = options.hint; options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(this, options, this.s.db, this); // If explain has been specified add it if (options.explain) { if (command.readConcern || command.writeConcern) { throw toError('"explain" cannot be used on an aggregate call with readConcern/writeConcern'); } command.explain = options.explain; } if (typeof options.comment === 'string') command.comment = options.comment; // Validate that cursor options is valid if (options.cursor != null && typeof options.cursor !== 'object') { throw toError('cursor options must be an object'); } options.cursor = options.cursor || { batchSize: 1000 }; command.cursor = options.cursor; // promiseLibrary options.promiseLibrary = this.s.promiseLibrary; // Set the AggregationCursor constructor options.cursorFactory = AggregationCursor; if (typeof callback !== 'function') { if (!this.s.topology.capabilities()) { throw new MongoError('cannot connect to server'); } // Allow disk usage command if (typeof options.allowDiskUse === 'boolean') command.allowDiskUse = options.allowDiskUse; if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS; // Execute the cursor return this.s.topology.cursor(this.s.namespace, command, options); } return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, command, options)); }; define.classMethod('aggregate', { callback: true, promise: false }); /** * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. * @method * @since 3.0.0 * @param {Array} [pipeline=null] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. * @param {object} [options=null] Optional settings * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. * @param {object} [options.resumeAfter=null] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query * @param {number} [options.batchSize=null] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. * @param {object} [options.collation=null] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. * @param {ReadPreference} [options.readPreference=null] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. * @param {ClientSession} [options.session] optional session to use for this operation * @return {ChangeStream} a ChangeStream instance. */ Collection.prototype.watch = function(pipeline, options) { pipeline = pipeline || []; options = options || {}; // Allow optionally not specifying a pipeline if (!Array.isArray(pipeline)) { options = pipeline; pipeline = []; } return new ChangeStream(this, pipeline, options); }; define.classMethod('watch', { callback: false, promise: false }); /** * The callback format for results * @callback Collection~parallelCollectionScanCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. */ /** * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are * no ordering guarantees for returned results. * @method * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.parallelCollectionScan = function(options, callback) { if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); // Set number of cursors to 1 options.numCursors = options.numCursors || 1; options.batchSize = options.batchSize || 1000; options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(this, options, this.s.db, this); // Add a promiseLibrary options.promiseLibrary = this.s.promiseLibrary; return executeOperation(this.s.topology, parallelCollectionScan, [this, options, callback], { returnsCursor: true }); }; var parallelCollectionScan = function(self, options, callback) { // Create command object var commandObject = { parallelCollectionScan: self.s.name, numCursors: options.numCursors }; // Do we have a readConcern specified decorateWithReadConcern(commandObject, self, options); // Store the raw value var raw = options.raw; delete options['raw']; // Execute the command self.s.db.command(commandObject, options, function(err, result) { if (err) return handleCallback(callback, err, null); if (result == null) return handleCallback( callback, new Error('no result returned for parallelCollectionScan'), null ); var cursors = []; // Add the raw back to the option if (raw) options.raw = raw; // Create command cursors for each item for (var i = 0; i < result.cursors.length; i++) { var rawId = result.cursors[i].cursor.id; // Convert cursorId to Long if needed var cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; // Add a command cursor cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); } handleCallback(callback, null, cursors); }); }; define.classMethod('parallelCollectionScan', { callback: true, promise: true }); /** * Execute a geo search using a geo haystack index on a collection. * * @method * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. * @param {object} [options.search=null] Filter the results by a query. * @param {number} [options.limit=false] Max number of results to return. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { var args = Array.prototype.slice.call(arguments, 2); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, geoHaystackSearch, [this, x, y, options, callback]); }; var geoHaystackSearch = function(self, x, y, options, callback) { // Build command object var commandObject = { geoSearch: self.s.name, near: [x, y] }; // Remove read preference from hash if it exists commandObject = decorateCommand(commandObject, options, { readPreference: true, session: true }); options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(self, options, self.s.db, self); // Do we have a readConcern specified decorateWithReadConcern(commandObject, self, options); // Execute the command self.s.db.command(commandObject, options, function(err, res) { if (err) return handleCallback(callback, err); if (res.err || res.errmsg) handleCallback(callback, toError(res)); // should we only be returning res.results here? Not sure if the user // should see the other return information handleCallback(callback, null, res); }); }; define.classMethod('geoHaystackSearch', { callback: true, promise: true }); /** * Group function helper * @ignore */ // var groupFunction = function () { // var c = db[ns].find(condition); // var map = new Map(); // var reduce_function = reduce; // // while (c.hasNext()) { // var obj = c.next(); // var key = {}; // // for (var i = 0, len = keys.length; i < len; ++i) { // var k = keys[i]; // key[k] = obj[k]; // } // // var aggObj = map.get(key); // // if (aggObj == null) { // var newObj = Object.extend({}, key); // aggObj = Object.extend(newObj, initial); // map.put(key, aggObj); // } // // reduce_function(obj, aggObj); // } // // return { "result": map.values() }; // }.toString(); var groupFunction = 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; /** * Run a group command across a collection * * @method * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. * @param {object} condition An optional condition that must be true for a row to be considered. * @param {object} initial Initial value of the aggregation counter object. * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. */ Collection.prototype.group = function( keys, condition, initial, reduce, finalize, command, options, callback ) { var args = Array.prototype.slice.call(arguments, 3); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; reduce = args.length ? args.shift() : null; finalize = args.length ? args.shift() : null; command = args.length ? args.shift() : null; options = args.length ? args.shift() || {} : {}; // Make sure we are backward compatible if (!(typeof finalize === 'function')) { command = finalize; finalize = null; } if ( !Array.isArray(keys) && keys instanceof Object && typeof keys !== 'function' && !(keys._bsontype === 'Code') ) { keys = Object.keys(keys); } if (typeof reduce === 'function') { reduce = reduce.toString(); } if (typeof finalize === 'function') { finalize = finalize.toString(); } // Set up the command as default command = command == null ? true : command; return executeOperation(this.s.topology, group, [ this, keys, condition, initial, reduce, finalize, command, options, callback ]); }; var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { // Execute using the command if (command) { var reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); var selector = { group: { ns: self.s.name, $reduce: reduceFunction, cond: condition, initial: initial, out: 'inline' } }; // if finalize is defined if (finalize != null) selector.group['finalize'] = finalize; // Set up group selector if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); } else { var hash = {}; keys.forEach(function(key) { hash[key] = 1; }); selector.group.key = hash; } options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(self, options, self.s.db, self); // Do we have a readConcern specified decorateWithReadConcern(selector, self, options); // Have we specified collation decorateWithCollation(selector, self, options); // Execute command self.s.db.command(selector, options, function(err, result) { if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.retval); }); } else { // Create execution scope var scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; scope.ns = self.s.name; scope.keys = keys; scope.condition = condition; scope.initial = initial; // Pass in the function text to execute within mongodb. var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); self.s.db.eval(new Code(groupfn, scope), null, options, function(err, results) { if (err) return handleCallback(callback, err, null); handleCallback(callback, null, results.result || results); }); } }; define.classMethod('group', { callback: true, promise: true }); /** * Functions that are passed as scope args must * be converted to Code instances. * @ignore */ function processScope(scope) { if (!isObject(scope) || scope._bsontype === 'ObjectID') { return scope; } var keys = Object.keys(scope); var i = keys.length; var key; var new_scope = {}; while (i--) { key = keys[i]; if ('function' === typeof scope[key]) { new_scope[key] = new Code(String(scope[key])); } else { new_scope[key] = processScope(scope[key]); } } return new_scope; } /** * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. * * @method * @param {(function|string)} map The mapping function. * @param {(function|string)} reduce The reduce function. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* * @param {object} [options.query=null] Query filter object. * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. * @param {number} [options.limit=null] Number of objects to return from collection. * @param {boolean} [options.keeptemp=false] Keep temporary data. * @param {(function|string)} [options.finalize=null] Finalize function. * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. * @param {boolean} [options.verbose=false] Provide statistics on job execution time. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~resultCallback} [callback] The command result callback * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ Collection.prototype.mapReduce = function(map, reduce, options, callback) { if ('function' === typeof options) (callback = options), (options = {}); // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) if (null == options.out) { throw new Error( 'the out option parameter must be defined, see mongodb docs for possible values' ); } if ('function' === typeof map) { map = map.toString(); } if ('function' === typeof reduce) { reduce = reduce.toString(); } if ('function' === typeof options.finalize) { options.finalize = options.finalize.toString(); } return executeOperation(this.s.topology, mapReduce, [this, map, reduce, options, callback]); }; var mapReduce = function(self, map, reduce, options, callback) { var mapCommandHash = { mapreduce: self.s.name, map: map, reduce: reduce }; // Exclusion list var exclusionList = ['readPreference', 'session']; // Add any other options passed in for (var n in options) { if ('scope' === n) { mapCommandHash[n] = processScope(options[n]); } else { // Only include if not in exclusion list if (exclusionList.indexOf(n) === -1) { mapCommandHash[n] = options[n]; } } } options = shallowClone(options); // Ensure we have the right read preference inheritance options = getReadPreference(self, options, self.s.db, self); // If we have a read preference and inline is not set as output fail hard if ( options.readPreference !== false && options.readPreference !== 'primary' && options['out'] && (options['out'].inline !== 1 && options['out'] !== 'inline') ) { // Force readPreference to primary options.readPreference = 'primary'; // Decorate command with writeConcern if supported decorateWithWriteConcern(mapCommandHash, self, options); } else { decorateWithReadConcern(mapCommandHash, self, options); } // Is bypassDocumentValidation specified if (typeof options.bypassDocumentValidation === 'boolean') { mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; } // Have we specified collation decorateWithCollation(mapCommandHash, self, options); // Execute command self.s.db.command(mapCommandHash, options, function(err, result) { if (err) return handleCallback(callback, err); // Check if we have an error if (1 !== result.ok || result.err || result.errmsg) { return handleCallback(callback, toError(result)); } // Create statistics value var stats = {}; if (result.timeMillis) stats['processtime'] = result.timeMillis; if (result.counts) stats['counts'] = result.counts; if (result.timing) stats['timing'] = result.timing; // invoked with inline? if (result.results) { // If we wish for no verbosity if (options['verbose'] == null || !options['verbose']) { return handleCallback(callback, null, result.results); } return handleCallback(callback, null, { results: result.results, stats: stats }); } // The returned collection var collection = null; // If we have an object it's a different db if (result.result != null && typeof result.result === 'object') { var doc = result.result; // Return a collection from another db var Db = require('./db'); collection = new Db(doc.db, self.s.db.s.topology, self.s.db.s.options).collection( doc.collection ); } else { // Create a collection object that wraps the result collection collection = self.s.db.collection(result.result); } // If we wish for no verbosity if (options['verbose'] == null || !options['verbose']) { return handleCallback(callback, err, collection); } // Return stats as third set of values handleCallback(callback, err, { collection: collection, stats: stats }); }); }; define.classMethod('mapReduce', { callback: true, promise: true }); /** * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. * * @method * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @return {UnorderedBulkOperation} */ Collection.prototype.initializeUnorderedBulkOp = function(options) { options = options || {}; options.promiseLibrary = this.s.promiseLibrary; return unordered(this.s.topology, this, options); }; define.classMethod('initializeUnorderedBulkOp', { callback: false, promise: false, returns: [ordered.UnorderedBulkOperation] }); /** * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. * * @method * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {OrderedBulkOperation} callback The command result callback * @return {null} */ Collection.prototype.initializeOrderedBulkOp = function(options) { options = options || {}; options.promiseLibrary = this.s.promiseLibrary; return ordered(this.s.topology, this, options); }; define.classMethod('initializeOrderedBulkOp', { callback: false, promise: false, returns: [ordered.OrderedBulkOperation] }); // Get write concern var writeConcern = function(target, db, col, options) { if (options.w != null || options.j != null || options.fsync != null) { var opts = {}; if (options.w != null) opts.w = options.w; if (options.wtimeout != null) opts.wtimeout = options.wtimeout; if (options.j != null) opts.j = options.j; if (options.fsync != null) opts.fsync = options.fsync; target.writeConcern = opts; } else if ( col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null ) { target.writeConcern = col.writeConcern; } else if ( db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null ) { target.writeConcern = db.writeConcern; } // NOTE: there is probably a much better place for this if (db.s.options.retryWrites) target.retryWrites = true; return target; }; // Figure out the read preference var getReadPreference = function(self, options, db) { let r = null; if (options.readPreference) { r = options.readPreference; } else if (self.s.readPreference) { r = self.s.readPreference; } else if (db.s.readPreference) { r = db.s.readPreference; } else { return options; } if (typeof r === 'string') { options.readPreference = new ReadPreference(r); } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { const mode = r.mode || r.preference; if (mode && typeof mode === 'string') { options.readPreference = new ReadPreference(mode, r.tags, { maxStalenessSeconds: r.maxStalenessSeconds }); } } else if (!(r instanceof ReadPreference)) { throw new TypeError('Invalid read preference: ' + r); } return options; }; module.exports = Collection; }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":335,"./aggregation_cursor":376,"./bulk/ordered":380,"./bulk/unordered":381,"./change_stream":382,"./command_cursor":384,"./cursor":385,"./db":386,"./metadata":392,"./utils":399,"mongodb-core":345,"util":563}],384:[function(require,module,exports){ 'use strict'; var inherits = require('util').inherits, ReadPreference = require('mongodb-core').ReadPreference, MongoError = require('mongodb-core').MongoError, Readable = require('stream').Readable, Define = require('./metadata'), CoreCursor = require('./cursor'); /** * @fileOverview The **CommandCursor** class is an internal class that embodies a * generalized cursor based on a MongoDB command allowing for iteration over the * results returned. It supports one by one document iteration, conversion to an * array or can be iterated as a Node 0.10.X or higher stream * * **CommandCursor Cannot directly be instantiated** * @example * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * // Create a collection we want to drop later * const col = client.db(dbName).collection('listCollectionsExample1'); * // Insert a bunch of documents * col.insert([{a:1, b:1} * , {a:2, b:2}, {a:3, b:3} * , {a:4, b:4}], {w:1}, function(err, result) { * test.equal(null, err); * // List the database collections available * db.listCollections().toArray(function(err, items) { * test.equal(null, err); * client.close(); * }); * }); * }); */ /** * Namespace provided by the browser. * @external Readable */ /** * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) * @class CommandCursor * @extends external:Readable * @fires CommandCursor#data * @fires CommandCursor#end * @fires CommandCursor#close * @fires CommandCursor#readable * @return {CommandCursor} an CommandCursor instance. */ var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); var state = CommandCursor.INIT; var streamOptions = {}; // MaxTimeMS var maxTimeMS = null; // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Set up Readable.call(this, { objectMode: true }); // Internal state this.s = { // MaxTimeMS maxTimeMS: maxTimeMS, // State state: state, // Stream options streamOptions: streamOptions, // BSON bson: bson, // Namespace ns: ns, // Command cmd: cmd, // Options options: options, // Topology topology: topology, // Topology Options topologyOptions: topologyOptions, // Promise library promiseLibrary: promiseLibrary }; }; /** * CommandCursor stream data event, fired for each document in the cursor. * * @event CommandCursor#data * @type {object} */ /** * CommandCursor stream end event * * @event CommandCursor#end * @type {null} */ /** * CommandCursor stream close event * * @event CommandCursor#close * @type {null} */ /** * CommandCursor stream readable event * * @event CommandCursor#readable * @type {null} */ // Inherit from Readable inherits(CommandCursor, Readable); // Set the methods to inherit from prototype var methodsToInherit = [ '_next', 'next', 'hasNext', 'each', 'forEach', 'toArray', 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill', 'setCursorBatchSize', '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled' ]; // Only inherit the types we need for (var i = 0; i < methodsToInherit.length; i++) { CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; } var define = (CommandCursor.define = new Define('CommandCursor', CommandCursor, true)); /** * Set the ReadPreference for the cursor. * @method * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. * @throws {MongoError} * @return {Cursor} */ CommandCursor.prototype.setReadPreference = function(readPreference) { if (this.s.state === CommandCursor.CLOSED || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } if (this.s.state !== CommandCursor.INIT) { throw MongoError.create({ message: 'cannot change cursor readPreference after cursor has been accessed', driver: true }); } if (readPreference instanceof ReadPreference) { this.s.options.readPreference = readPreference; } else if (typeof readPreference === 'string') { this.s.options.readPreference = new ReadPreference(readPreference); } else { throw new TypeError('Invalid read preference: ' + readPreference); } return this; }; define.classMethod('setReadPreference', { callback: false, promise: false, returns: [CommandCursor] }); /** * Set the batch size for the cursor. * @method * @param {number} value The batchSize for the cursor. * @throws {MongoError} * @return {CommandCursor} */ CommandCursor.prototype.batchSize = function(value) { if (this.s.state === CommandCursor.CLOSED || this.isDead()) throw MongoError.create({ message: 'Cursor is closed', driver: true }); if (typeof value !== 'number') throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; this.setCursorBatchSize(value); return this; }; define.classMethod('batchSize', { callback: false, promise: false, returns: [CommandCursor] }); /** * Add a maxTimeMS stage to the aggregation pipeline * @method * @param {number} value The state maxTimeMS value. * @return {CommandCursor} */ CommandCursor.prototype.maxTimeMS = function(value) { if (this.s.topology.lastIsMaster().minWireVersion > 2) { this.s.cmd.maxTimeMS = value; } return this; }; define.classMethod('maxTimeMS', { callback: false, promise: false, returns: [CommandCursor] }); CommandCursor.prototype.get = CommandCursor.prototype.toArray; define.classMethod('get', { callback: true, promise: false }); // Inherited methods define.classMethod('toArray', { callback: true, promise: true }); define.classMethod('each', { callback: true, promise: false }); define.classMethod('forEach', { callback: true, promise: false }); define.classMethod('next', { callback: true, promise: true }); define.classMethod('hasNext', { callback: true, promise: true }); define.classMethod('close', { callback: true, promise: true }); define.classMethod('isClosed', { callback: false, promise: false, returns: [Boolean] }); define.classMethod('rewind', { callback: false, promise: false }); define.classMethod('bufferedCount', { callback: false, promise: false, returns: [Number] }); define.classMethod('readBufferedDocuments', { callback: false, promise: false, returns: [Array] }); /** * Get the next available document from the cursor, returns null if no more documents are available. * @function CommandCursor.prototype.next * @param {CommandCursor~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * Check if there is any document still available in the cursor * @function CommandCursor.prototype.hasNext * @param {CommandCursor~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * The callback format for results * @callback CommandCursor~toArrayResultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object[]} documents All the documents the satisfy the cursor. */ /** * Returns an array of documents. The caller is responsible for making sure that there * is enough memory to store the results. Note that the array only contain partial * results when this cursor had been previouly accessed. * @method CommandCursor.prototype.toArray * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ /** * The callback format for results * @callback CommandCursor~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {(object|null)} result The result object if the command was executed successfully. */ /** * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, * not all of the elements will be iterated if this cursor had been previouly accessed. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements * at any given time if batch size is specified. Otherwise, the caller is responsible * for making sure that the entire result can fit the memory. * @method CommandCursor.prototype.each * @param {CommandCursor~resultCallback} callback The result callback. * @throws {MongoError} * @return {null} */ /** * Close the cursor, sending a KillCursor command and emitting close. * @method CommandCursor.prototype.close * @param {CommandCursor~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ /** * Is the cursor closed * @method CommandCursor.prototype.isClosed * @return {boolean} */ /** * Clone the cursor * @function CommandCursor.prototype.clone * @return {CommandCursor} */ /** * Resets the cursor * @function CommandCursor.prototype.rewind * @return {CommandCursor} */ /** * The callback format for the forEach iterator method * @callback CommandCursor~iteratorCallback * @param {Object} doc An emitted document for the iterator */ /** * The callback error format for the forEach iterator method * @callback CommandCursor~endCallback * @param {MongoError} error An error instance representing the error during the execution. */ /* * Iterates over all the documents for this cursor using the iterator, callback pattern. * @method CommandCursor.prototype.forEach * @param {CommandCursor~iteratorCallback} iterator The iteration callback. * @param {CommandCursor~endCallback} callback The end callback. * @throws {MongoError} * @return {null} */ CommandCursor.INIT = 0; CommandCursor.OPEN = 1; CommandCursor.CLOSED = 2; module.exports = CommandCursor; },{"./cursor":385,"./metadata":392,"mongodb-core":345,"stream":548,"util":563}],385:[function(require,module,exports){ 'use strict'; var inherits = require('util').inherits, f = require('util').format, formattedOrderClause = require('./utils').formattedOrderClause, handleCallback = require('./utils').handleCallback, ReadPreference = require('mongodb-core').ReadPreference, MongoError = require('mongodb-core').MongoError, Readable = require('stream').Readable, Define = require('./metadata'), CoreCursor = require('mongodb-core').Cursor, Map = require('mongodb-core').BSON.Map, executeOperation = require('./utils').executeOperation; /** * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB * allowing for iteration over the results returned from the underlying query. It supports * one by one document iteration, conversion to an array or can be iterated as a Node 4.X * or higher stream * * **CURSORS Cannot directly be instantiated** * @example * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * // Create a collection we want to drop later * const col = client.db(dbName).collection('createIndexExample1'); * // Insert a bunch of documents * col.insert([{a:1, b:1} * , {a:2, b:2}, {a:3, b:3} * , {a:4, b:4}], {w:1}, function(err, result) { * test.equal(null, err); * // Show that duplicate records got dropped * col.find({}).toArray(function(err, items) { * test.equal(null, err); * test.equal(4, items.length); * client.close(); * }); * }); * }); */ /** * Namespace provided by the mongodb-core and node.js * @external CoreCursor * @external Readable */ // Flags allowed for cursor var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; var fields = ['numberOfRetries', 'tailableRetryInterval']; var push = Array.prototype.push; /** * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) * @class Cursor * @extends external:CoreCursor * @extends external:Readable * @property {string} sortValue Cursor query sort setting. * @property {boolean} timeout Is Cursor able to time out. * @property {ReadPreference} readPreference Get cursor ReadPreference. * @fires Cursor#data * @fires Cursor#end * @fires Cursor#close * @fires Cursor#readable * @return {Cursor} a Cursor instance. * @example * Cursor cursor options. * * collection.find({}).project({a:1}) // Create a projection of field a * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 * collection.find({}).filter({a:1}) // Set query on the cursor * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} * collection.find({}).max(10) // Set the cursor maxScan * collection.find({}).maxScan(10) // Set the cursor maxScan * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS * collection.find({}).min(100) // Set the cursor min * collection.find({}).returnKey(10) // Set the cursor returnKey * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference * collection.find({}).showRecordId(true) // Set the cursor showRecordId * collection.find({}).snapshot(true) // Set the cursor snapshot * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query * collection.find({}).hint('a_1') // Set the cursor hint * * All options are chainable, so one can do the following. * * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) */ var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); var state = Cursor.INIT; var streamOptions = {}; // Tailable cursor options var numberOfRetries = options.numberOfRetries || 5; var tailableRetryInterval = options.tailableRetryInterval || 500; var currentNumberOfRetries = numberOfRetries; // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Set up Readable.call(this, { objectMode: true }); // Internal cursor state this.s = { // Tailable cursor options numberOfRetries: numberOfRetries, tailableRetryInterval: tailableRetryInterval, currentNumberOfRetries: currentNumberOfRetries, // State state: state, // Stream options streamOptions: streamOptions, // BSON bson: bson, // Namespace ns: ns, // Command cmd: cmd, // Options options: options, // Topology topology: topology, // Topology options topologyOptions: topologyOptions, // Promise library promiseLibrary: promiseLibrary, // Current doc currentDoc: null, // Optional ClientSession session: options.session }; // Translate correctly if (this.s.options.noCursorTimeout === true) { this.addCursorFlag('noCursorTimeout', true); } // Set the sort value this.sortValue = this.s.cmd.sort; // Get the batchSize var batchSize = cmd.cursor && cmd.cursor.batchSize ? cmd.cursor && cmd.cursor.batchSize : options.cursor && options.cursor.batchSize ? options.cursor.batchSize : 1000; // Set the batchSize this.setCursorBatchSize(batchSize); }; /** * Cursor stream data event, fired for each document in the cursor. * * @event Cursor#data * @type {object} */ /** * Cursor stream end event * * @event Cursor#end * @type {null} */ /** * Cursor stream close event * * @event Cursor#close * @type {null} */ /** * Cursor stream readable event * * @event Cursor#readable * @type {null} */ // Inherit from Readable inherits(Cursor, Readable); // Map core cursor _next method so we can apply mapping CoreCursor.prototype._next = CoreCursor.prototype.next; for (var name in CoreCursor.prototype) { Cursor.prototype[name] = CoreCursor.prototype[name]; } var define = (Cursor.define = new Define('Cursor', Cursor, true)); /** * Check if there is any document still available in the cursor * @method * @param {Cursor~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ Cursor.prototype.hasNext = function(callback) { return executeOperation(this.s.topology, hasNext, [this, callback], { skipSessions: true }); }; const hasNext = (self, callback) => { if (self.s.currentDoc) { return callback(null, true); } nextObject(self, function(err, doc) { if (err) return callback(err, null); if (self.s.state === Cursor.CLOSED || self.isDead()) return callback(null, false); if (!doc) return callback(null, false); self.s.currentDoc = doc; callback(null, true); }); }; define.classMethod('hasNext', { callback: true, promise: true }); /** * Get the next available document from the cursor, returns null if no more documents are available. * @method * @param {Cursor~resultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ Cursor.prototype.next = function(callback) { return executeOperation(this.s.topology, next, [this, callback], { skipSessions: true }); }; const next = (self, callback) => { // Return the currentDoc if someone called hasNext first if (self.s.currentDoc) { var doc = self.s.currentDoc; self.s.currentDoc = null; return callback(null, doc); } // Return the next object nextObject(self, callback); }; define.classMethod('next', { callback: true, promise: true }); /** * Set the cursor query * @method * @param {object} filter The filter object used for the cursor. * @return {Cursor} */ Cursor.prototype.filter = function(filter) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.query = filter; return this; }; define.classMethod('filter', { callback: false, promise: false, returns: [Cursor] }); /** * Set the cursor maxScan * @method * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query * @return {Cursor} */ Cursor.prototype.maxScan = function(maxScan) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.maxScan = maxScan; return this; }; define.classMethod('maxScan', { callback: false, promise: false, returns: [Cursor] }); /** * Set the cursor hint * @method * @param {object} hint If specified, then the query system will only consider plans using the hinted index. * @return {Cursor} */ Cursor.prototype.hint = function(hint) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.hint = hint; return this; }; define.classMethod('hint', { callback: false, promise: false, returns: [Cursor] }); /** * Set the cursor min * @method * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. * @return {Cursor} */ Cursor.prototype.min = function(min) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) throw MongoError.create({ message: 'Cursor is closed', driver: true }); this.s.cmd.min = min; return this; }; define.classMethod('min', { callback: false, promise: false, returns: [Cursor] }); /** * Set the cursor max * @method * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. * @return {Cursor} */ Cursor.prototype.max = function(max) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.max = max; return this; }; define.classMethod('max', { callback: false, promise: false, returns: [Cursor] }); /** * Set the cursor returnKey * @method * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: * @return {Cursor} */ Cursor.prototype.returnKey = function(value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.returnKey = value; return this; }; define.classMethod('returnKey', { callback: false, promise: false, returns: [Cursor] }); /** * Set the cursor showRecordId * @method * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. * @return {Cursor} */ Cursor.prototype.showRecordId = function(value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.showDiskLoc = value; return this; }; define.classMethod('showRecordId', { callback: false, promise: false, returns: [Cursor] }); /** * Set the cursor snapshot * @method * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. * @return {Cursor} */ Cursor.prototype.snapshot = function(value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.snapshot = value; return this; }; define.classMethod('snapshot', { callback: false, promise: false, returns: [Cursor] }); /** * Set a node.js specific cursor option * @method * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. * @param {object} value The field value. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.setCursorOption = function(field, value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } if (fields.indexOf(field) === -1) { throw MongoError.create({ message: f('option %s not a supported option %s', field, fields), driver: true }); } this.s[field] = value; if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; return this; }; define.classMethod('setCursorOption', { callback: false, promise: false, returns: [Cursor] }); /** * Add a cursor flag to the cursor * @method * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. * @param {boolean} value The flag boolean value. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.addCursorFlag = function(flag, value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } if (flags.indexOf(flag) === -1) { throw MongoError.create({ message: f('flag %s not a supported flag %s', flag, flags), driver: true }); } if (typeof value !== 'boolean') { throw MongoError.create({ message: f('flag %s must be a boolean value', flag), driver: true }); } this.s.cmd[flag] = value; return this; }; define.classMethod('addCursorFlag', { callback: false, promise: false, returns: [Cursor] }); /** * Add a query modifier to the cursor query * @method * @param {string} name The query modifier (must start with $, such as $orderby etc) * @param {boolean} value The flag boolean value. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.addQueryModifier = function(name, value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } if (name[0] !== '$') { throw MongoError.create({ message: f('%s is not a valid query modifier'), driver: true }); } // Strip of the $ var field = name.substr(1); // Set on the command this.s.cmd[field] = value; // Deal with the special case for sort if (field === 'orderby') this.s.cmd.sort = this.s.cmd[field]; return this; }; define.classMethod('addQueryModifier', { callback: false, promise: false, returns: [Cursor] }); /** * Add a comment to the cursor query allowing for tracking the comment in the log. * @method * @param {string} value The comment attached to this query. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.comment = function(value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.comment = value; return this; }; define.classMethod('comment', { callback: false, promise: false, returns: [Cursor] }); /** * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) * @method * @param {number} value Number of milliseconds to wait before aborting the tailed query. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.maxAwaitTimeMS = function(value) { if (typeof value !== 'number') { throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); } if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.maxAwaitTimeMS = value; return this; }; define.classMethod('maxAwaitTimeMS', { callback: false, promise: false, returns: [Cursor] }); /** * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) * @method * @param {number} value Number of milliseconds to wait before aborting the query. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.maxTimeMS = function(value) { if (typeof value !== 'number') { throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); } if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.maxTimeMS = value; return this; }; define.classMethod('maxTimeMS', { callback: false, promise: false, returns: [Cursor] }); Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; define.classMethod('maxTimeMs', { callback: false, promise: false, returns: [Cursor] }); /** * Sets a field projection for the query. * @method * @param {object} value The field projection object. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.project = function(value) { if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } this.s.cmd.fields = value; return this; }; define.classMethod('project', { callback: false, promise: false, returns: [Cursor] }); /** * Sets the sort order of the cursor query. * @method * @param {(string|array|object)} keyOrList The key or keys set for the sort. * @param {number} [direction] The direction of the sorting (1 or -1). * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.sort = function(keyOrList, direction) { if (this.s.options.tailable) { throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); } if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } var order = keyOrList; // We have an array of arrays, we need to preserve the order of the sort // so we will us a Map if (Array.isArray(order) && Array.isArray(order[0])) { order = new Map( order.map(function(x) { var value = [x[0], null]; if (x[1] === 'asc') { value[1] = 1; } else if (x[1] === 'desc') { value[1] = -1; } else if (x[1] === 1 || x[1] === -1) { value[1] = x[1]; } else { throw new MongoError( "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" ); } return value; }) ); } if (direction != null) { order = [[keyOrList, direction]]; } this.s.cmd.sort = order; this.sortValue = order; return this; }; define.classMethod('sort', { callback: false, promise: false, returns: [Cursor] }); /** * Set the batch size for the cursor. * @method * @param {number} value The batchSize for the cursor. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.batchSize = function(value) { if (this.s.options.tailable) { throw MongoError.create({ message: "Tailable cursor doesn't support batchSize", driver: true }); } if (this.s.state === Cursor.CLOSED || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } if (typeof value !== 'number') { throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); } this.s.cmd.batchSize = value; this.setCursorBatchSize(value); return this; }; define.classMethod('batchSize', { callback: false, promise: false, returns: [Cursor] }); /** * Set the collation options for the cursor. * @method * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.collation = function(value) { this.s.cmd.collation = value; return this; }; define.classMethod('collation', { callback: false, promise: false, returns: [Cursor] }); /** * Set the limit for the cursor. * @method * @param {number} value The limit for the cursor query. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.limit = function(value) { if (this.s.options.tailable) { throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); } if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } if (typeof value !== 'number') { throw MongoError.create({ message: 'limit requires an integer', driver: true }); } this.s.cmd.limit = value; // this.cursorLimit = value; this.setCursorLimit(value); return this; }; define.classMethod('limit', { callback: false, promise: false, returns: [Cursor] }); /** * Set the skip for the cursor. * @method * @param {number} value The skip for the cursor query. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.skip = function(value) { if (this.s.options.tailable) { throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); } if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { throw MongoError.create({ message: 'Cursor is closed', driver: true }); } if (typeof value !== 'number') { throw MongoError.create({ message: 'skip requires an integer', driver: true }); } this.s.cmd.skip = value; this.setCursorSkip(value); return this; }; define.classMethod('skip', { callback: false, promise: false, returns: [Cursor] }); /** * The callback format for results * @callback Cursor~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {(object|null|boolean)} result The result object if the command was executed successfully. */ /** * Clone the cursor * @function external:CoreCursor#clone * @return {Cursor} */ /** * Resets the cursor * @function external:CoreCursor#rewind * @return {null} */ // Get the next available document from the cursor, returns null if no more documents are available. var nextObject = function(self, callback) { if (self.s.state === Cursor.CLOSED || (self.isDead && self.isDead())) return handleCallback( callback, MongoError.create({ message: 'Cursor is closed', driver: true }) ); if (self.s.state === Cursor.INIT && self.s.cmd.sort) { try { self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); } catch (err) { return handleCallback(callback, err); } } // Get the next object self._next(function(err, doc) { self.s.state = Cursor.OPEN; if (err) return handleCallback(callback, err); handleCallback(callback, null, doc); }); }; // Trampoline emptying the number of retrieved items // without incurring a nextTick operation var loop = function(self, callback) { // No more items we are done if (self.bufferedCount() === 0) return; // Get the next document self._next(callback); // Loop return loop; }; /** * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, * not all of the elements will be iterated if this cursor had been previouly accessed. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements * at any given time if batch size is specified. Otherwise, the caller is responsible * for making sure that the entire result can fit the memory. * @method * @deprecated * @param {Cursor~resultCallback} callback The result callback. * @throws {MongoError} * @return {null} */ Cursor.prototype.each = function(callback) { // Rewind cursor state this.rewind(); // Set current cursor to INIT this.s.state = Cursor.INIT; // Run the query _each(this, callback); }; define.classMethod('each', { callback: true, promise: false }); // Run the each loop var _each = function(self, callback) { if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); if (self.isNotified()) return; if (self.s.state === Cursor.CLOSED || self.isDead()) { return handleCallback( callback, MongoError.create({ message: 'Cursor is closed', driver: true }) ); } if (self.s.state === Cursor.INIT) self.s.state = Cursor.OPEN; // Define function to avoid global scope escape var fn = null; // Trampoline all the entries if (self.bufferedCount() > 0) { while ((fn = loop(self, callback))) fn(self, callback); _each(self, callback); } else { self.next(function(err, item) { if (err) return handleCallback(callback, err); if (item == null) { return self.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); } if (handleCallback(callback, null, item) === false) return; _each(self, callback); }); } }; /** * The callback format for the forEach iterator method * @callback Cursor~iteratorCallback * @param {Object} doc An emitted document for the iterator */ /** * The callback error format for the forEach iterator method * @callback Cursor~endCallback * @param {MongoError} error An error instance representing the error during the execution. */ /** * Iterates over all the documents for this cursor using the iterator, callback pattern. * @method * @param {Cursor~iteratorCallback} iterator The iteration callback. * @param {Cursor~endCallback} callback The end callback. * @throws {MongoError} * @return {null} */ Cursor.prototype.forEach = function(iterator, callback) { this.each(function(err, doc) { if (err) { callback(err); return false; } if (doc != null) { iterator(doc); return true; } if (doc == null && callback) { var internalCallback = callback; callback = null; internalCallback(null); return false; } }); }; define.classMethod('forEach', { callback: true, promise: false }); /** * Set the ReadPreference for the cursor. * @method * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. * @throws {MongoError} * @return {Cursor} */ Cursor.prototype.setReadPreference = function(readPreference) { if (this.s.state !== Cursor.INIT) { throw MongoError.create({ message: 'cannot change cursor readPreference after cursor has been accessed', driver: true }); } if (readPreference instanceof ReadPreference) { this.s.options.readPreference = readPreference; } else if (typeof readPreference === 'string') { this.s.options.readPreference = new ReadPreference(readPreference); } else { throw new TypeError('Invalid read preference: ' + readPreference); } return this; }; define.classMethod('setReadPreference', { callback: false, promise: false, returns: [Cursor] }); /** * The callback format for results * @callback Cursor~toArrayResultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object[]} documents All the documents the satisfy the cursor. */ /** * Returns an array of documents. The caller is responsible for making sure that there * is enough memory to store the results. Note that the array only contain partial * results when this cursor had been previouly accessed. In that case, * cursor.rewind() can be used to reset the cursor. * @method * @param {Cursor~toArrayResultCallback} [callback] The result callback. * @throws {MongoError} * @return {Promise} returns Promise if no callback passed */ Cursor.prototype.toArray = function(callback) { var self = this; if (self.s.options.tailable) { throw MongoError.create({ message: 'Tailable cursor cannot be converted to array', driver: true }); } return executeOperation(this.s.topology, toArray, [this, callback], { skipSessions: true }); }; var toArray = function(self, callback) { var items = []; // Reset cursor self.rewind(); self.s.state = Cursor.INIT; // Fetch all the documents var fetchDocs = function() { self._next(function(err, doc) { if (err) return handleCallback(callback, err); if (doc == null) { return self.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); } // Add doc to items items.push(doc); // Get all buffered objects if (self.bufferedCount() > 0) { var docs = self.readBufferedDocuments(self.bufferedCount()); // Transform the doc if transform method added if (self.s.transforms && typeof self.s.transforms.doc === 'function') { docs = docs.map(self.s.transforms.doc); } push.apply(items, docs); } // Attempt a fetch fetchDocs(); }); }; fetchDocs(); }; define.classMethod('toArray', { callback: true, promise: true }); /** * The callback format for results * @callback Cursor~countResultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {number} count The count of documents. */ /** * Get the count of documents for this cursor * @method * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. * @param {object} [options=null] Optional settings. * @param {number} [options.skip=null] The number of documents to skip. * @param {number} [options.limit=null] The maximum amounts to count before aborting. * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. * @param {string} [options.hint=null] An index name hint for the query. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {Cursor~countResultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ Cursor.prototype.count = function(applySkipLimit, opts, callback) { if (this.s.cmd.query == null) throw MongoError.create({ message: 'count can only be used with find command', driver: true }); if (typeof opts === 'function') (callback = opts), (opts = {}); opts = opts || {}; return executeOperation(this.s.topology, count, [this, applySkipLimit, opts, callback], { skipSessions: true }); }; var count = function(self, applySkipLimit, opts, callback) { if (typeof applySkipLimit === 'function') { callback = applySkipLimit; applySkipLimit = true; } if (applySkipLimit) { if (typeof self.cursorSkip() === 'number') opts.skip = self.cursorSkip(); if (typeof self.cursorLimit() === 'number') opts.limit = self.cursorLimit(); } // Command var delimiter = self.s.ns.indexOf('.'); var command = { count: self.s.ns.substr(delimiter + 1), query: self.s.cmd.query }; // Apply a readConcern if set if (self.s.cmd.readConcern) { command.readConcern = self.s.cmd.readConcern; } // Apply a hint if set if (self.s.cmd.hint) { command.hint = self.s.cmd.hint; } if (typeof opts.maxTimeMS === 'number') { command.maxTimeMS = opts.maxTimeMS; } else if (self.s.cmd && typeof self.s.cmd.maxTimeMS === 'number') { command.maxTimeMS = self.s.cmd.maxTimeMS; } // Merge in any options if (opts.skip) command.skip = opts.skip; if (opts.limit) command.limit = opts.limit; if (self.s.options.hint) command.hint = self.s.options.hint; // Set cursor server to the same as the topology self.server = self.topology.s.coreTopology; // Execute the command self.s.topology.command( f('%s.$cmd', self.s.ns.substr(0, delimiter)), command, function(err, result) { callback(err, result ? result.result.n : null); }, self.options ); }; define.classMethod('count', { callback: true, promise: true }); /** * Close the cursor, sending a KillCursor command and emitting close. * @method * @param {object} [options] Optional settings. * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. * @param {Cursor~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ Cursor.prototype.close = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, { skipKillCursors: false }, options); this.s.state = Cursor.CLOSED; if (!options.skipKillCursors) { // Kill the cursor this.kill(); } const completeClose = () => { // Emit the close event for the cursor this.emit('close'); // Callback if provided if (typeof callback === 'function') { return handleCallback(callback, null, this); } // Return a Promise return new this.s.promiseLibrary(function(resolve) { resolve(); }); }; if (this.s.session) { return this.s.session.endSession(() => completeClose()); } return completeClose(); }; define.classMethod('close', { callback: true, promise: true }); /** * Map all documents using the provided function * @method * @param {function} [transform] The mapping transformation method. * @return {Cursor} */ Cursor.prototype.map = function(transform) { if (this.cursorState.transforms && this.cursorState.transforms.doc) { var oldTransform = this.cursorState.transforms.doc; this.cursorState.transforms.doc = function(doc) { return transform(oldTransform(doc)); }; } else { this.cursorState.transforms = { doc: transform }; } return this; }; define.classMethod('map', { callback: false, promise: false, returns: [Cursor] }); /** * Is the cursor closed * @method * @return {boolean} */ Cursor.prototype.isClosed = function() { return this.isDead(); }; define.classMethod('isClosed', { callback: false, promise: false, returns: [Boolean] }); Cursor.prototype.destroy = function(err) { if (err) this.emit('error', err); this.pause(); this.close(); }; define.classMethod('destroy', { callback: false, promise: false }); /** * Return a modified Readable stream including a possible transform method. * @method * @param {object} [options=null] Optional settings. * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. * @return {Cursor} */ Cursor.prototype.stream = function(options) { this.s.streamOptions = options || {}; return this; }; define.classMethod('stream', { callback: false, promise: false, returns: [Cursor] }); /** * Execute the explain for the cursor * @method * @param {Cursor~resultCallback} [callback] The result callback. * @return {Promise} returns Promise if no callback passed */ Cursor.prototype.explain = function(callback) { this.s.cmd.explain = true; // Do we have a readConcern if (this.s.cmd.readConcern) { delete this.s.cmd['readConcern']; } return executeOperation(this.s.topology, this._next.bind(this), [callback], { skipSessions: true }); }; define.classMethod('explain', { callback: true, promise: true }); Cursor.prototype._read = function() { var self = this; if (self.s.state === Cursor.CLOSED || self.isDead()) { return self.push(null); } // Get the next item self.next(function(err, result) { if (err) { if (self.listeners('error') && self.listeners('error').length > 0) { self.emit('error', err); } if (!self.isDead()) self.close(); // Emit end event self.emit('end'); return self.emit('finish'); } // If we provided a transformation method if (typeof self.s.streamOptions.transform === 'function' && result != null) { return self.push(self.s.streamOptions.transform(result)); } // If we provided a map function if ( self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function' && result != null ) { return self.push(self.cursorState.transforms.doc(result)); } // Return the result self.push(result); if (result === null && self.isDead()) { self.once('end', () => { self.close(); self.emit('finish'); }); } }); }; Object.defineProperty(Cursor.prototype, 'readPreference', { enumerable: true, get: function() { if (!this || !this.s) { return null; } return this.s.options.readPreference; } }); Object.defineProperty(Cursor.prototype, 'namespace', { enumerable: true, get: function() { if (!this || !this.s) { return null; } // TODO: refactor this logic into core var ns = this.s.ns || ''; var firstDot = ns.indexOf('.'); if (firstDot < 0) { return { database: this.s.ns, collection: '' }; } return { database: ns.substr(0, firstDot), collection: ns.substr(firstDot + 1) }; } }); /** * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. * @function external:Readable#read * @param {number} size Optional argument to specify how much data to read. * @return {(String | Buffer | null)} */ /** * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. * @function external:Readable#setEncoding * @param {string} encoding The encoding to use. * @return {null} */ /** * This method will cause the readable stream to resume emitting data events. * @function external:Readable#resume * @return {null} */ /** * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. * @function external:Readable#pause * @return {null} */ /** * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. * @function external:Readable#pipe * @param {Writable} destination The destination for writing data * @param {object} [options] Pipe options * @return {null} */ /** * This method will remove the hooks set up for a previous pipe() call. * @function external:Readable#unpipe * @param {Writable} [destination] The destination for writing data * @return {null} */ /** * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. * @function external:Readable#unshift * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. * @return {null} */ /** * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) * @function external:Readable#wrap * @param {Stream} stream An "old style" readable stream. * @return {null} */ Cursor.INIT = 0; Cursor.OPEN = 1; Cursor.CLOSED = 2; Cursor.GET_MORE = 3; module.exports = Cursor; },{"./metadata":392,"./utils":399,"mongodb-core":345,"stream":548,"util":563}],386:[function(require,module,exports){ 'use strict'; var EventEmitter = require('events').EventEmitter, inherits = require('util').inherits, getSingleProperty = require('./utils').getSingleProperty, shallowClone = require('./utils').shallowClone, parseIndexOptions = require('./utils').parseIndexOptions, debugOptions = require('./utils').debugOptions, CommandCursor = require('./command_cursor'), handleCallback = require('./utils').handleCallback, filterOptions = require('./utils').filterOptions, toError = require('./utils').toError, ReadPreference = require('mongodb-core').ReadPreference, f = require('util').format, Admin = require('./admin'), Code = require('mongodb-core').BSON.Code, MongoError = require('mongodb-core').MongoError, ObjectID = require('mongodb-core').ObjectID, Define = require('./metadata'), Logger = require('mongodb-core').Logger, Collection = require('./collection'), crypto = require('crypto'), mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern, executeOperation = require('./utils').executeOperation; var debugFields = [ 'authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId', 'serializeFunctions', 'raw', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds', 'readPreference', 'pkFactory', 'parentDb', 'promiseLibrary', 'noListener' ]; // Filter out any write concern options var illegalCommandFields = [ 'w', 'wtimeout', 'j', 'fsync', 'autoIndexId', 'strict', 'serializeFunctions', 'pkFactory', 'raw', 'readPreference', 'session' ]; /** * @fileOverview The **Db** class is a class that represents a MongoDB Database. * * @example * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * // Get an additional db * const testDb = client.db('test'); * client.close(); * }); */ // Allowed parameters var legalOptionNames = [ 'w', 'wtimeout', 'fsync', 'j', 'readPreference', 'readPreferenceTags', 'native_parser', 'forceServerObjectId', 'pkFactory', 'serializeFunctions', 'raw', 'bufferMaxEntries', 'authSource', 'ignoreUndefined', 'promoteLongs', 'promiseLibrary', 'readConcern', 'retryMiliSeconds', 'numberOfRetries', 'parentDb', 'noListener', 'loggerLevel', 'logger', 'promoteBuffers', 'promoteLongs', 'promoteValues', 'compression', 'retryWrites' ]; /** * Creates a new Db instance * @class * @param {string} databaseName The name of the database this instance represents. * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. * @param {object} [options=null] Optional settings. * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database * @property {string} databaseName The name of the database this instance represents. * @property {object} options The options associated with the db instance. * @property {boolean} native_parser The current value of the parameter native_parser. * @property {boolean} slaveOk The current slaveOk value for the db instance. * @property {object} writeConcern The current write concern values. * @property {object} topology Access the topology object (single server, replicaset or mongos). * @fires Db#close * @fires Db#reconnect * @fires Db#error * @fires Db#timeout * @fires Db#parseError * @fires Db#fullsetup * @return {Db} a Db instance. */ var Db = function(databaseName, topology, options) { options = options || {}; if (!(this instanceof Db)) return new Db(databaseName, topology, options); EventEmitter.call(this); var self = this; // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Filter the options options = filterOptions(options, legalOptionNames); // Ensure we put the promiseLib in the options options.promiseLibrary = promiseLibrary; // var self = this; // Internal state of the db object this.s = { // Database name databaseName: databaseName, // DbCache dbCache: {}, // Children db's children: [], // Topology topology: topology, // Options options: options, // Logger instance logger: Logger('Db', options), // Get the bson parser bson: topology ? topology.bson : null, // Unpack read preference readPreference: options.readPreference, // Set buffermaxEntries bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, // Parent db (if chained) parentDb: options.parentDb || null, // Set up the primary key factory or fallback to ObjectID pkFactory: options.pkFactory || ObjectID, // Get native parser nativeParser: options.nativeParser || options.native_parser, // Promise library promiseLibrary: promiseLibrary, // No listener noListener: typeof options.noListener === 'boolean' ? options.noListener : false, // ReadConcern readConcern: options.readConcern }; // Ensure we have a valid db name validateDatabaseName(self.s.databaseName); // Add a read Only property getSingleProperty(this, 'serverConfig', self.s.topology); getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); getSingleProperty(this, 'databaseName', self.s.databaseName); // This is a child db, do not register any listeners if (options.parentDb) return; if (this.s.noListener) return; // Add listeners topology.on('error', createListener(self, 'error', self)); topology.on('timeout', createListener(self, 'timeout', self)); topology.on('close', createListener(self, 'close', self)); topology.on('parseError', createListener(self, 'parseError', self)); topology.once('open', createListener(self, 'open', self)); topology.once('fullsetup', createListener(self, 'fullsetup', self)); topology.once('all', createListener(self, 'all', self)); topology.on('reconnect', createListener(self, 'reconnect', self)); }; inherits(Db, EventEmitter); var define = (Db.define = new Define('Db', Db, false)); // Topology Object.defineProperty(Db.prototype, 'topology', { enumerable: true, get: function() { return this.s.topology; } }); // Options Object.defineProperty(Db.prototype, 'options', { enumerable: true, get: function() { return this.s.options; } }); // slaveOk specified Object.defineProperty(Db.prototype, 'slaveOk', { enumerable: true, get: function() { if ( this.s.options.readPreference != null && (this.s.options.readPreference !== 'primary' || this.s.options.readPreference.mode !== 'primary') ) { return true; } return false; } }); // get the write Concern Object.defineProperty(Db.prototype, 'writeConcern', { enumerable: true, get: function() { var ops = {}; if (this.s.options.w != null) ops.w = this.s.options.w; if (this.s.options.j != null) ops.j = this.s.options.j; if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync; if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; return ops; } }); /** * Ensures provided read preference is properly converted into an object * @param {(ReadPreference|string|object)} readPreference the user provided read preference * @return {ReadPreference} */ const convertReadPreference = function(readPreference) { if (readPreference) { if (typeof readPreference === 'string') { return new ReadPreference(readPreference); } else if ( readPreference && !(readPreference instanceof ReadPreference) && typeof readPreference === 'object' ) { const mode = readPreference.mode || readPreference.preference; if (mode && typeof mode === 'string') { return new ReadPreference(mode, readPreference.tags, { maxStalenessSeconds: readPreference.maxStalenessSeconds }); } } else if (!(readPreference instanceof ReadPreference)) { throw new TypeError('Invalid read preference: ' + readPreference); } } return readPreference; }; /** * The callback format for results * @callback Db~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object} result The result object if the command was executed successfully. */ var executeCommand = function(self, command, options, callback) { // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Get the db name we are executing against var dbName = options.dbName || options.authdb || self.s.databaseName; // If we have a readPreference set if (options.readPreference == null && self.s.readPreference) { options.readPreference = self.s.readPreference; } // Convert the readPreference if its not a write if (options.readPreference) { options.readPreference = convertReadPreference(options.readPreference); } else { options.readPreference = ReadPreference.primary; } // Debug information if (self.s.logger.isDebug()) self.s.logger.debug( f( 'executing command %s against %s with options [%s]', JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)) ) ); // Execute command self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { if (err) return handleCallback(callback, err); if (options.full) return handleCallback(callback, null, result); handleCallback(callback, null, result.result); }); }; /** * Execute a command * @method * @param {object} command The command hash * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.command = function(command, options, callback) { // Change the callback if (typeof options === 'function') (callback = options), (options = {}); // Clone the options options = shallowClone(options); return executeOperation(this.s.topology, executeCommand, [this, command, options, callback]); }; define.classMethod('command', { callback: true, promise: true }); /** * Return the Admin db instance * @method * @return {Admin} return the new Admin db instance */ Db.prototype.admin = function() { return new Admin(this, this.s.topology, this.s.promiseLibrary); }; define.classMethod('admin', { callback: false, promise: false, returns: [Admin] }); /** * The callback format for the collection method, must be used if strict is specified * @callback Db~collectionResultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection} collection The collection instance. */ var collectionKeys = [ 'pkFactory', 'readPreference', 'serializeFunctions', 'strict', 'readConcern', 'ignoreUndefined', 'promoteValues', 'promoteBuffers', 'promoteLongs' ]; /** * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can * can use it without a callback in the following way: `var collection = db.collection('mycollection');` * * @method * @param {string} name the collection name we wish to access. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.strict=false] Returns an error if the collection does not exist * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) * @param {Db~collectionResultCallback} callback The collection result callback * @return {Collection} return the new Collection instance if not in strict mode */ Db.prototype.collection = function(name, options, callback) { var self = this; if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; options = shallowClone(options); // Set the promise library options.promiseLibrary = this.s.promiseLibrary; // If we have not set a collection level readConcern set the db level one options.readConcern = options.readConcern || this.s.readConcern; // Do we have ignoreUndefined set if (this.s.options.ignoreUndefined) { options.ignoreUndefined = this.s.options.ignoreUndefined; } // Merge in all needed options and ensure correct writeConcern merging from db level options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); // Execute if (options == null || !options.strict) { try { var collection = new Collection( this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options ); if (callback) callback(null, collection); return collection; } catch (err) { if (err instanceof MongoError && callback) return callback(err); throw err; } } // Strict mode if (typeof callback !== 'function') { throw toError(f('A callback is required in strict mode. While getting collection %s.', name)); } // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } // Strict mode this.listCollections({ name: name }, options).toArray(function(err, collections) { if (err != null) return handleCallback(callback, err, null); if (collections.length === 0) return handleCallback( callback, toError(f('Collection %s does not exist. Currently in strict mode.', name)), null ); try { return handleCallback( callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options) ); } catch (err) { return handleCallback(callback, err, null); } }); }; define.classMethod('collection', { callback: true, promise: false, returns: [Collection] }); function decorateWithWriteConcern(command, self, options) { // Do we support write concerns 3.4 and higher if (self.s.topology.capabilities().commandsTakeWriteConcern) { // Get the write concern settings var finalOptions = writeConcern(shallowClone(options), self, options); // Add the write concern to the command if (finalOptions.writeConcern) { command.writeConcern = finalOptions.writeConcern; } } } var createCollection = function(self, name, options, callback) { // Get the write concern options var finalOptions = writeConcern(shallowClone(options), self, options); // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } // Check if we have the name self .listCollections({ name: name }, finalOptions) .setReadPreference(ReadPreference.PRIMARY) .toArray(function(err, collections) { if (err != null) return handleCallback(callback, err, null); if (collections.length > 0 && finalOptions.strict) { return handleCallback( callback, MongoError.create({ message: f('Collection %s already exists. Currently in strict mode.', name), driver: true }), null ); } else if (collections.length > 0) { try { return handleCallback( callback, null, new Collection( self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options ) ); } catch (err) { return handleCallback(callback, err); } } // Create collection command var cmd = { create: name }; // Decorate command with writeConcern if supported decorateWithWriteConcern(cmd, self, options); // Add all optional parameters for (var n in options) { if ( options[n] != null && typeof options[n] !== 'function' && illegalCommandFields.indexOf(n) === -1 ) { cmd[n] = options[n]; } } // Force a primary read Preference finalOptions.readPreference = ReadPreference.PRIMARY; // Execute command self.command(cmd, finalOptions, function(err) { if (err) return handleCallback(callback, err); handleCallback( callback, null, new Collection( self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options ) ); }); }); }; /** * Create a new collection on a server with the specified options. Use this to create capped collections. * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ * * @method * @param {string} name the collection name we wish to access. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.strict=false] Returns an error if the collection does not exist * @param {boolean} [options.capped=false] Create a capped collection. * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. * @param {number} [options.size=null] The size of the capped collection in bytes. * @param {number} [options.max=null] The maximum number of documents in the capped collection. * @param {number} [options.flags=null] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. * @param {object} [options.storageEngine=null] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. * @param {object} [options.validator=null] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. * @param {string} [options.validationLevel=null] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. * @param {string} [options.validationAction=null] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. * @param {object} [options.indexOptionDefaults=null] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. * @param {string} [options.viewOn=null] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. * @param {array} [options.pipeline=null] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~collectionResultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.createCollection = function(name, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; return executeOperation(this.s.topology, createCollection, [this, name, options, callback]); }; define.classMethod('createCollection', { callback: true, promise: true }); /** * Get all the db statistics. * * @method * @param {object} [options=null] Optional settings. * @param {number} [options.scale=null] Divide the returned sizes by scale value. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The collection result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.stats = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Build command object var commandObject = { dbStats: true }; // Check if we have the scale value if (options['scale'] != null) commandObject['scale'] = options['scale']; // If we have a readPreference set if (options.readPreference == null && this.s.readPreference) { options.readPreference = this.s.readPreference; } // Execute the command return this.command(commandObject, options, callback); }; define.classMethod('stats', { callback: true, promise: true }); // Transformation methods for cursor results var listCollectionsTranforms = function(databaseName) { var matching = f('%s.', databaseName); return { doc: function(doc) { var index = doc.name.indexOf(matching); // Remove database name if available if (doc.name && index === 0) { doc.name = doc.name.substr(index + matching.length); } return doc; } }; }; /** * Get the list of all collection information for the specified db. * * @method * @param {object} [filter={}] Query to filter collections by * @param {object} [options=null] Optional settings. * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {ClientSession} [options.session] optional session to use for this operation * @return {CommandCursor} */ Db.prototype.listCollections = function(filter, options) { filter = filter || {}; options = options || {}; // Shallow clone the object options = shallowClone(options); // Set the promise library options.promiseLibrary = this.s.promiseLibrary; // Ensure valid readPreference if (options.readPreference) { options.readPreference = convertReadPreference(options.readPreference); } else { options.readPreference = this.s.readPreference || ReadPreference.primary; } // We have a list collections command if (this.serverConfig.capabilities().hasListCollectionsCommand) { // Cursor options var cursor = options.batchSize ? { batchSize: options.batchSize } : {}; // Build the command var command = { listCollections: true, filter: filter, cursor: cursor }; // Set the AggregationCursor constructor options.cursorFactory = CommandCursor; // Create the cursor cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); // Do we have a readPreference, apply it if (options.readPreference) { cursor.setReadPreference(options.readPreference); } // Return the cursor return cursor; } // We cannot use the listCollectionsCommand if (!this.serverConfig.capabilities().hasListCollectionsCommand) { // If we have legacy mode and have not provided a full db name filter it if ( typeof filter.name === 'string' && !new RegExp('^' + this.databaseName + '\\.').test(filter.name) ) { filter = shallowClone(filter); filter.name = f('%s.%s', this.s.databaseName, filter.name); } } // No filter, filter by current database if (filter == null) { filter.name = f('/%s/', this.s.databaseName); } // Rewrite the filter to use $and to filter out indexes if (filter.name) { filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; } else { filter = { name: /^((?!\$).)*$/ }; } // Return options var _options = { transforms: listCollectionsTranforms(this.s.databaseName) }; // Get the cursor cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); // Do we have a readPreference, apply it if (options.readPreference) cursor.setReadPreference(options.readPreference); // Set the passed in batch size if one was provided if (options.batchSize) cursor = cursor.batchSize(options.batchSize); // We have a fallback mode using legacy systems collections return cursor; }; define.classMethod('listCollections', { callback: false, promise: false, returns: [CommandCursor] }); var evaluate = function(self, code, parameters, options, callback) { var finalCode = code; var finalParameters = []; // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // If not a code object translate to one if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); // Ensure the parameters are correct if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { finalParameters = [parameters]; } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { finalParameters = parameters; } // Create execution selector var cmd = { $eval: finalCode, args: finalParameters }; // Check if the nolock parameter is passed in if (options['nolock']) { cmd['nolock'] = options['nolock']; } // Set primary read preference options.readPreference = new ReadPreference(ReadPreference.PRIMARY); // Execute the command self.command(cmd, options, function(err, result) { if (err) return handleCallback(callback, err, null); if (result && result.ok === 1) return handleCallback(callback, null, result.retval); if (result) return handleCallback( callback, MongoError.create({ message: f('eval failed: %s', result.errmsg), driver: true }), null ); handleCallback(callback, err, result); }); }; /** * Evaluate JavaScript on the server * * @method * @param {Code} code JavaScript to execute on server. * @param {(object|array)} parameters The parameters for the call. * @param {object} [options=null] Optional settings. * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The results callback * @deprecated Eval is deprecated on MongoDB 3.2 and forward * @return {Promise} returns Promise if no callback passed */ Db.prototype.eval = function(code, parameters, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; parameters = args.length ? args.shift() : parameters; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, evaluate, [this, code, parameters, options, callback]); }; define.classMethod('eval', { callback: true, promise: true }); /** * Rename a collection. * * @method * @param {string} fromCollection Name of current collection to rename. * @param {string} toCollection New name of of the collection. * @param {object} [options=null] Optional settings. * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~collectionResultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add return new collection options.new_collection = true; const collection = this.collection(fromCollection); return executeOperation(this.s.topology, collection.rename.bind(collection), [ toCollection, options, callback ]); }; define.classMethod('renameCollection', { callback: true, promise: true }); /** * Drop a collection from the database, removing it permanently. New accesses will create a new collection. * * @method * @param {string} name Name of collection to drop * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.dropCollection = function(name, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Command to execute var cmd = { drop: name }; // Decorate with write concern decorateWithWriteConcern(cmd, this, options); // options const opts = Object.assign({}, this.s.options, { readPreference: ReadPreference.PRIMARY }); if (options.session) opts.session = options.session; return executeOperation(this.s.topology, dropCollection, [this, cmd, opts, callback]); }; const dropCollection = (self, cmd, options, callback) => { return self.command(cmd, options, function(err, result) { // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (err) return handleCallback(callback, err); if (result.ok) return handleCallback(callback, null, true); handleCallback(callback, null, false); }); }; define.classMethod('dropCollection', { callback: true, promise: true }); /** * Drop a database, removing it permanently from the server. * * @method * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.dropDatabase = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Drop database command var cmd = { dropDatabase: 1 }; // Decorate with write concern decorateWithWriteConcern(cmd, this, options); // Ensure primary only const finalOptions = Object.assign( {}, { readPreference: ReadPreference.PRIMARY }, this.s.options ); if (options.session) { finalOptions.session = options.session; } return executeOperation(this.s.topology, dropDatabase, [this, cmd, finalOptions, callback]); }; const dropDatabase = (self, cmd, options, callback) => { self.command(cmd, options, function(err, result) { // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (callback == null) return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }; define.classMethod('dropDatabase', { callback: true, promise: true }); /** * Fetch all collections for the current db. * * @method * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~collectionsResultCallback} [callback] The results callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.collections = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, collections, [this, options, callback]); }; var collections = function(self, options, callback) { // Let's get the collection names self.listCollections({}, options).toArray(function(err, documents) { if (err != null) return handleCallback(callback, err, null); // Filter collections removing any illegal ones documents = documents.filter(function(doc) { return doc.name.indexOf('$') === -1; }); // Return the collection objects handleCallback( callback, null, documents.map(function(d) { return new Collection( self, self.s.topology, self.s.databaseName, d.name, self.s.pkFactory, self.s.options ); }) ); }); }; define.classMethod('collections', { callback: true, promise: true }); /** * Runs a command on the database as admin. * @method * @param {object} command The command hash * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.executeDbAdminCommand = function(selector, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Convert read preference if (options.readPreference) { options.readPreference = convertReadPreference(options.readPreference); } return executeOperation(this.s.topology, executeDbAdminCommand, [ this, selector, options, callback ]); }; const executeDbAdminCommand = (self, selector, options, callback) => { self.s.topology.command('admin.$cmd', selector, options, function(err, result) { // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (err) return handleCallback(callback, err); handleCallback(callback, null, result.result); }); }; define.classMethod('executeDbAdminCommand', { callback: true, promise: true }); /** * Creates an index on the db and collection collection. * @method * @param {string} name Name of the collection to create the index on. * @param {(string|object)} fieldOrSpec Defines the index. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.unique=false] Creates an unique index. * @param {boolean} [options.sparse=false] Creates a sparse index. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. * @param {number} [options.v=null] Specify the format version of the indexes. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options ? shallowClone(options) : {}; return executeOperation(this.s.topology, createIndex, [ this, name, fieldOrSpec, options, callback ]); }; var createIndex = function(self, name, fieldOrSpec, options, callback) { // Get the write concern options var finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); finalOptions = writeConcern(finalOptions, self, options); // Ensure we have a callback if (finalOptions.writeConcern && typeof callback !== 'function') { throw MongoError.create({ message: 'Cannot use a writeConcern without a provided callback', driver: true }); } // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Attempt to run using createIndexes command createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { if (err == null) return handleCallback(callback, err, result); // 67 = 'CannotCreateIndex' (malformed index options) // 85 = 'IndexOptionsConflict' (index already exists with different options) // 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) // 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) // These errors mean that the server recognized `createIndex` as a command // and so we don't need to fallback to an insert. if (err.code === 67 || err.code === 11000 || err.code === 85 || err.code === 11600) { return handleCallback(callback, err, result); } // Create command var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); // Set no key checking finalOptions.checkKeys = false; // Insert document self.s.topology.insert( f('%s.%s', self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { if (callback == null) return; if (err) return handleCallback(callback, err); if (result == null) return handleCallback(callback, null, null); if (result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); handleCallback(callback, null, doc.name); } ); }); }; define.classMethod('createIndex', { callback: true, promise: true }); /** * Ensures that an index exists, if it does not it creates it * @method * @deprecated since version 2.0 * @param {string} name The index name * @param {(string|object)} fieldOrSpec Defines the index. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.unique=false] Creates an unique index. * @param {boolean} [options.sparse=false] Creates a sparse index. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. * @param {number} [options.v=null] Specify the format version of the indexes. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, ensureIndex, [ this, name, fieldOrSpec, options, callback ]); }; var ensureIndex = function(self, name, fieldOrSpec, options, callback) { // Get the write concern options var finalOptions = writeConcern({}, self, options); // Create command var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); var index_name = selector.name; // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Merge primary readPreference finalOptions.readPreference = ReadPreference.PRIMARY; // Check if the index allready exists self.indexInformation(name, finalOptions, function(err, indexInformation) { if (err != null && err.code !== 26) return handleCallback(callback, err, null); // If the index does not exist, create it if (indexInformation == null || !indexInformation[index_name]) { self.createIndex(name, fieldOrSpec, options, callback); } else { if (typeof callback === 'function') return handleCallback(callback, null, index_name); } }); }; define.classMethod('ensureIndex', { callback: true, promise: true }); Db.prototype.addChild = function(db) { if (this.s.parentDb) return this.s.parentDb.addChild(db); this.s.children.push(db); }; var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { // Special case where there is no password ($external users) if (typeof username === 'string' && password != null && typeof password === 'object') { options = password; password = null; } // Unpack all options if (typeof options === 'function') { callback = options; options = {}; } // Error out if we digestPassword set if (options.digestPassword != null) { throw toError( "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." ); } // Get additional values var customData = options.customData != null ? options.customData : {}; var roles = Array.isArray(options.roles) ? options.roles : []; var maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; // If not roles defined print deprecated message if (roles.length === 0) { console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); } // Get the error options var commandOptions = { writeCommand: true }; if (options['dbName']) commandOptions.dbName = options['dbName']; // Add maxTimeMS to options if set if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; // Check the db name and add roles if needed if ( (self.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && !Array.isArray(options.roles) ) { roles = ['root']; } else if (!Array.isArray(options.roles)) { roles = ['dbOwner']; } // Build the command to execute var command = { createUser: username, customData: customData, roles: roles, digestPassword: false }; // Apply write concern to command command = writeConcern(command, self, options); // Use node md5 generator var md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ':mongo:' + password); var userPassword = md5.digest('hex'); // No password if (typeof password === 'string') { command.pwd = userPassword; } // Force write using primary commandOptions.readPreference = ReadPreference.primary; // Execute the command self.command(command, commandOptions, function(err, result) { if (err && err.ok === 0 && err.code === undefined) return handleCallback(callback, { code: -5000 }, null); if (err) return handleCallback(callback, err, null); handleCallback( callback, !result.ok ? toError(result) : null, result.ok ? [{ user: username, pwd: '' }] : null ); }); }; var addUser = function(self, username, password, options, callback) { // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Attempt to execute auth command _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { // We need to perform the backward compatible insert operation if (err && err.code === -5000) { var finalOptions = writeConcern(shallowClone(options), self, options); // Use node md5 generator var md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ':mongo:' + password); var userPassword = md5.digest('hex'); // If we have another db set var db = options.dbName ? new Db(options.dbName, self.s.topology, self.s.options) : self; // Fetch a user collection var collection = db.collection(Db.SYSTEM_USER_COLLECTION); // Check if we are inserting the first user collection.count({}, finalOptions, function(err, count) { // We got an error (f.ex not authorized) if (err != null) return handleCallback(callback, err, null); // Check if the user exists and update i collection .find({ user: username }, { dbName: options['dbName'] }, finalOptions) .toArray(function(err) { // We got an error (f.ex not authorized) if (err != null) return handleCallback(callback, err, null); // Add command keys finalOptions.upsert = true; // We have a user, let's update the password or upsert if not collection.update( { user: username }, { $set: { user: username, pwd: userPassword } }, finalOptions, function(err) { if (count === 0 && err) return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, [{ user: username, pwd: userPassword }]); } ); }); }); return; } if (err) return handleCallback(callback, err); handleCallback(callback, err, r); }); }; /** * Add a user to the database. * @method * @param {string} username The username. * @param {string} password The password. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.addUser = function(username, password, options, callback) { // Unpack the parameters var args = Array.prototype.slice.call(arguments, 2); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, addUser, [this, username, password, options, callback]); }; define.classMethod('addUser', { callback: true, promise: true }); var _executeAuthRemoveUserCommand = function(self, username, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Get the error options var commandOptions = { writeCommand: true }; if (options['dbName']) commandOptions.dbName = options['dbName']; // Get additional values var maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; // Add maxTimeMS to options if set if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; // Build the command to execute var command = { dropUser: username }; // Apply write concern to command command = writeConcern(command, self, options); // Force write using primary commandOptions.readPreference = ReadPreference.primary; // Execute the command self.command(command, commandOptions, function(err, result) { if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }; var removeUser = function(self, username, options, callback) { // Attempt to execute command _executeAuthRemoveUserCommand(self, username, options, function(err, result) { if (err && err.code === -5000) { var finalOptions = writeConcern(shallowClone(options), self, options); // If we have another db set var db = options.dbName ? new Db(options.dbName, self.s.topology, self.s.options) : self; // Fetch a user collection var collection = db.collection(Db.SYSTEM_USER_COLLECTION); // Locate the user collection.findOne({ user: username }, finalOptions, function(err, user) { if (user == null) return handleCallback(callback, err, false); collection.remove({ user: username }, finalOptions, function(err) { handleCallback(callback, err, true); }); }); return; } if (err) return handleCallback(callback, err); handleCallback(callback, err, result); }); }; define.classMethod('removeUser', { callback: true, promise: true }); /** * Remove a user from a database * @method * @param {string} username The username. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.removeUser = function(username, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() || {} : {}; return executeOperation(this.s.topology, removeUser, [this, username, options, callback]); }; /** * Set the current profiling level of MongoDB * * @param {string} level The new profiling level (off, slow_only, all). * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback. * @return {Promise} returns Promise if no callback passed */ Db.prototype.setProfilingLevel = function(level, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, setProfilingLevel, [this, level, options, callback]); }; var setProfilingLevel = function(self, level, options, callback) { var command = {}; var profile = 0; if (level === 'off') { profile = 0; } else if (level === 'slow_only') { profile = 1; } else if (level === 'all') { profile = 2; } else { return callback(new Error('Error: illegal profiling level value ' + level)); } // Set up the profile number command['profile'] = profile; self.command(command, options, function(err, doc) { if (err == null && doc.ok === 1) return callback(null, level); return err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); }); }; define.classMethod('setProfilingLevel', { callback: true, promise: true }); /** * Retrive the current profiling information for MongoDB * * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback. * @return {Promise} returns Promise if no callback passed * @deprecated Query the system.profile collection directly. */ Db.prototype.profilingInfo = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, profilingInfo, [this, options, callback]); }; var profilingInfo = function(self, options, callback) { try { self .collection('system.profile') .find({}, null, options) .toArray(callback); } catch (err) { return callback(err, null); } }; define.classMethod('profilingInfo', { callback: true, promise: true }); /** * Retrieve the current profiling Level for MongoDB * * @param {Object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.profilingLevel = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, profilingLevel, [this, options, callback]); }; var profilingLevel = function(self, options, callback) { self.command({ profile: -1 }, options, function(err, doc) { if (err == null && doc.ok === 1) { var was = doc.was; if (was === 0) return callback(null, 'off'); if (was === 1) return callback(null, 'slow_only'); if (was === 2) return callback(null, 'all'); return callback(new Error('Error: illegal profiling level value ' + was), null); } else { err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); } }); }; define.classMethod('profilingLevel', { callback: true, promise: true }); /** * Retrieves this collections index info. * @method * @param {string} name The name of the collection. * @param {object} [options=null] Optional settings. * @param {boolean} [options.full=false] Returns the full raw index information. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {ClientSession} [options.session] optional session to use for this operation * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Db.prototype.indexInformation = function(name, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.s.topology, indexInformation, [this, name, options, callback]); }; var indexInformation = function(self, name, options, callback) { // If we specified full information var full = options['full'] == null ? false : options['full']; // Did the user destroy the topology if (self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Process all the results from the index command and collection var processResults = function(indexes) { // Contains all the information var info = {}; // Process all the indexes for (var i = 0; i < indexes.length; i++) { var index = indexes[i]; // Let's unpack the object info[index.name] = []; for (var name in index.key) { info[index.name].push([name, index.key[name]]); } } return info; }; // Get the list of indexes of the specified collection self .collection(name) .listIndexes(options) .toArray(function(err, indexes) { if (err) return callback(toError(err)); if (!Array.isArray(indexes)) return handleCallback(callback, null, []); if (full) return handleCallback(callback, null, indexes); handleCallback(callback, null, processResults(indexes)); }); }; define.classMethod('indexInformation', { callback: true, promise: true }); var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { var indexParameters = parseIndexOptions(fieldOrSpec); var fieldHash = indexParameters.fieldHash; // Generate the index name var indexName = typeof options.name === 'string' ? options.name : indexParameters.name; var selector = { ns: db.databaseName + '.' + name, key: fieldHash, name: indexName }; // Ensure we have a correct finalUnique var finalUnique = options == null || 'object' === typeof options ? false : options; // Set up options options = options == null || typeof options === 'boolean' ? {} : options; // Add all the options var keysToOmit = Object.keys(selector); for (var optionName in options) { if (keysToOmit.indexOf(optionName) === -1) { selector[optionName] = options[optionName]; } } if (selector['unique'] == null) selector['unique'] = finalUnique; // Remove any write concern operations var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; for (var i = 0; i < removeKeys.length; i++) { delete selector[removeKeys[i]]; } // Return the command creation selector return selector; }; var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { // Build the index var indexParameters = parseIndexOptions(fieldOrSpec); // Generate the index name var indexName = typeof options.name === 'string' ? options.name : indexParameters.name; // Set up the index var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; // merge all the options var keysToOmit = Object.keys(indexes[0]).concat([ 'w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session' ]); for (var optionName in options) { if (keysToOmit.indexOf(optionName) === -1) { indexes[0][optionName] = options[optionName]; } } // Get capabilities var capabilities = self.s.topology.capabilities(); // Did the user pass in a collation, check if our write server supports it if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { // Create a new error var error = new MongoError(f('server/primary/mongos does not support collation')); error.code = 67; // Return the error return callback(error); } // Create command, apply write concern to command var cmd = writeConcern({ createIndexes: name, indexes: indexes }, self, options); // Decorate command with writeConcern if supported decorateWithWriteConcern(cmd, self, options); // ReadPreference primary options.readPreference = ReadPreference.PRIMARY; // Build the command self.command(cmd, options, function(err, result) { if (err) return handleCallback(callback, err, null); if (result.ok === 0) return handleCallback(callback, toError(result), null); // Return the indexName for backward compatibility handleCallback(callback, null, indexName); }); }; // Validate the database name var validateDatabaseName = function(databaseName) { if (typeof databaseName !== 'string') throw MongoError.create({ message: 'database name must be a string', driver: true }); if (databaseName.length === 0) throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); if (databaseName === '$external') return; var invalidChars = [' ', '.', '$', '/', '\\']; for (var i = 0; i < invalidChars.length; i++) { if (databaseName.indexOf(invalidChars[i]) !== -1) throw MongoError.create({ message: "database names cannot contain the character '" + invalidChars[i] + "'", driver: true }); } }; // Get write concern var writeConcern = function(target, db, options) { if (options.w != null || options.j != null || options.fsync != null) { var opts = {}; if (options.w) opts.w = options.w; if (options.wtimeout) opts.wtimeout = options.wtimeout; if (options.j) opts.j = options.j; if (options.fsync) opts.fsync = options.fsync; target.writeConcern = opts; } else if ( db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null ) { target.writeConcern = db.writeConcern; } return target; }; // Add listeners to topology var createListener = function(self, e, object) { var listener = function(err) { if (object.listeners(e).length > 0) { object.emit(e, err, self); // Emit on all associated db's if available for (var i = 0; i < self.s.children.length; i++) { self.s.children[i].emit(e, err, self.s.children[i]); } } }; return listener; }; /** * Unref all sockets * @method */ Db.prototype.unref = function() { this.s.topology.unref(); }; /** * Db close event * * Emitted after a socket closed against a single server or mongos proxy. * * @event Db#close * @type {MongoError} */ /** * Db reconnect event * * * Server: Emitted when the driver has reconnected and re-authenticated. * * ReplicaSet: N/A * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. * * @event Db#reconnect * @type {object} */ /** * Db error event * * Emitted after an error occurred against a single server or mongos proxy. * * @event Db#error * @type {MongoError} */ /** * Db timeout event * * Emitted after a socket timeout occurred against a single server or mongos proxy. * * @event Db#timeout * @type {MongoError} */ /** * Db parseError event * * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. * * @event Db#parseError * @type {MongoError} */ /** * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. * * * Server: Emitted when the driver has connected to the single server and has authenticated. * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. * * @event Db#fullsetup * @type {Db} */ // Constants Db.SYSTEM_NAMESPACE_COLLECTION = 'system.namespaces'; Db.SYSTEM_INDEX_COLLECTION = 'system.indexes'; Db.SYSTEM_PROFILE_COLLECTION = 'system.profile'; Db.SYSTEM_USER_COLLECTION = 'system.users'; Db.SYSTEM_COMMAND_COLLECTION = '$cmd'; Db.SYSTEM_JS_COLLECTION = 'system.js'; module.exports = Db; },{"./admin":375,"./collection":383,"./command_cursor":384,"./metadata":392,"./utils":399,"crypto":287,"events":316,"mongodb-core":345,"util":563}],387:[function(require,module,exports){ (function (Buffer){ 'use strict'; var stream = require('stream'), util = require('util'); module.exports = GridFSBucketReadStream; /** * A readable stream that enables you to read buffers from GridFS. * * Do not instantiate this class directly. Use `openDownloadStream()` instead. * * @class * @param {Collection} chunks Handle for chunks collection * @param {Collection} files Handle for files collection * @param {Object} readPreference The read preference to use * @param {Object} filter The query to use to find the file document * @param {Object} [options=null] Optional settings. * @param {Number} [options.sort=null] Optional sort for the file find query * @param {Number} [options.skip=null] Optional skip for the file find query * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before * @fires GridFSBucketReadStream#error * @fires GridFSBucketReadStream#file * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. */ function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { this.s = { bytesRead: 0, chunks: chunks, cursor: null, expected: 0, files: files, filter: filter, init: false, expectedEnd: 0, file: null, options: options, readPreference: readPreference }; stream.Readable.call(this); } util.inherits(GridFSBucketReadStream, stream.Readable); /** * An error occurred * * @event GridFSBucketReadStream#error * @type {Error} */ /** * Fires when the stream loaded the file document corresponding to the * provided id. * * @event GridFSBucketReadStream#file * @type {object} */ /** * Emitted when a chunk of data is available to be consumed. * * @event GridFSBucketReadStream#data * @type {object} */ /** * Fired when the stream is exhausted (no more data events). * * @event GridFSBucketReadStream#end * @type {object} */ /** * Fired when the stream is exhausted and the underlying cursor is killed * * @event GridFSBucketReadStream#close * @type {object} */ /** * Reads from the cursor and pushes to the stream. * @method */ GridFSBucketReadStream.prototype._read = function() { var _this = this; if (this.destroyed) { return; } waitForFile(_this, function() { doRead(_this); }); }; /** * Sets the 0-based offset in bytes to start streaming from. Throws * an error if this stream has entered flowing mode * (e.g. if you've already called `on('data')`) * @method * @param {Number} start Offset in bytes to start reading at * @return {GridFSBucketReadStream} */ GridFSBucketReadStream.prototype.start = function(start) { throwIfInitialized(this); this.s.options.start = start; return this; }; /** * Sets the 0-based offset in bytes to start streaming from. Throws * an error if this stream has entered flowing mode * (e.g. if you've already called `on('data')`) * @method * @param {Number} end Offset in bytes to stop reading at * @return {GridFSBucketReadStream} */ GridFSBucketReadStream.prototype.end = function(end) { throwIfInitialized(this); this.s.options.end = end; return this; }; /** * Marks this stream as aborted (will never push another `data` event) * and kills the underlying cursor. Will emit the 'end' event, and then * the 'close' event once the cursor is successfully killed. * * @method * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. * @fires GridFSBucketWriteStream#close * @fires GridFSBucketWriteStream#end */ GridFSBucketReadStream.prototype.abort = function(callback) { var _this = this; this.push(null); this.destroyed = true; if (this.s.cursor) { this.s.cursor.close(function(error) { _this.emit('close'); callback && callback(error); }); } else { if (!this.s.init) { // If not initialized, fire close event because we will never // get a cursor _this.emit('close'); } callback && callback(); } }; /** * @ignore */ function throwIfInitialized(self) { if (self.s.init) { throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); } } /** * @ignore */ function doRead(_this) { if (_this.destroyed) { return; } _this.s.cursor.next(function(error, doc) { if (_this.destroyed) { return; } if (error) { return __handleError(_this, error); } if (!doc) { _this.push(null); return _this.s.cursor.close(function(error) { if (error) { return __handleError(_this, error); } _this.emit('close'); }); } var bytesRemaining = _this.s.file.length - _this.s.bytesRead; var expectedN = _this.s.expected++; var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); if (doc.n > expectedN) { var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; return __handleError(_this, new Error(errmsg)); } if (doc.n < expectedN) { errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; return __handleError(_this, new Error(errmsg)); } var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; if (buf.length !== expectedLength) { if (bytesRemaining <= 0) { errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; return __handleError(_this, new Error(errmsg)); } errmsg = 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; return __handleError(_this, new Error(errmsg)); } _this.s.bytesRead += buf.length; if (buf.length === 0) { return _this.push(null); } var sliceStart = null; var sliceEnd = null; if (_this.s.bytesToSkip != null) { sliceStart = _this.s.bytesToSkip; _this.s.bytesToSkip = 0; } if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { sliceEnd = _this.s.bytesToTrim; } // If the remaining amount of data left is < chunkSize read the right amount of data if (_this.s.options.end && _this.s.options.end - _this.s.bytesToSkip < buf.length) { sliceEnd = _this.s.options.end - _this.s.bytesToSkip; } if (sliceStart != null || sliceEnd != null) { buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); } _this.push(buf); }); } /** * @ignore */ function init(self) { var findOneOptions = {}; if (self.s.readPreference) { findOneOptions.readPreference = self.s.readPreference; } if (self.s.options && self.s.options.sort) { findOneOptions.sort = self.s.options.sort; } if (self.s.options && self.s.options.skip) { findOneOptions.skip = self.s.options.skip; } self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { if (error) { return __handleError(self, error); } if (!doc) { var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; var err = new Error(errmsg); err.code = 'ENOENT'; return __handleError(self, err); } // If document is empty, kill the stream immediately and don't // execute any reads if (doc.length <= 0) { self.push(null); return; } if (self.destroyed) { // If user destroys the stream before we have a cursor, wait // until the query is done to say we're 'closed' because we can't // cancel a query. self.emit('close'); return; } self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); var filter = { files_id: doc._id }; // Currently (MongoDB 3.4.4) skip function does not support the index, // it needs to retrieve all the documents first and then skip them. (CS-25811) // As work around we use $gte on the "n" field. if (self.s.options && self.s.options.start != null) { var skip = Math.floor(self.s.options.start / doc.chunkSize); if (skip > 0) { filter['n'] = { $gte: skip }; } } self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); if (self.s.readPreference) { self.s.cursor.setReadPreference(self.s.readPreference); } self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); self.s.file = doc; self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); self.emit('file', doc); }); } /** * @ignore */ function waitForFile(_this, callback) { if (_this.s.file) { return callback(); } if (!_this.s.init) { init(_this); _this.s.init = true; } _this.once('file', function() { callback(); }); } /** * @ignore */ function handleStartOption(stream, doc, options) { if (options && options.start != null) { if (options.start > doc.length) { throw new Error( 'Stream start (' + options.start + ') must not be ' + 'more than the length of the file (' + doc.length + ')' ); } if (options.start < 0) { throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); } if (options.end != null && options.end < options.start) { throw new Error( 'Stream start (' + options.start + ') must not be ' + 'greater than stream end (' + options.end + ')' ); } stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; stream.s.expected = Math.floor(options.start / doc.chunkSize); return options.start - stream.s.bytesRead; } } /** * @ignore */ function handleEndOption(stream, doc, cursor, options) { if (options && options.end != null) { if (options.end > doc.length) { throw new Error( 'Stream end (' + options.end + ') must not be ' + 'more than the length of the file (' + doc.length + ')' ); } if (options.start < 0) { throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); } var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; } } /** * @ignore */ function __handleError(_this, error) { _this.emit('error', error); } }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":335,"stream":548,"util":563}],388:[function(require,module,exports){ 'use strict'; var Emitter = require('events').EventEmitter; var GridFSBucketReadStream = require('./download'); var GridFSBucketWriteStream = require('./upload'); var shallowClone = require('../utils').shallowClone; var toError = require('../utils').toError; var util = require('util'); var executeOperation = require('../utils').executeOperation; var DEFAULT_GRIDFS_BUCKET_OPTIONS = { bucketName: 'fs', chunkSizeBytes: 255 * 1024 }; module.exports = GridFSBucket; /** * Constructor for a streaming GridFS interface * @class * @param {Db} db A db handle * @param {object} [options=null] Optional settings. * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB * @param {object} [options.writeConcern=null] Optional write concern to be passed to write operations, for instance `{ w: 1 }` * @param {object} [options.readPreference=null] Optional read preference to be passed to read operations * @fires GridFSBucketWriteStream#index * @return {GridFSBucket} */ function GridFSBucket(db, options) { Emitter.apply(this); this.setMaxListeners(0); if (options && typeof options === 'object') { options = shallowClone(options); var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); for (var i = 0; i < keys.length; ++i) { if (!options[keys[i]]) { options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; } } } else { options = DEFAULT_GRIDFS_BUCKET_OPTIONS; } this.s = { db: db, options: options, _chunksCollection: db.collection(options.bucketName + '.chunks'), _filesCollection: db.collection(options.bucketName + '.files'), checkedIndexes: false, calledOpenUploadStream: false, promiseLibrary: db.s.promiseLibrary || Promise }; } util.inherits(GridFSBucket, Emitter); /** * When the first call to openUploadStream is made, the upload stream will * check to see if it needs to create the proper indexes on the chunks and * files collections. This event is fired either when 1) it determines that * no index creation is necessary, 2) when it successfully creates the * necessary indexes. * * @event GridFSBucket#index * @type {Error} */ /** * Returns a writable stream (GridFSBucketWriteStream) for writing * buffers to GridFS. The stream's 'id' property contains the resulting * file's id. * @method * @param {string} filename The value of the 'filename' key in the files doc * @param {object} [options=null] Optional settings. * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field * @return {GridFSBucketWriteStream} */ GridFSBucket.prototype.openUploadStream = function(filename, options) { if (options) { options = shallowClone(options); } else { options = {}; } if (!options.chunkSizeBytes) { options.chunkSizeBytes = this.s.options.chunkSizeBytes; } return new GridFSBucketWriteStream(this, filename, options); }; /** * Returns a writable stream (GridFSBucketWriteStream) for writing * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting * file's id. * @method * @param {string|number|object} id A custom id used to identify the file * @param {string} filename The value of the 'filename' key in the files doc * @param {object} [options=null] Optional settings. * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field * @return {GridFSBucketWriteStream} */ GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { if (options) { options = shallowClone(options); } else { options = {}; } if (!options.chunkSizeBytes) { options.chunkSizeBytes = this.s.options.chunkSizeBytes; } options.id = id; return new GridFSBucketWriteStream(this, filename, options); }; /** * Returns a readable stream (GridFSBucketReadStream) for streaming file * data from GridFS. * @method * @param {ObjectId} id The id of the file doc * @param {Object} [options=null] Optional settings. * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before * @return {GridFSBucketReadStream} */ GridFSBucket.prototype.openDownloadStream = function(id, options) { var filter = { _id: id }; options = { start: options && options.start, end: options && options.end }; return new GridFSBucketReadStream( this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, filter, options ); }; /** * Deletes a file with the given id * @method * @param {ObjectId} id The id of the file doc * @param {GridFSBucket~errorCallback} [callback] */ GridFSBucket.prototype.delete = function(id, callback) { return executeOperation(this.s.db.s.topology, _delete, [this, id, callback], { skipSessions: true }); }; /** * @ignore */ function _delete(_this, id, callback) { _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { if (error) { return callback(error); } _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { if (error) { return callback(error); } // Delete orphaned chunks before returning FileNotFound if (!res.result.n) { var errmsg = 'FileNotFound: no file with id ' + id + ' found'; return callback(new Error(errmsg)); } callback(); }); }); } /** * Convenience wrapper around find on the files collection * @method * @param {Object} filter * @param {Object} [options=null] Optional settings for cursor * @param {number} [options.batchSize=null] Optional batch size for cursor * @param {number} [options.limit=null] Optional limit for cursor * @param {number} [options.maxTimeMS=null] Optional maxTimeMS for cursor * @param {boolean} [options.noCursorTimeout=null] Optionally set cursor's `noCursorTimeout` flag * @param {number} [options.skip=null] Optional skip for cursor * @param {object} [options.sort=null] Optional sort for cursor * @return {Cursor} */ GridFSBucket.prototype.find = function(filter, options) { filter = filter || {}; options = options || {}; var cursor = this.s._filesCollection.find(filter); if (options.batchSize != null) { cursor.batchSize(options.batchSize); } if (options.limit != null) { cursor.limit(options.limit); } if (options.maxTimeMS != null) { cursor.maxTimeMS(options.maxTimeMS); } if (options.noCursorTimeout != null) { cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); } if (options.skip != null) { cursor.skip(options.skip); } if (options.sort != null) { cursor.sort(options.sort); } return cursor; }; /** * Returns a readable stream (GridFSBucketReadStream) for streaming the * file with the given name from GridFS. If there are multiple files with * the same name, this will stream the most recent file with the given name * (as determined by the `uploadDate` field). You can set the `revision` * option to change this behavior. * @method * @param {String} filename The name of the file to stream * @param {Object} [options=null] Optional settings * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before * @return {GridFSBucketReadStream} */ GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { var sort = { uploadDate: -1 }; var skip = null; if (options && options.revision != null) { if (options.revision >= 0) { sort = { uploadDate: 1 }; skip = options.revision; } else { skip = -options.revision - 1; } } var filter = { filename: filename }; options = { sort: sort, skip: skip, start: options && options.start, end: options && options.end }; return new GridFSBucketReadStream( this.s._chunksCollection, this.s._filesCollection, this.s.options.readPreference, filter, options ); }; /** * Renames the file with the given _id to the given string * @method * @param {ObjectId} id the id of the file to rename * @param {String} filename new name for the file * @param {GridFSBucket~errorCallback} [callback] */ GridFSBucket.prototype.rename = function(id, filename, callback) { return executeOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { skipSessions: true }); }; /** * @ignore */ function _rename(_this, id, filename, callback) { var filter = { _id: id }; var update = { $set: { filename: filename } }; _this.s._filesCollection.updateOne(filter, update, function(error, res) { if (error) { return callback(error); } if (!res.result.n) { return callback(toError('File with id ' + id + ' not found')); } callback(); }); } /** * Removes this bucket's files collection, followed by its chunks collection. * @method * @param {GridFSBucket~errorCallback} [callback] */ GridFSBucket.prototype.drop = function(callback) { return executeOperation(this.s.db.s.topology, _drop, [this, callback], { skipSessions: true }); }; /** * @ignore */ function _drop(_this, callback) { _this.s._filesCollection.drop(function(error) { if (error) { return callback(error); } _this.s._chunksCollection.drop(function(error) { if (error) { return callback(error); } return callback(); }); }); } /** * Callback format for all GridFSBucket methods that can accept a callback. * @callback GridFSBucket~errorCallback * @param {MongoError} error An error instance representing any errors that occurred */ },{"../utils":399,"./download":387,"./upload":389,"events":316,"util":563}],389:[function(require,module,exports){ (function (Buffer){ 'use strict'; var core = require('mongodb-core'); var crypto = require('crypto'); var stream = require('stream'); var util = require('util'); var ERROR_NAMESPACE_NOT_FOUND = 26; module.exports = GridFSBucketWriteStream; /** * A writable stream that enables you to write buffers to GridFS. * * Do not instantiate this class directly. Use `openUploadStream()` instead. * * @class * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket * @param {string} filename The value of the 'filename' key in the files doc * @param {object} [options=null] Optional settings. * @param {string|number|object} [options.id=null] Custom file id for the GridFS file. * @param {number} [options.chunkSizeBytes=null] The chunk size to use, in bytes * @param {number} [options.w=null] The write concern * @param {number} [options.wtimeout=null] The write concern timeout * @param {number} [options.j=null] The journal write concern * @fires GridFSBucketWriteStream#error * @fires GridFSBucketWriteStream#finish * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. */ function GridFSBucketWriteStream(bucket, filename, options) { options = options || {}; this.bucket = bucket; this.chunks = bucket.s._chunksCollection; this.filename = filename; this.files = bucket.s._filesCollection; this.options = options; // Signals the write is all done this.done = false; this.id = options.id ? options.id : core.BSON.ObjectId(); this.chunkSizeBytes = this.options.chunkSizeBytes; this.bufToStore = new Buffer(this.chunkSizeBytes); this.length = 0; this.md5 = crypto.createHash('md5'); this.n = 0; this.pos = 0; this.state = { streamEnd: false, outstandingRequests: 0, errored: false, aborted: false, promiseLibrary: this.bucket.s.promiseLibrary }; if (!this.bucket.s.calledOpenUploadStream) { this.bucket.s.calledOpenUploadStream = true; var _this = this; checkIndexes(this, function() { _this.bucket.s.checkedIndexes = true; _this.bucket.emit('index'); }); } } util.inherits(GridFSBucketWriteStream, stream.Writable); /** * An error occurred * * @event GridFSBucketWriteStream#error * @type {Error} */ /** * `end()` was called and the write stream successfully wrote the file * metadata and all the chunks to MongoDB. * * @event GridFSBucketWriteStream#finish * @type {object} */ /** * Write a buffer to the stream. * * @method * @param {Buffer} chunk Buffer to write * @param {String} encoding Optional encoding for the buffer * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. */ GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { var _this = this; return waitForIndexes(this, function() { return doWrite(_this, chunk, encoding, callback); }); }; /** * Places this write stream into an aborted state (all future writes fail) * and deletes all chunks that have already been written. * * @method * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred * @return {Promise} if no callback specified */ GridFSBucketWriteStream.prototype.abort = function(callback) { if (this.state.streamEnd) { var error = new Error('Cannot abort a stream that has already completed'); if (typeof callback === 'function') { return callback(error); } return this.state.promiseLibrary.reject(error); } if (this.state.aborted) { error = new Error('Cannot call abort() on a stream twice'); if (typeof callback === 'function') { return callback(error); } return this.state.promiseLibrary.reject(error); } this.state.aborted = true; this.chunks.deleteMany({ files_id: this.id }, function(error) { if (typeof callback === 'function') callback(error); }); }; /** * Tells the stream that no more data will be coming in. The stream will * persist the remaining data to MongoDB, write the files document, and * then emit a 'finish' event. * * @method * @param {Buffer} chunk Buffer to write * @param {String} encoding Optional encoding for the buffer * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB */ GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { var _this = this; if (typeof chunk === 'function') { (callback = chunk), (chunk = null), (encoding = null); } else if (typeof encoding === 'function') { (callback = encoding), (encoding = null); } if (checkAborted(this, callback)) { return; } this.state.streamEnd = true; if (callback) { this.once('finish', function(result) { callback(null, result); }); } if (!chunk) { waitForIndexes(this, function() { writeRemnant(_this); }); return; } this.write(chunk, encoding, function() { writeRemnant(_this); }); }; /** * @ignore */ function __handleError(_this, error, callback) { if (_this.state.errored) { return; } _this.state.errored = true; if (callback) { return callback(error); } _this.emit('error', error); } /** * @ignore */ function createChunkDoc(filesId, n, data) { return { _id: core.BSON.ObjectId(), files_id: filesId, n: n, data: data }; } /** * @ignore */ function checkChunksIndex(_this, callback) { _this.chunks.listIndexes().toArray(function(error, indexes) { if (error) { // Collection doesn't exist so create index if (error.code === ERROR_NAMESPACE_NOT_FOUND) { var index = { files_id: 1, n: 1 }; _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { if (error) { return callback(error); } callback(); }); return; } return callback(error); } var hasChunksIndex = false; indexes.forEach(function(index) { if (index.key) { var keys = Object.keys(index.key); if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { hasChunksIndex = true; } } }); if (hasChunksIndex) { callback(); } else { index = { files_id: 1, n: 1 }; var indexOptions = getWriteOptions(_this); indexOptions.background = false; indexOptions.unique = true; _this.chunks.createIndex(index, indexOptions, function(error) { if (error) { return callback(error); } callback(); }); } }); } /** * @ignore */ function checkDone(_this, callback) { if (_this.done) return true; if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { // Set done so we dont' trigger duplicate createFilesDoc _this.done = true; // Create a new files doc var filesDoc = createFilesDoc( _this.id, _this.length, _this.chunkSizeBytes, _this.md5.digest('hex'), _this.filename, _this.options.contentType, _this.options.aliases, _this.options.metadata ); if (checkAborted(_this, callback)) { return false; } _this.files.insert(filesDoc, getWriteOptions(_this), function(error) { if (error) { return __handleError(_this, error, callback); } _this.emit('finish', filesDoc); }); return true; } return false; } /** * @ignore */ function checkIndexes(_this, callback) { _this.files.findOne({}, { _id: 1 }, function(error, doc) { if (error) { return callback(error); } if (doc) { return callback(); } _this.files.listIndexes().toArray(function(error, indexes) { if (error) { // Collection doesn't exist so create index if (error.code === ERROR_NAMESPACE_NOT_FOUND) { var index = { filename: 1, uploadDate: 1 }; _this.files.createIndex(index, { background: false }, function(error) { if (error) { return callback(error); } checkChunksIndex(_this, callback); }); return; } return callback(error); } var hasFileIndex = false; indexes.forEach(function(index) { var keys = Object.keys(index.key); if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { hasFileIndex = true; } }); if (hasFileIndex) { checkChunksIndex(_this, callback); } else { index = { filename: 1, uploadDate: 1 }; var indexOptions = getWriteOptions(_this); indexOptions.background = false; _this.files.createIndex(index, indexOptions, function(error) { if (error) { return callback(error); } checkChunksIndex(_this, callback); }); } }); }); } /** * @ignore */ function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { var ret = { _id: _id, length: length, chunkSize: chunkSize, uploadDate: new Date(), md5: md5, filename: filename }; if (contentType) { ret.contentType = contentType; } if (aliases) { ret.aliases = aliases; } if (metadata) { ret.metadata = metadata; } return ret; } /** * @ignore */ function doWrite(_this, chunk, encoding, callback) { if (checkAborted(_this, callback)) { return false; } var inputBuf = Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk, encoding); _this.length += inputBuf.length; // Input is small enough to fit in our buffer if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { inputBuf.copy(_this.bufToStore, _this.pos); _this.pos += inputBuf.length; callback && callback(); // Note that we reverse the typical semantics of write's return value // to be compatible with node's `.pipe()` function. // True means client can keep writing. return true; } // Otherwise, buffer is too big for current chunk, so we need to flush // to MongoDB. var inputBufRemaining = inputBuf.length; var spaceRemaining = _this.chunkSizeBytes - _this.pos; var numToCopy = Math.min(spaceRemaining, inputBuf.length); var outstandingRequests = 0; while (inputBufRemaining > 0) { var inputBufPos = inputBuf.length - inputBufRemaining; inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); _this.pos += numToCopy; spaceRemaining -= numToCopy; if (spaceRemaining === 0) { _this.md5.update(_this.bufToStore); var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); ++_this.state.outstandingRequests; ++outstandingRequests; if (checkAborted(_this, callback)) { return false; } _this.chunks.insert(doc, getWriteOptions(_this), function(error) { if (error) { return __handleError(_this, error); } --_this.state.outstandingRequests; --outstandingRequests; if (!outstandingRequests) { _this.emit('drain', doc); callback && callback(); checkDone(_this); } }); spaceRemaining = _this.chunkSizeBytes; _this.pos = 0; ++_this.n; } inputBufRemaining -= numToCopy; numToCopy = Math.min(spaceRemaining, inputBufRemaining); } // Note that we reverse the typical semantics of write's return value // to be compatible with node's `.pipe()` function. // False means the client should wait for the 'drain' event. return false; } /** * @ignore */ function getWriteOptions(_this) { var obj = {}; if (_this.options.writeConcern) { obj.w = _this.options.writeConcern.w; obj.wtimeout = _this.options.writeConcern.wtimeout; obj.j = _this.options.writeConcern.j; } return obj; } /** * @ignore */ function waitForIndexes(_this, callback) { if (_this.bucket.s.checkedIndexes) { return callback(false); } _this.bucket.once('index', function() { callback(true); }); return true; } /** * @ignore */ function writeRemnant(_this, callback) { // Buffer is empty, so don't bother to insert if (_this.pos === 0) { return checkDone(_this, callback); } ++_this.state.outstandingRequests; // Create a new buffer to make sure the buffer isn't bigger than it needs // to be. var remnant = new Buffer(_this.pos); _this.bufToStore.copy(remnant, 0, 0, _this.pos); _this.md5.update(remnant); var doc = createChunkDoc(_this.id, _this.n, remnant); // If the stream was aborted, do not write remnant if (checkAborted(_this, callback)) { return false; } _this.chunks.insert(doc, getWriteOptions(_this), function(error) { if (error) { return __handleError(_this, error); } --_this.state.outstandingRequests; checkDone(_this); }); } /** * @ignore */ function checkAborted(_this, callback) { if (_this.state.aborted) { if (typeof callback === 'function') { callback(new Error('this stream has been aborted')); } return true; } return false; } }).call(this,require("buffer").Buffer) },{"buffer":144,"crypto":287,"mongodb-core":345,"stream":548,"util":563}],390:[function(require,module,exports){ (function (Buffer){ 'use strict'; var Binary = require('mongodb-core').BSON.Binary, ObjectID = require('mongodb-core').BSON.ObjectID; /** * Class for representing a single chunk in GridFS. * * @class * * @param file {GridStore} The {@link GridStore} object holding this chunk. * @param mongoObject {object} The mongo object representation of this chunk. * * @throws Error when the type of data field for {@link mongoObject} is not * supported. Currently supported types for data field are instances of * {@link String}, {@link Array}, {@link Binary} and {@link Binary} * from the bson module * * @see Chunk#buildMongoObject */ var Chunk = function(file, mongoObject, writeConcern) { if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); this.file = file; var mongoObjectFinal = mongoObject == null ? {} : mongoObject; this.writeConcern = writeConcern || { w: 1 }; this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; this.data = new Binary(); if (typeof mongoObjectFinal.data === 'string') { var buffer = new Buffer(mongoObjectFinal.data.length); buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); this.data = new Binary(buffer); } else if (Array.isArray(mongoObjectFinal.data)) { buffer = new Buffer(mongoObjectFinal.data.length); var data = mongoObjectFinal.data.join(''); buffer.write(data, 0, data.length, 'binary'); this.data = new Binary(buffer); } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { this.data = mongoObjectFinal.data; } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { throw Error('Illegal chunk format'); } // Update position this.internalPosition = 0; }; /** * Writes a data to this object and advance the read/write head. * * @param data {string} the data to write * @param callback {function(*, GridStore)} This will be called after executing * this method. The first parameter will contain null and the second one * will contain a reference to this object. */ Chunk.prototype.write = function(data, callback) { this.data.write(data, this.internalPosition, data.length, 'binary'); this.internalPosition = this.data.length(); if (callback != null) return callback(null, this); return this; }; /** * Reads data and advances the read/write head. * * @param length {number} The length of data to read. * * @return {string} The data read if the given length will not exceed the end of * the chunk. Returns an empty String otherwise. */ Chunk.prototype.read = function(length) { // Default to full read if no index defined length = length == null || length === 0 ? this.length() : length; if (this.length() - this.internalPosition + 1 >= length) { var data = this.data.read(this.internalPosition, length); this.internalPosition = this.internalPosition + length; return data; } else { return ''; } }; Chunk.prototype.readSlice = function(length) { if (this.length() - this.internalPosition >= length) { var data = null; if (this.data.buffer != null) { //Pure BSON data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); } else { //Native BSON data = new Buffer(length); length = this.data.readInto(data, this.internalPosition); } this.internalPosition = this.internalPosition + length; return data; } else { return null; } }; /** * Checks if the read/write head is at the end. * * @return {boolean} Whether the read/write head has reached the end of this * chunk. */ Chunk.prototype.eof = function() { return this.internalPosition === this.length() ? true : false; }; /** * Reads one character from the data of this chunk and advances the read/write * head. * * @return {string} a single character data read if the the read/write head is * not at the end of the chunk. Returns an empty String otherwise. */ Chunk.prototype.getc = function() { return this.read(1); }; /** * Clears the contents of the data in this chunk and resets the read/write head * to the initial position. */ Chunk.prototype.rewind = function() { this.internalPosition = 0; this.data = new Binary(); }; /** * Saves this chunk to the database. Also overwrites existing entries having the * same id as this chunk. * * @param callback {function(*, GridStore)} This will be called after executing * this method. The first parameter will contain null and the second one * will contain a reference to this object. */ Chunk.prototype.save = function(options, callback) { var self = this; if (typeof options === 'function') { callback = options; options = {}; } self.file.chunkCollection(function(err, collection) { if (err) return callback(err); // Merge the options var writeOptions = { upsert: true }; for (var name in options) writeOptions[name] = options[name]; for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; if (self.data.length() > 0) { self.buildMongoObject(function(mongoObject) { var options = { forceServerObjectId: true }; for (var name in self.writeConcern) { options[name] = self.writeConcern[name]; } collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { callback(err, self); }); }); } else { callback(null, self); } // }); }); }; /** * Creates a mongoDB object representation of this chunk. * * @param callback {function(Object)} This will be called after executing this * method. The object will be passed to the first parameter and will have * the structure: * *

 *        {
 *          '_id' : , // {number} id for this chunk
 *          'files_id' : , // {number} foreign key to the file collection
 *          'n' : , // {number} chunk number
 *          'data' : , // {bson#Binary} the chunk data itself
 *        }
 *        
* * @see MongoDB GridFS Chunk Object Structure */ Chunk.prototype.buildMongoObject = function(callback) { var mongoObject = { files_id: this.file.fileId, n: this.chunkNumber, data: this.data }; // If we are saving using a specific ObjectId if (this.objectId != null) mongoObject._id = this.objectId; callback(mongoObject); }; /** * @return {number} the length of the data */ Chunk.prototype.length = function() { return this.data.length(); }; /** * The position of the read/write head * @name position * @lends Chunk# * @field */ Object.defineProperty(Chunk.prototype, 'position', { enumerable: true, get: function() { return this.internalPosition; }, set: function(value) { this.internalPosition = value; } }); /** * The default chunk size * @constant */ Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; module.exports = Chunk; }).call(this,require("buffer").Buffer) },{"buffer":144,"mongodb-core":345}],391:[function(require,module,exports){ (function (process){ 'use strict'; /** * @fileOverview GridFS is a tool for MongoDB to store files to the database. * Because of the restrictions of the object size the database can hold, a * facility to split a file into several chunks is needed. The {@link GridStore} * class offers a simplified api to interact with files while managing the * chunks of split files behind the scenes. More information about GridFS can be * found here. * * @example * const MongoClient = require('mongodb').MongoClient; * const GridStore = require('mongodb').GridStore; * const ObjectID = require('mongodb').ObjectID; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * const db = client.db(dbName); * const gridStore = new GridStore(db, null, "w"); * gridStore.open(function(err, gridStore) { * gridStore.write("hello world!", function(err, gridStore) { * gridStore.close(function(err, result) { * // Let's read the file using object Id * GridStore.read(db, result._id, function(err, data) { * test.equal('hello world!', data); * client.close(); * test.done(); * }); * }); * }); * }); * }); */ var Chunk = require('./chunk'), ObjectID = require('mongodb-core').BSON.ObjectID, ReadPreference = require('mongodb-core').ReadPreference, Buffer = require('buffer').Buffer, Collection = require('../collection'), fs = require('fs'), f = require('util').format, util = require('util'), Define = require('../metadata'), MongoError = require('mongodb-core').MongoError, inherits = util.inherits, Duplex = require('stream').Duplex, shallowClone = require('../utils').shallowClone, executeOperation = require('../utils').executeOperation; var REFERENCE_BY_FILENAME = 0, REFERENCE_BY_ID = 1; /** * Namespace provided by the mongodb-core and node.js * @external Duplex */ /** * Create a new GridStore instance * * Modes * - **"r"** - read only. This is the default mode. * - **"w"** - write in truncate mode. Existing data will be overwriten. * * @class * @param {Db} db A database instance to interact with. * @param {object} [id] optional unique id for this file * @param {string} [filename] optional filename for this file, no unique constrain on the field * @param {string} mode set the mode for this file. * @param {object} [options=null] Optional settings. * @param {(number|string)} [options.w=null] The write concern. * @param {number} [options.wtimeout=null] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.fsync=false] Specify a file sync write concern. * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. * @param {object} [options.metadata=null] Arbitrary data the user wants to store. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @property {number} chunkSize Get the gridstore chunk size. * @property {number} md5 The md5 checksum for this file. * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory * @return {GridStore} a GridStore instance. * @deprecated Use GridFSBucket API instead */ var GridStore = function GridStore(db, id, filename, mode, options) { if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); this.db = db; // Handle options if (typeof options === 'undefined') options = {}; // Handle mode if (typeof mode === 'undefined') { mode = filename; filename = undefined; } else if (typeof mode === 'object') { options = mode; mode = filename; filename = undefined; } if (id && id._bsontype === 'ObjectID') { this.referenceBy = REFERENCE_BY_ID; this.fileId = id; this.filename = filename; } else if (typeof filename === 'undefined') { this.referenceBy = REFERENCE_BY_FILENAME; this.filename = id; if (mode.indexOf('w') != null) { this.fileId = new ObjectID(); } } else { this.referenceBy = REFERENCE_BY_ID; this.fileId = id; this.filename = filename; } // Set up the rest this.mode = mode == null ? 'r' : mode; this.options = options || {}; // Opened this.isOpen = false; // Set the root if overridden this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; this.position = 0; this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.primary; this.writeConcern = _getWriteConcern(db, this.options); // Set default chunk size this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; // Get the promiseLibrary var promiseLibrary = this.options.promiseLibrary || Promise; // Set the promiseLibrary this.promiseLibrary = promiseLibrary; Object.defineProperty(this, 'chunkSize', { enumerable: true, get: function() { return this.internalChunkSize; }, set: function(value) { if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { this.internalChunkSize = this.internalChunkSize; } else { this.internalChunkSize = value; } } }); Object.defineProperty(this, 'md5', { enumerable: true, get: function() { return this.internalMd5; } }); Object.defineProperty(this, 'chunkNumber', { enumerable: true, get: function() { return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; } }); }; var define = (GridStore.define = new Define('Gridstore', GridStore, true)); /** * The callback format for the Gridstore.open method * @callback GridStore~openCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {GridStore} gridStore The GridStore instance if the open method was successful. */ /** * Opens the file from the database and initialize this object. Also creates a * new one if file does not exist. * * @method * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~openCallback} [callback] this will be called after executing this method * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.open = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); } return executeOperation(this.db.s.topology, open, [this, options, callback], { skipSessions: true }); }; var open = function(self, options, callback) { // Get the write concern var writeConcern = _getWriteConcern(self.db, self.options); // If we are writing we need to ensure we have the right indexes for md5's if (self.mode === 'w' || self.mode === 'w+') { // Get files collection var collection = self.collection(); // Put index on filename collection.ensureIndex([['filename', 1]], writeConcern, function() { // Get chunk collection var chunkCollection = self.chunkCollection(); // Make an unique index for compatibility with mongo-cxx-driver:legacy var chunkIndexOptions = shallowClone(writeConcern); chunkIndexOptions.unique = true; // Ensure index on chunk collection chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { // Open the connection _open(self, writeConcern, function(err, r) { if (err) return callback(err); self.isOpen = true; callback(err, r); }); }); }); } else { // Open the gridstore _open(self, writeConcern, function(err, r) { if (err) return callback(err); self.isOpen = true; callback(err, r); }); } }; // Push the definition for open define.classMethod('open', { callback: true, promise: true }); /** * Verify if the file is at EOF. * * @method * @return {boolean} true if the read/write head is at the end of this file. * @deprecated Use GridFSBucket API instead */ GridStore.prototype.eof = function() { return this.position === this.length ? true : false; }; define.classMethod('eof', { callback: false, promise: false, returns: [Boolean] }); /** * The callback result format. * @callback GridStore~resultCallback * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {MongoError} error An error instance representing the error during the execution. * @param {object} result The result from the callback. */ /** * Retrieves a single character from this file. * * @method * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.getc = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.db.s.topology, getc, [this, options, callback], { skipSessions: true }); }; var getc = function(self, options, callback) { if (self.eof()) { callback(null, null); } else if (self.currentChunk.eof()) { nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { self.currentChunk = chunk; self.position = self.position + 1; callback(err, self.currentChunk.getc()); }); } else { self.position = self.position + 1; callback(null, self.currentChunk.getc()); } }; define.classMethod('getc', { callback: true, promise: true }); /** * Writes a string to the file with a newline character appended at the end if * the given string does not have one. * * @method * @param {string} string the string to write. * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.puts = function(string, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; var finalString = string.match(/\n$/) == null ? string + '\n' : string; return executeOperation( this.db.s.topology, this.write.bind(this), [finalString, options, callback], { skipSessions: true } ); }; define.classMethod('puts', { callback: true, promise: true }); /** * Return a modified Readable stream including a possible transform method. * * @method * @return {GridStoreStream} * @deprecated Use GridFSBucket API instead */ GridStore.prototype.stream = function() { return new GridStoreStream(this); }; define.classMethod('stream', { callback: false, promise: false, returns: [GridStoreStream] }); /** * Writes some data. This method will work properly only if initialized with mode "w" or "w+". * * @method * @param {(string|Buffer)} data the data to write. * @param {boolean} [close] closes this file after writing if set to true. * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.write = function write(data, close, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation( this.db.s.topology, _writeNormal, [this, data, close, options, callback], { skipSessions: true } ); }; define.classMethod('write', { callback: true, promise: true }); /** * Handles the destroy part of a stream * * @method * @result {null} * @deprecated Use GridFSBucket API instead */ GridStore.prototype.destroy = function destroy() { // close and do not emit any more events. queued data is not sent. if (!this.writable) return; this.readable = false; if (this.writable) { this.writable = false; this._q.length = 0; this.emit('close'); } }; define.classMethod('destroy', { callback: false, promise: false }); /** * Stores a file from the file system to the GridFS database. * * @method * @param {(string|Buffer|FileHandle)} file the file to store. * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.writeFile = function(file, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.db.s.topology, writeFile, [this, file, options, callback], { skipSessions: true }); }; var writeFile = function(self, file, options, callback) { if (typeof file === 'string') { fs.open(file, 'r', function(err, fd) { if (err) return callback(err); self.writeFile(fd, callback); }); return; } self.open(function(err, self) { if (err) return callback(err, self); fs.fstat(file, function(err, stats) { if (err) return callback(err, self); var offset = 0; var index = 0; // Write a chunk var writeChunk = function() { // Allocate the buffer var _buffer = new Buffer(self.chunkSize); // Read the file fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { if (err) return callback(err, self); offset = offset + bytesRead; // Create a new chunk for the data var chunk = new Chunk(self, { n: index++ }, self.writeConcern); chunk.write(data.slice(0, bytesRead), function(err, chunk) { if (err) return callback(err, self); chunk.save({}, function(err) { if (err) return callback(err, self); self.position = self.position + bytesRead; // Point to current chunk self.currentChunk = chunk; if (offset >= stats.size) { fs.close(file, function(err) { if (err) return callback(err); self.close(function(err) { if (err) return callback(err, self); return callback(null, self); }); }); } else { return process.nextTick(writeChunk); } }); }); }); }; // Process the first write process.nextTick(writeChunk); }); }); }; define.classMethod('writeFile', { callback: true, promise: true }); /** * Saves this file to the database. This will overwrite the old entry if it * already exists. This will work properly only if mode was initialized to * "w" or "w+". * * @method * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.close = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.db.s.topology, close, [this, options, callback], { skipSessions: true }); }; var close = function(self, options, callback) { if (self.mode[0] === 'w') { // Set up options options = Object.assign({}, self.writeConcern, options); if (self.currentChunk != null && self.currentChunk.position > 0) { self.currentChunk.save({}, function(err) { if (err && typeof callback === 'function') return callback(err); self.collection(function(err, files) { if (err && typeof callback === 'function') return callback(err); // Build the mongo object if (self.uploadDate != null) { buildMongoObject(self, function(err, mongoObject) { if (err) { if (typeof callback === 'function') return callback(err); else throw err; } files.save(mongoObject, options, function(err) { if (typeof callback === 'function') callback(err, mongoObject); }); }); } else { self.uploadDate = new Date(); buildMongoObject(self, function(err, mongoObject) { if (err) { if (typeof callback === 'function') return callback(err); else throw err; } files.save(mongoObject, options, function(err) { if (typeof callback === 'function') callback(err, mongoObject); }); }); } }); }); } else { self.collection(function(err, files) { if (err && typeof callback === 'function') return callback(err); self.uploadDate = new Date(); buildMongoObject(self, function(err, mongoObject) { if (err) { if (typeof callback === 'function') return callback(err); else throw err; } files.save(mongoObject, options, function(err) { if (typeof callback === 'function') callback(err, mongoObject); }); }); }); } } else if (self.mode[0] === 'r') { if (typeof callback === 'function') callback(null, null); } else { if (typeof callback === 'function') callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); } }; define.classMethod('close', { callback: true, promise: true }); /** * The collection callback format. * @callback GridStore~collectionCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection} collection The collection from the command execution. */ /** * Retrieve this file's chunks collection. * * @method * @param {GridStore~collectionCallback} callback the command callback. * @return {Collection} * @deprecated Use GridFSBucket API instead */ GridStore.prototype.chunkCollection = function(callback) { if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); return this.db.collection(this.root + '.chunks'); }; define.classMethod('chunkCollection', { callback: true, promise: false, returns: [Collection] }); /** * Deletes all the chunks of this file in the database. * * @method * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.unlink = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.db.s.topology, unlink, [this, options, callback], { skipSessions: true }); }; var unlink = function(self, options, callback) { deleteChunks(self, function(err) { if (err !== null) { err.message = 'at deleteChunks: ' + err.message; return callback(err); } self.collection(function(err, collection) { if (err !== null) { err.message = 'at collection: ' + err.message; return callback(err); } collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { callback(err, self); }); }); }); }; define.classMethod('unlink', { callback: true, promise: true }); /** * Retrieves the file collection associated with this object. * * @method * @param {GridStore~collectionCallback} callback the command callback. * @return {Collection} * @deprecated Use GridFSBucket API instead */ GridStore.prototype.collection = function(callback) { if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); return this.db.collection(this.root + '.files'); }; define.classMethod('collection', { callback: true, promise: false, returns: [Collection] }); /** * The readlines callback format. * @callback GridStore~readlinesCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {string[]} strings The array of strings returned. */ /** * Read the entire file as a list of strings splitting by the provided separator. * * @method * @param {string} [separator] The character to be recognized as the newline separator. * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~readlinesCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.readlines = function(separator, options, callback) { var args = Array.prototype.slice.call(arguments, 0); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; separator = args.length ? args.shift() : '\n'; separator = separator || '\n'; options = args.length ? args.shift() : {}; return executeOperation(this.db.s.topology, readlines, [this, separator, options, callback], { skipSessions: true }); }; var readlines = function(self, separator, options, callback) { self.read(function(err, data) { if (err) return callback(err); var items = data.toString().split(separator); items = items.length > 0 ? items.splice(0, items.length - 1) : []; for (var i = 0; i < items.length; i++) { items[i] = items[i] + separator; } callback(null, items); }); }; define.classMethod('readlines', { callback: true, promise: true }); /** * Deletes all the chunks of this file in the database if mode was set to "w" or * "w+" and resets the read/write head to the initial position. * * @method * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.rewind = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; return executeOperation(this.db.s.topology, rewind, [this, options, callback], { skipSessions: true }); }; var rewind = function(self, options, callback) { if (self.currentChunk.chunkNumber !== 0) { if (self.mode[0] === 'w') { deleteChunks(self, function(err) { if (err) return callback(err); self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); self.position = 0; callback(null, self); }); } else { self.currentChunk(0, function(err, chunk) { if (err) return callback(err); self.currentChunk = chunk; self.currentChunk.rewind(); self.position = 0; callback(null, self); }); } } else { self.currentChunk.rewind(); self.position = 0; callback(null, self); } }; define.classMethod('rewind', { callback: true, promise: true }); /** * The read callback format. * @callback GridStore~readCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Buffer} data The data read from the GridStore object */ /** * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. * * There are 3 signatures for this method: * * (callback) * (length, callback) * (length, buffer, callback) * * @method * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~readCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.read = function(length, buffer, options, callback) { var args = Array.prototype.slice.call(arguments, 0); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; length = args.length ? args.shift() : null; buffer = args.length ? args.shift() : null; options = args.length ? args.shift() : {}; return executeOperation(this.db.s.topology, read, [this, length, buffer, options, callback], { skipSessions: true }); }; var read = function(self, length, buffer, options, callback) { // The data is a c-terminated string and thus the length - 1 var finalLength = length == null ? self.length - self.position : length; var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; // Add a index to buffer to keep track of writing position or apply current index finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); // Copy content to final buffer slice.copy(finalBuffer, finalBuffer._index); // Update internal position self.position = self.position + finalBuffer.length; // Check if we don't have a file at all if (finalLength === 0 && finalBuffer.length === 0) return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); // Else return data return callback(null, finalBuffer); } // Read the next chunk slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); // Copy content to final buffer slice.copy(finalBuffer, finalBuffer._index); // Update index position finalBuffer._index += slice.length; // Load next chunk and read more nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { if (err) return callback(err); if (chunk.length() > 0) { self.currentChunk = chunk; self.read(length, finalBuffer, callback); } else { if (finalBuffer._index > 0) { callback(null, finalBuffer); } else { callback( MongoError.create({ message: 'no chunks found for file, possibly corrupt', driver: true }), null ); } } }); }; define.classMethod('read', { callback: true, promise: true }); /** * The tell callback format. * @callback GridStore~tellCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {number} position The current read position in the GridStore. */ /** * Retrieves the position of the read/write head of this file. * * @method * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~tellCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.tell = function(callback) { var self = this; // We provided a callback leg if (typeof callback === 'function') return callback(null, this.position); // Return promise return new self.promiseLibrary(function(resolve) { resolve(self.position); }); }; define.classMethod('tell', { callback: true, promise: true }); /** * The tell callback format. * @callback GridStore~gridStoreCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {GridStore} gridStore The gridStore. */ /** * Moves the read/write head to a new location. * * There are 3 signatures for this method * * Seek Location Modes * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. * - **GridStore.IO_SEEK_END**, set the position from the end of the file. * * @method * @param {number} [position] the position to seek to * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. * @param {object} [options] Optional settings * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~gridStoreCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.prototype.seek = function(position, seekLocation, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; seekLocation = args.length ? args.shift() : null; options = args.length ? args.shift() : {}; return executeOperation( this.db.s.topology, seek, [this, position, seekLocation, options, callback], { skipSessions: true } ); }; var seek = function(self, position, seekLocation, options, callback) { // Seek only supports read mode if (self.mode !== 'r') { return callback( MongoError.create({ message: 'seek is only supported for mode r', driver: true }) ); } var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; var finalPosition = position; var targetPosition = 0; // Calculate the position if (seekLocationFinal === GridStore.IO_SEEK_CUR) { targetPosition = self.position + finalPosition; } else if (seekLocationFinal === GridStore.IO_SEEK_END) { targetPosition = self.length + finalPosition; } else { targetPosition = finalPosition; } // Get the chunk var newChunkNumber = Math.floor(targetPosition / self.chunkSize); var seekChunk = function() { nthChunk(self, newChunkNumber, function(err, chunk) { if (err) return callback(err, null); if (chunk == null) return callback(new Error('no chunk found')); // Set the current chunk self.currentChunk = chunk; self.position = targetPosition; self.currentChunk.position = self.position % self.chunkSize; callback(err, self); }); }; seekChunk(); }; define.classMethod('seek', { callback: true, promise: true }); /** * @ignore */ var _open = function(self, options, callback) { var collection = self.collection(); // Create the query var query = self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; query = null == self.fileId && self.filename == null ? null : query; options.readPreference = self.readPreference; // Fetch the chunks if (query != null) { collection.findOne(query, options, function(err, doc) { if (err) { return error(err); } // Check if the collection for the files exists otherwise prepare the new one if (doc != null) { self.fileId = doc._id; // Prefer a new filename over the existing one if this is a write self.filename = self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; self.contentType = doc.contentType; self.internalChunkSize = doc.chunkSize; self.uploadDate = doc.uploadDate; self.aliases = doc.aliases; self.length = doc.length; self.metadata = doc.metadata; self.internalMd5 = doc.md5; } else if (self.mode !== 'r') { self.fileId = self.fileId == null ? new ObjectID() : self.fileId; self.contentType = GridStore.DEFAULT_CONTENT_TYPE; self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; self.length = 0; } else { self.length = 0; var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; return error( MongoError.create({ message: f( 'file with id %s not opened for writing', self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename ), driver: true }), self ); } // Process the mode of the object if (self.mode === 'r') { nthChunk(self, 0, options, function(err, chunk) { if (err) return error(err); self.currentChunk = chunk; self.position = 0; callback(null, self); }); } else if (self.mode === 'w' && doc) { // Delete any existing chunks deleteChunks(self, options, function(err) { if (err) return error(err); self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; self.position = 0; callback(null, self); }); } else if (self.mode === 'w') { self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; self.position = 0; callback(null, self); } else if (self.mode === 'w+') { nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { if (err) return error(err); // Set the current chunk self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; self.currentChunk.position = self.currentChunk.data.length(); self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; self.position = self.length; callback(null, self); }); } }); } else { // Write only mode self.fileId = null == self.fileId ? new ObjectID() : self.fileId; self.contentType = GridStore.DEFAULT_CONTENT_TYPE; self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; self.length = 0; // No file exists set up write mode if (self.mode === 'w') { // Delete any existing chunks deleteChunks(self, options, function(err) { if (err) return error(err); self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; self.position = 0; callback(null, self); }); } else if (self.mode === 'w+') { nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { if (err) return error(err); // Set the current chunk self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; self.currentChunk.position = self.currentChunk.data.length(); self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; self.position = self.length; callback(null, self); }); } } // only pass error to callback once function error(err) { if (error.err) return; callback((error.err = err)); } }; /** * @ignore */ var writeBuffer = function(self, buffer, close, callback) { if (typeof close === 'function') { callback = close; close = null; } var finalClose = typeof close === 'boolean' ? close : false; if (self.mode !== 'w') { callback( MongoError.create({ message: f( 'file with id %s not opened for writing', self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename ), driver: true }), null ); } else { if (self.currentChunk.position + buffer.length >= self.chunkSize) { // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left // to a new chunk (recursively) var previousChunkNumber = self.currentChunk.chunkNumber; var leftOverDataSize = self.chunkSize - self.currentChunk.position; var firstChunkData = buffer.slice(0, leftOverDataSize); var leftOverData = buffer.slice(leftOverDataSize); // A list of chunks to write out var chunksToWrite = [self.currentChunk.write(firstChunkData)]; // If we have more data left than the chunk size let's keep writing new chunks while (leftOverData.length >= self.chunkSize) { // Create a new chunk and write to it var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); firstChunkData = leftOverData.slice(0, self.chunkSize); leftOverData = leftOverData.slice(self.chunkSize); // Update chunk number previousChunkNumber = previousChunkNumber + 1; // Write data newChunk.write(firstChunkData); // Push chunk to save list chunksToWrite.push(newChunk); } // Set current chunk with remaining data self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); // If we have left over data write it if (leftOverData.length > 0) self.currentChunk.write(leftOverData); // Update the position for the gridstore self.position = self.position + buffer.length; // Total number of chunks to write var numberOfChunksToWrite = chunksToWrite.length; for (var i = 0; i < chunksToWrite.length; i++) { chunksToWrite[i].save({}, function(err) { if (err) return callback(err); numberOfChunksToWrite = numberOfChunksToWrite - 1; if (numberOfChunksToWrite <= 0) { // We care closing the file before returning if (finalClose) { return self.close(function(err) { callback(err, self); }); } // Return normally return callback(null, self); } }); } } else { // Update the position for the gridstore self.position = self.position + buffer.length; // We have less data than the chunk size just write it and callback self.currentChunk.write(buffer); // We care closing the file before returning if (finalClose) { return self.close(function(err) { callback(err, self); }); } // Return normally return callback(null, self); } } }; /** * Creates a mongoDB object representation of this object. * *

 *        {
 *          '_id' : , // {number} id for this file
 *          'filename' : , // {string} name for this file
 *          'contentType' : , // {string} mime type for this file
 *          'length' : , // {number} size of this file?
 *          'chunksize' : , // {number} chunk size used by this file
 *          'uploadDate' : , // {Date}
 *          'aliases' : , // {array of string}
 *          'metadata' : , // {string}
 *        }
 *        
* * @ignore */ var buildMongoObject = function(self, callback) { // Calcuate the length var mongoObject = { _id: self.fileId, filename: self.filename, contentType: self.contentType, length: self.position ? self.position : 0, chunkSize: self.chunkSize, uploadDate: self.uploadDate, aliases: self.aliases, metadata: self.metadata }; var md5Command = { filemd5: self.fileId, root: self.root }; self.db.command(md5Command, function(err, results) { if (err) return callback(err); mongoObject.md5 = results.md5; callback(null, mongoObject); }); }; /** * Gets the nth chunk of this file. * @ignore */ var nthChunk = function(self, chunkNumber, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || self.writeConcern; options.readPreference = self.readPreference; // Get the nth chunk self .chunkCollection() .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { if (err) return callback(err); var finalChunk = chunk == null ? {} : chunk; callback(null, new Chunk(self, finalChunk, self.writeConcern)); }); }; /** * @ignore */ var lastChunkNumber = function(self) { return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); }; /** * Deletes all the chunks of this file in the database. * * @ignore */ var deleteChunks = function(self, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || self.writeConcern; if (self.fileId != null) { self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { if (err) return callback(err, false); callback(null, true); }); } else { callback(null, true); } }; /** * The collection to be used for holding the files and chunks collection. * * @classconstant DEFAULT_ROOT_COLLECTION */ GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; /** * Default file mime type * * @classconstant DEFAULT_CONTENT_TYPE */ GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; /** * Seek mode where the given length is absolute. * * @classconstant IO_SEEK_SET */ GridStore.IO_SEEK_SET = 0; /** * Seek mode where the given length is an offset to the current read/write head. * * @classconstant IO_SEEK_CUR */ GridStore.IO_SEEK_CUR = 1; /** * Seek mode where the given length is an offset to the end of the file. * * @classconstant IO_SEEK_END */ GridStore.IO_SEEK_END = 2; /** * Checks if a file exists in the database. * * @method * @static * @param {Db} db the database to query. * @param {string} name The name of the file to look for. * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] result from exists. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { var args = Array.prototype.slice.call(arguments, 2); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; rootCollection = args.length ? args.shift() : null; options = args.length ? args.shift() : {}; options = options || {}; return executeOperation( db.s.topology, exists, [db, fileIdObject, rootCollection, options, callback], { skipSessions: true } ); }; var exists = function(db, fileIdObject, rootCollection, options, callback) { // Establish read preference var readPreference = options.readPreference || ReadPreference.PRIMARY; // Fetch collection var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; db.collection(rootCollectionFinal + '.files', function(err, collection) { if (err) return callback(err); // Build query var query = typeof fileIdObject === 'string' || Object.prototype.toString.call(fileIdObject) === '[object RegExp]' ? { filename: fileIdObject } : { _id: fileIdObject }; // Attempt to locate file // We have a specific query if ( fileIdObject != null && typeof fileIdObject === 'object' && Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' ) { query = fileIdObject; } // Check if the entry exists collection.findOne(query, { readPreference: readPreference }, function(err, item) { if (err) return callback(err); callback(null, item == null ? false : true); }); }); }; define.staticMethod('exist', { callback: true, promise: true }); /** * Gets the list of files stored in the GridFS. * * @method * @static * @param {Db} db the database to query. * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] result from exists. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.list = function(db, rootCollection, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; rootCollection = args.length ? args.shift() : null; options = args.length ? args.shift() : {}; options = options || {}; return executeOperation(db.s.topology, list, [db, rootCollection, options, callback], { skipSessions: true }); }; var list = function(db, rootCollection, options, callback) { // Ensure we have correct values if (rootCollection != null && typeof rootCollection === 'object') { options = rootCollection; rootCollection = null; } // Establish read preference var readPreference = options.readPreference || ReadPreference.primary; // Check if we are returning by id not filename var byId = options['id'] != null ? options['id'] : false; // Fetch item var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; var items = []; db.collection(rootCollectionFinal + '.files', function(err, collection) { if (err) return callback(err); collection.find({}, { readPreference: readPreference }, function(err, cursor) { if (err) return callback(err); cursor.each(function(err, item) { if (item != null) { items.push(byId ? item._id : item.filename); } else { callback(err, items); } }); }); }); }; define.staticMethod('list', { callback: true, promise: true }); /** * Reads the contents of a file. * * This method has the following signatures * * (db, name, callback) * (db, name, length, callback) * (db, name, length, offset, callback) * (db, name, length, offset, options, callback) * * @method * @static * @param {Db} db the database to query. * @param {string} name The name of the file. * @param {number} [length] The size of data to read. * @param {number} [offset] The offset from the head of the file of which to start reading from. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~readCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.read = function(db, name, length, offset, options, callback) { var args = Array.prototype.slice.call(arguments, 2); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; length = args.length ? args.shift() : null; offset = args.length ? args.shift() : null; options = args.length ? args.shift() : null; options = options || {}; return executeOperation( db.s.topology, readStatic, [db, name, length, offset, options, callback], { skipSessions: true } ); }; var readStatic = function(db, name, length, offset, options, callback) { new GridStore(db, name, 'r', options).open(function(err, gridStore) { if (err) return callback(err); // Make sure we are not reading out of bounds if (offset && offset >= gridStore.length) return callback('offset larger than size of file', null); if (length && length > gridStore.length) return callback('length is larger than the size of the file', null); if (offset && length && offset + length > gridStore.length) return callback('offset and length is larger than the size of the file', null); if (offset != null) { gridStore.seek(offset, function(err, gridStore) { if (err) return callback(err); gridStore.read(length, callback); }); } else { gridStore.read(length, callback); } }); }; define.staticMethod('read', { callback: true, promise: true }); /** * Read the entire file as a list of strings splitting by the provided separator. * * @method * @static * @param {Db} db the database to query. * @param {(String|object)} name the name of the file. * @param {string} [separator] The character to be recognized as the newline separator. * @param {object} [options=null] Optional settings. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~readlinesCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.readlines = function(db, name, separator, options, callback) { var args = Array.prototype.slice.call(arguments, 2); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; separator = args.length ? args.shift() : null; options = args.length ? args.shift() : null; options = options || {}; return executeOperation( db.s.topology, readlinesStatic, [db, name, separator, options, callback], { skipSessions: true } ); }; var readlinesStatic = function(db, name, separator, options, callback) { var finalSeperator = separator == null ? '\n' : separator; new GridStore(db, name, 'r', options).open(function(err, gridStore) { if (err) return callback(err); gridStore.readlines(finalSeperator, callback); }); }; define.staticMethod('readlines', { callback: true, promise: true }); /** * Deletes the chunks and metadata information of a file from GridFS. * * @method * @static * @param {Db} db The database to query. * @param {(string|array)} names The name/names of the files to delete. * @param {object} [options=null] Optional settings. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {ClientSession} [options.session] optional session to use for this operation * @param {GridStore~resultCallback} [callback] the command callback. * @return {Promise} returns Promise if no callback passed * @deprecated Use GridFSBucket API instead */ GridStore.unlink = function(db, names, options, callback) { var args = Array.prototype.slice.call(arguments, 2); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() : {}; options = options || {}; return executeOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { skipSessions: true }); }; var unlinkStatic = function(self, db, names, options, callback) { // Get the write concern var writeConcern = _getWriteConcern(db, options); // List of names if (names.constructor === Array) { var tc = 0; for (var i = 0; i < names.length; i++) { ++tc; GridStore.unlink(db, names[i], options, function() { if (--tc === 0) { callback(null, self); } }); } } else { new GridStore(db, names, 'w', options).open(function(err, gridStore) { if (err) return callback(err); deleteChunks(gridStore, function(err) { if (err) return callback(err); gridStore.collection(function(err, collection) { if (err) return callback(err); collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { callback(err, self); }); }); }); }); } }; define.staticMethod('unlink', { callback: true, promise: true }); /** * @ignore */ var _writeNormal = function(self, data, close, options, callback) { // If we have a buffer write it using the writeBuffer method if (Buffer.isBuffer(data)) { return writeBuffer(self, data, close, callback); } else { return writeBuffer(self, new Buffer(data, 'binary'), close, callback); } }; /** * @ignore */ var _setWriteConcernHash = function(options) { var finalOptions = {}; if (options.w != null) finalOptions.w = options.w; if (options.journal === true) finalOptions.j = options.journal; if (options.j === true) finalOptions.j = options.j; if (options.fsync === true) finalOptions.fsync = options.fsync; if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; return finalOptions; }; /** * @ignore */ var _getWriteConcern = function(self, options) { // Final options var finalOptions = { w: 1 }; options = options || {}; // Local options verification if ( options.w != null || typeof options.j === 'boolean' || typeof options.journal === 'boolean' || typeof options.fsync === 'boolean' ) { finalOptions = _setWriteConcernHash(options); } else if (options.safe != null && typeof options.safe === 'object') { finalOptions = _setWriteConcernHash(options.safe); } else if (typeof options.safe === 'boolean') { finalOptions = { w: options.safe ? 1 : 0 }; } else if ( self.options.w != null || typeof self.options.j === 'boolean' || typeof self.options.journal === 'boolean' || typeof self.options.fsync === 'boolean' ) { finalOptions = _setWriteConcernHash(self.options); } else if ( self.safe && (self.safe.w != null || typeof self.safe.j === 'boolean' || typeof self.safe.journal === 'boolean' || typeof self.safe.fsync === 'boolean') ) { finalOptions = _setWriteConcernHash(self.safe); } else if (typeof self.safe === 'boolean') { finalOptions = { w: self.safe ? 1 : 0 }; } // Ensure we don't have an invalid combination of write concerns if ( finalOptions.w < 1 && (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) ) throw MongoError.create({ message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', driver: true }); // Return the options return finalOptions; }; /** * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) * * @class * @extends external:Duplex * @return {GridStoreStream} a GridStoreStream instance. * @deprecated Use GridFSBucket API instead */ var GridStoreStream = function(gs) { // Initialize the duplex stream Duplex.call(this); // Get the gridstore this.gs = gs; // End called this.endCalled = false; // If we have a seek this.totalBytesToRead = this.gs.length - this.gs.position; this.seekPosition = this.gs.position; }; // // Inherit duplex inherits(GridStoreStream, Duplex); GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; // Set up override GridStoreStream.prototype.pipe = function(destination) { var self = this; // Only open gridstore if not already open if (!self.gs.isOpen) { self.gs.open(function(err) { if (err) return self.emit('error', err); self.totalBytesToRead = self.gs.length - self.gs.position; self._pipe.apply(self, [destination]); }); } else { self.totalBytesToRead = self.gs.length - self.gs.position; self._pipe.apply(self, [destination]); } return destination; }; // Called by stream GridStoreStream.prototype._read = function() { var self = this; var read = function() { // Read data self.gs.read(length, function(err, buffer) { if (err && !self.endCalled) return self.emit('error', err); // Stream is closed if (self.endCalled || buffer == null) return self.push(null); // Remove bytes read if (buffer.length <= self.totalBytesToRead) { self.totalBytesToRead = self.totalBytesToRead - buffer.length; self.push(buffer); } else if (buffer.length > self.totalBytesToRead) { self.totalBytesToRead = self.totalBytesToRead - buffer._index; self.push(buffer.slice(0, buffer._index)); } // Finished reading if (self.totalBytesToRead <= 0) { self.endCalled = true; } }); }; // Set read length var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; if (!self.gs.isOpen) { self.gs.open(function(err) { self.totalBytesToRead = self.gs.length - self.gs.position; if (err) return self.emit('error', err); read(); }); } else { read(); } }; GridStoreStream.prototype.destroy = function() { this.pause(); this.endCalled = true; this.gs.close(); this.emit('end'); }; GridStoreStream.prototype.write = function(chunk) { var self = this; if (self.endCalled) return self.emit( 'error', MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) ); // Do we have to open the gridstore if (!self.gs.isOpen) { self.gs.open(function() { self.gs.isOpen = true; self.gs.write(chunk, function() { process.nextTick(function() { self.emit('drain'); }); }); }); return false; } else { self.gs.write(chunk, function() { self.emit('drain'); }); return true; } }; GridStoreStream.prototype.end = function(chunk, encoding, callback) { var self = this; var args = Array.prototype.slice.call(arguments, 0); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; chunk = args.length ? args.shift() : null; encoding = args.length ? args.shift() : null; self.endCalled = true; if (chunk) { self.gs.write(chunk, function() { self.gs.close(function() { if (typeof callback === 'function') callback(); self.emit('end'); }); }); } self.gs.close(function() { if (typeof callback === 'function') callback(); self.emit('end'); }); }; /** * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. * @function external:Duplex#read * @param {number} size Optional argument to specify how much data to read. * @return {(String | Buffer | null)} */ /** * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. * @function external:Duplex#setEncoding * @param {string} encoding The encoding to use. * @return {null} */ /** * This method will cause the readable stream to resume emitting data events. * @function external:Duplex#resume * @return {null} */ /** * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. * @function external:Duplex#pause * @return {null} */ /** * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. * @function external:Duplex#pipe * @param {Writable} destination The destination for writing data * @param {object} [options] Pipe options * @return {null} */ /** * This method will remove the hooks set up for a previous pipe() call. * @function external:Duplex#unpipe * @param {Writable} [destination] The destination for writing data * @return {null} */ /** * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. * @function external:Duplex#unshift * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. * @return {null} */ /** * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) * @function external:Duplex#wrap * @param {Stream} stream An "old style" readable stream. * @return {null} */ /** * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. * @function external:Duplex#write * @param {(string|Buffer)} chunk The data to write * @param {string} encoding The encoding, if chunk is a String * @param {function} callback Callback for when this chunk of data is flushed * @return {boolean} */ /** * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. * @function external:Duplex#end * @param {(string|Buffer)} chunk The data to write * @param {string} encoding The encoding, if chunk is a String * @param {function} callback Callback for when this chunk of data is flushed * @return {null} */ /** * GridStoreStream stream data event, fired for each document in the cursor. * * @event GridStoreStream#data * @type {object} */ /** * GridStoreStream stream end event * * @event GridStoreStream#end * @type {null} */ /** * GridStoreStream stream close event * * @event GridStoreStream#close * @type {null} */ /** * GridStoreStream stream readable event * * @event GridStoreStream#readable * @type {null} */ /** * GridStoreStream stream drain event * * @event GridStoreStream#drain * @type {null} */ /** * GridStoreStream stream finish event * * @event GridStoreStream#finish * @type {null} */ /** * GridStoreStream stream pipe event * * @event GridStoreStream#pipe * @type {null} */ /** * GridStoreStream stream unpipe event * * @event GridStoreStream#unpipe * @type {null} */ /** * GridStoreStream stream error event * * @event GridStoreStream#error * @type {null} */ /** * @ignore */ module.exports = GridStore; }).call(this,require('_process')) },{"../collection":383,"../metadata":392,"../utils":399,"./chunk":390,"_process":507,"buffer":144,"fs":123,"mongodb-core":345,"stream":548,"util":563}],392:[function(require,module,exports){ 'use strict'; var f = require('util').format; var Define = function(name, object, stream) { this.name = name; this.object = object; this.stream = typeof stream === 'boolean' ? stream : false; this.instrumentations = {}; }; Define.prototype.classMethod = function(name, options) { var keys = Object.keys(options).sort(); var key = generateKey(keys, options); // Add a list of instrumentations if (this.instrumentations[key] == null) { this.instrumentations[key] = { methods: [], options: options }; } // Push to list of method for this instrumentation this.instrumentations[key].methods.push(name); }; var generateKey = function(keys, options) { var parts = []; for (var i = 0; i < keys.length; i++) { parts.push(f('%s=%s', keys[i], options[keys[i]])); } return parts.join(); }; Define.prototype.staticMethod = function(name, options) { options.static = true; var keys = Object.keys(options).sort(); var key = generateKey(keys, options); // Add a list of instrumentations if (this.instrumentations[key] == null) { this.instrumentations[key] = { methods: [], options: options }; } // Push to list of method for this instrumentation this.instrumentations[key].methods.push(name); }; Define.prototype.generate = function() { // Generate the return object var object = { name: this.name, obj: this.object, stream: this.stream, instrumentations: [] }; for (var name in this.instrumentations) { object.instrumentations.push(this.instrumentations[name]); } return object; }; module.exports = Define; },{"util":563}],393:[function(require,module,exports){ (function (Buffer,process){ 'use strict'; var parse = require('./url_parser'), Server = require('./topologies/server'), Mongos = require('./topologies/mongos'), ReplSet = require('./topologies/replset'), EventEmitter = require('events').EventEmitter, inherits = require('util').inherits, Define = require('./metadata'), ReadPreference = require('mongodb-core').ReadPreference, Logger = require('mongodb-core').Logger, MongoError = require('mongodb-core').MongoError, handleCallback = require('./utils').handleCallback, Db = require('./db'), f = require('util').format, shallowClone = require('./utils').shallowClone, authenticate = require('./authenticate'), ServerSessionPool = require('mongodb-core').Sessions.ServerSessionPool, executeOperation = require('./utils').executeOperation; /** * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. * * @example * // Connect using a MongoClient instance * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * const mongoClient = new MongoClient(url); * mongoClient.connect(function(err, client) { * const db = client.db(dbName); * client.close(); * }); * * @example * // Connect using the MongoClient.connect static method * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * const db = client.db(dbName); * client.close(); * }); */ var validOptionNames = [ 'poolSize', 'ssl', 'sslValidate', 'sslCA', 'sslCert', 'sslKey', 'sslPass', 'sslCRL', 'autoReconnect', 'noDelay', 'keepAlive', 'keepAliveInitialDelay', 'connectTimeoutMS', 'family', 'socketTimeoutMS', 'reconnectTries', 'reconnectInterval', 'ha', 'haInterval', 'replicaSet', 'secondaryAcceptableLatencyMS', 'acceptableLatencyMS', 'connectWithNoPrimary', 'authSource', 'w', 'wtimeout', 'j', 'forceServerObjectId', 'serializeFunctions', 'ignoreUndefined', 'raw', 'bufferMaxEntries', 'readPreference', 'pkFactory', 'promiseLibrary', 'readConcern', 'maxStalenessSeconds', 'loggerLevel', 'logger', 'promoteValues', 'promoteBuffers', 'promoteLongs', 'domainsEnabled', 'checkServerIdentity', 'validateOptions', 'appname', 'auth', 'user', 'password', 'authMechanism', 'compression', 'fsync', 'readPreferenceTags', 'numberOfRetries', 'auto_reconnect', 'minSize' ]; var ignoreOptionNames = ['native_parser']; var legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; function validOptions(options) { var _validOptions = validOptionNames.concat(legacyOptionNames); for (var name in options) { if (ignoreOptionNames.indexOf(name) !== -1) { continue; } if (_validOptions.indexOf(name) === -1 && options.validateOptions) { return new MongoError(f('option %s is not supported', name)); } else if (_validOptions.indexOf(name) === -1) { console.warn(f('the options [%s] is not supported', name)); } if (legacyOptionNames.indexOf(name) !== -1) { console.warn( f( 'the server/replset/mongos options are deprecated, ' + 'all their options are supported at the top level of the options object [%s]', validOptionNames ) ); } } } /** * Creates a new MongoClient instance * @class * @param {string} url The connection URI string * @param {object} [options] Optional settings * @param {number} [options.poolSize=5] The maximum size of the individual server pool * @param {boolean} [options.ssl=false] Enable SSL connection. * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting * @param {number} [options.family=null] Version of IP stack. Can be 4, 6 or null (default). * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry * @param {string} [options.replicaSet=undefined] The Replicaset set name * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available * @param {string} [options.authSource=undefined] Define the database to authenticate against * @param {(number|string)} [options.w=null] The write concern * @param {number} [options.wtimeout=null] The write concern timeout * @param {boolean} [options.j=false] Specify a journal write concern * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields * @param {boolean} [options.raw=false] Return document results as raw BSON buffers * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {object} [options.readConcern=null] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) * @param {object} [options.logger=undefined] Custom logger object * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections * @param {string} [options.auth.user=undefined] The username for auth * @param {string} [options.auth.password=undefined] The password for auth * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR * @param {object} [options.compression=null] Type of compression to use: snappy or zlib * @param {boolean} [options.fsync=false] Specify a file sync write concern * @param {array} [options.readPreferenceTags=null] Read preference tags * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances * @param {MongoClient~connectCallback} [callback] The command result callback * @return {MongoClient} a MongoClient instance */ function MongoClient(url, options) { if (!(this instanceof MongoClient)) return new MongoClient(); // Set up event emitter EventEmitter.call(this); // The internal state this.s = { url: url, options: options || {}, promiseLibrary: null, dbCache: {}, sessions: [] }; // Get the promiseLibrary var promiseLibrary = this.s.options.promiseLibrary || Promise; // Add the promise to the internal state this.s.promiseLibrary = promiseLibrary; } /** * @ignore */ inherits(MongoClient, EventEmitter); var define = (MongoClient.define = new Define('MongoClient', MongoClient, false)); /** * The callback format for results * @callback MongoClient~connectCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {MongoClient} client The connected client. */ /** * Connect to MongoDB using a url as documented at * * docs.mongodb.org/manual/reference/connection-string/ * * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver * * @method * @param {MongoClient~connectCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ MongoClient.prototype.connect = function(callback) { // Validate options object var err = validOptions(this.s.options); if (typeof callback === 'string') { throw new TypeError('`connect` only accepts a callback'); } return executeOperation(this, connectOp, [this, err, callback], { skipSessions: true }); }; const connectOp = (self, err, callback) => { // Did we have a validation error if (err) return callback(err); // Fallback to callback based connect connect(self, self.s.url, self.s.options, function(err) { if (err) return callback(err); callback(null, self); }); }; define.classMethod('close', { callback: true, promise: true, returns: [MongoClient] }); /** * Logout user from server, fire off on all connections and remove all auth info * @method * @param {object} [options=null] Optional settings. * @param {string} [options.dbName=null] Logout against different database than current. * @param {Db~resultCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ MongoClient.prototype.logout = function(options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Establish the correct database name var dbName = this.s.options.authSource ? this.s.options.authSource : this.s.options.dbName; return executeOperation(this, logout, [this, dbName, callback], { skipSessions: true }); }; const logout = (self, dbName, callback) => { self.topology.logout(dbName, function(err) { if (err) return callback(err); callback(null, true); }); }; define.classMethod('logout', { callback: true, promise: true }); /** * Close the db and its underlying connections * @method * @param {boolean} force Force close, emitting no events * @param {Db~noResultCallback} [callback] The result callback * @return {Promise} returns Promise if no callback passed */ MongoClient.prototype.close = function(force, callback) { var self = this; if (typeof force === 'function') (callback = force), (force = false); // Close the topologu connection this.topology.close(force); // Emit close event self.emit('close', self); // Fire close event on any cached db instances for (var name in this.s.dbCache) { this.s.dbCache[name].emit('close'); } // Remove listeners after emit self.removeAllListeners('close'); // If we have sessions, we want to send a single `endSessions` command for them, // and then individually clean them up. They will be removed from the internal state // when they emit their `ended` events. if (this.s.sessions.length) { this.topology.endSessions(this.s.sessions); this.s.sessions.forEach(session => session.endSession({ skipCommand: true })); } // Callback after next event loop tick if (typeof callback === 'function') return process.nextTick(function() { handleCallback(callback, null); }); // Return dummy promise return new this.s.promiseLibrary(function(resolve) { resolve(); }); }; define.classMethod('close', { callback: true, promise: true }); /** * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are * related in a parent-child relationship to the original instance so that events are correctly emitted on child * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. * You can control these behaviors with the options noListener and returnNonCachedInstance. * * @method * @param {string} name The name of the database we want to use. * @param {object} [options=null] Optional settings. * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created * @return {Db} */ MongoClient.prototype.db = function(dbName, options) { options = options || {}; // Copy the options and add out internal override of the not shared flag var finalOptions = Object.assign({}, this.s.options, options); // Do we have the db in the cache already if (this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) { return this.s.dbCache[dbName]; } // Add promiseLibrary finalOptions.promiseLibrary = this.s.promiseLibrary; // If no topology throw an error message if (!this.topology) { throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); } // Return the db object var db = new Db(dbName, this.topology, finalOptions); // Add the db to the cache this.s.dbCache[dbName] = db; // Return the database return db; }; /** * Check if MongoClient is connected * * @method * @param {string} name The name of the database we want to use. * @param {object} [options=null] Optional settings. * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created * @return {boolean} */ MongoClient.prototype.isConnected = function(options) { options = options || {}; if (!this.topology) return false; return this.topology.isConnected(options); }; /** * Connect to MongoDB using a url as documented at * * docs.mongodb.org/manual/reference/connection-string/ * * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver * * @method * @static * @param {string} url The connection URI string * @param {object} [options] Optional settings * @param {number} [options.poolSize=5] The maximum size of the individual server pool * @param {boolean} [options.ssl=false] Enable SSL connection. * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances * @param {boolean} [options.noDelay=true] TCP Connection no delay * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting * @param {number} [options.family=null] Version of IP stack. Can be 4, 6 or null (default). * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry * @param {string} [options.replicaSet=undefined] The Replicaset set name * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available * @param {string} [options.authSource=undefined] Define the database to authenticate against * @param {(number|string)} [options.w=null] The write concern * @param {number} [options.wtimeout=null] The write concern timeout * @param {boolean} [options.j=false] Specify a journal write concern * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields * @param {boolean} [options.raw=false] Return document results as raw BSON buffers * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible * @param {object} [options.readConcern=null] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) * @param {object} [options.logger=undefined] Custom logger object * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections * @param {string} [options.auth.user=undefined] The username for auth * @param {string} [options.auth.password=undefined] The password for auth * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR * @param {object} [options.compression=null] Type of compression to use: snappy or zlib * @param {boolean} [options.fsync=false] Specify a file sync write concern * @param {array} [options.readPreferenceTags=null] Read preference tags * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances * @param {MongoClient~connectCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ MongoClient.connect = function(url, options, callback) { var args = Array.prototype.slice.call(arguments, 1); callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; options = args.length ? args.shift() : null; options = options || {}; // Create client var mongoClient = new MongoClient(url, options); // Execute the connect method return mongoClient.connect(callback); }; define.staticMethod('connect', { callback: true, promise: true }); /** * Starts a new session on the server * * @param {object} [options] optional settings for a driver session * @param {MongoClient~sessionCallback} [callback] The callback called with a newly establish session, or an error if one occurred * @return {Promise} if no callback is specified, a promise will be returned for the newly established session */ MongoClient.prototype.startSession = function(options) { options = options || {}; if (!this.topology) { throw new MongoError('Must connect to a server before calling this method'); } if (!this.topology.hasSessionSupport()) { throw new MongoError('Current topology does not support sessions'); } const session = this.topology.startSession(options); session.once('ended', () => { this.s.sessions = this.s.sessions.filter(s => s.equals(session)); }); this.s.sessions.push(session); return session; }; var mergeOptions = function(target, source, flatten) { for (var name in source) { if (source[name] && typeof source[name] === 'object' && flatten) { target = mergeOptions(target, source[name], flatten); } else { target[name] = source[name]; } } return target; }; var createUnifiedOptions = function(finalOptions, options) { var childOptions = [ 'mongos', 'server', 'db', 'replset', 'db_options', 'server_options', 'rs_options', 'mongos_options' ]; var noMerge = ['readconcern', 'compression']; for (var name in options) { if (noMerge.indexOf(name.toLowerCase()) !== -1) { finalOptions[name] = options[name]; } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { finalOptions = mergeOptions(finalOptions, options[name], false); } else { if ( options[name] && typeof options[name] === 'object' && !Buffer.isBuffer(options[name]) && !Array.isArray(options[name]) ) { finalOptions = mergeOptions(finalOptions, options[name], true); } else { finalOptions[name] = options[name]; } } } return finalOptions; }; function translateOptions(options) { // If we have a readPreference passed in by the db options if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { options.readPreference = new ReadPreference(options.readPreference || options.read_preference); } // Do we have readPreference tags, add them if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; } // Do we have maxStalenessSeconds if (options.maxStalenessSeconds) { options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; } // Set the socket and connection timeouts if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; // Create server instances return options.servers.map(function(serverObj) { return serverObj.domain_socket ? new Server(serverObj.domain_socket, 27017, options) : new Server(serverObj.host, serverObj.port, options); }); } var events = [ 'timeout', 'close', 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', 'topologyClosed', 'topologyDescriptionChanged', 'joined', 'left', 'ping', 'ha', 'all', 'fullsetup' ]; // // Collect all events in order from SDAM // function collectEvents(self, topology) { var collectedEvents = []; if (self instanceof MongoClient) { events.forEach(function(event) { topology.on(event, function(object1, object2) { collectedEvents.push({ event: event, object1: object1, object2: object2 }); }); }); } return collectedEvents; } // // Clear out all event // function clearAllEvents(topology) { events.forEach(function(event) { topology.removeAllListeners(event); }); } // // Replay any events due to single server connection switching to Mongos // function replayEvents(self, events) { for (var i = 0; i < events.length; i++) { self.emit(events[i].event, events[i].object1, events[i].object2); } } function relayEvents(self, topology) { var events = [ 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', 'topologyClosed', 'topologyDescriptionChanged', 'joined', 'left', 'ping', 'ha' ]; events.forEach(function(event) { topology.on(event, function(object1, object2) { self.emit(event, object1, object2); }); }); } function assignTopology(client, topology) { client.topology = topology; topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); } function createServer(self, options, callback) { // Pass in the promise library options.promiseLibrary = self.s.promiseLibrary; // Set default options var servers = translateOptions(options); // Propagate the events to the client var collectedEvents = collectEvents(self, servers[0]); // Connect to topology servers[0].connect(function(err, topology) { if (err) return callback(err); // Clear out all the collected event listeners clearAllEvents(servers[0]); // Relay all the events relayEvents(self, servers[0]); // Add listeners addListeners(self, servers[0]); // Check if we are really speaking to a mongos var ismaster = topology.lastIsMaster(); // Set the topology assignTopology(self, topology); // Do we actually have a mongos if (ismaster && ismaster.msg === 'isdbgrid') { // Destroy the current connection topology.close(); // Create mongos connection instead return createMongos(self, options, callback); } // Fire all the events replayEvents(self, collectedEvents); // Otherwise callback callback(err, topology); }); } function createReplicaset(self, options, callback) { // Pass in the promise library options.promiseLibrary = self.s.promiseLibrary; // Set default options var servers = translateOptions(options); // Create the topology var topology = new ReplSet(servers, options); // Add listeners addListeners(self, topology); // Propagate the events to the client relayEvents(self, topology); // Open the connection topology.connect(options, function(err, topology) { if (err) return callback(err); assignTopology(self, topology); callback(null, topology); }); } function createMongos(self, options, callback) { // Pass in the promise library options.promiseLibrary = self.s.promiseLibrary; // Set default options var servers = translateOptions(options); // Create the topology var topology = new Mongos(servers, options); // Add listeners addListeners(self, topology); // Propagate the events to the client relayEvents(self, topology); // Open the connection topology.connect(options, function(err, topology) { if (err) return callback(err); assignTopology(self, topology); callback(null, topology); }); } function createListener(self, event) { return function(v1, v2) { if (event === 'open' || event === 'fullsetup' || event === 'all' || event === 'reconnect') { return self.emit(event, self); } self.emit(event, v1, v2); }; } function addListeners(self, topology) { topology.on('authenticated', createListener(self, 'authenticated')); topology.on('error', createListener(self, 'error')); topology.on('timeout', createListener(self, 'timeout')); topology.on('close', createListener(self, 'close')); topology.on('parseError', createListener(self, 'parseError')); topology.once('open', createListener(self, 'open')); topology.once('fullsetup', createListener(self, 'fullsetup')); topology.once('all', createListener(self, 'all')); topology.on('reconnect', createListener(self, 'reconnect')); } function connectHandler(client, options, callback) { return function(err, topology) { if (err) { return process.nextTick(function() { try { callback(err, null); } catch (err) { if (topology) topology.close(); throw err; } }); } // No authentication just reconnect if (!options.auth) { return process.nextTick(function() { try { callback(err, topology); } catch (err) { if (topology) topology.close(); throw err; } }); } // Authenticate authenticate(client, options.user, options.password, options, function(err, success) { if (success) { process.nextTick(function() { try { callback(null, topology); } catch (err) { if (topology) topology.close(); throw err; } }); } else { if (topology) topology.close(); process.nextTick(function() { try { callback(err ? err : new Error('Could not authenticate user ' + options.auth[0]), null); } catch (err) { if (topology) topology.close(); throw err; } }); } }); }; } /* * Connect using MongoClient */ var connect = function(self, url, options, callback) { options = options || {}; options = shallowClone(options); // If callback is null throw an exception if (callback == null) { throw new Error('no callback function provided'); } // Get a logger for MongoClient var logger = Logger('MongoClient', options); // Did we pass in a Server/ReplSet/Mongos if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { // Set the topology assignTopology(self, url); // Add listeners addListeners(self, url); // Connect return url.connect( options, connectHandler(self, options, function(err, topology) { if (err) return connectCallback(err, topology); if (options.user || options.password || options.authMechanism) { return authenticate(self, options.user, options.password, options, function(err) { if (err) return connectCallback(err, topology); connectCallback(err, topology); }); } connectCallback(err, topology); }) ); } parse(url, options, function(err, object) { // Do not attempt to connect if parsing error if (err) return callback(err); // Parse the string var _finalOptions = createUnifiedOptions({}, object); _finalOptions = mergeOptions(_finalOptions, object, false); _finalOptions = createUnifiedOptions(_finalOptions, options); // Check if we have connection and socket timeout set if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; if (_finalOptions.db_options && _finalOptions.db_options.auth) { delete _finalOptions.db_options.auth; } // Store the merged options object self.s.options = _finalOptions; // Failure modes if (object.servers.length === 0) { return callback(new Error('connection string must contain at least one seed host')); } // Do we have a replicaset then skip discovery and go straight to connectivity if (_finalOptions.replicaSet || _finalOptions.rs_name) { return createReplicaset( self, _finalOptions, connectHandler(self, _finalOptions, connectCallback) ); } else if (object.servers.length > 1) { return createMongos( self, _finalOptions, connectHandler(self, _finalOptions, connectCallback) ); } else { return createServer( self, _finalOptions, connectHandler(self, _finalOptions, connectCallback) ); } }); function connectCallback(err, topology) { if (err && err.message === 'no mongos proxies found in seed list') { if (logger.isWarn()) { logger.warn( f( 'seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name' ) ); } // Return a more specific error message for MongoClient.connect return callback( new MongoError( 'seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name' ) ); } // Return the error and db instance callback(err, topology); } }; module.exports = MongoClient; }).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) },{"../../is-buffer/index.js":335,"./authenticate":378,"./db":386,"./metadata":392,"./topologies/mongos":394,"./topologies/replset":395,"./topologies/server":396,"./url_parser":398,"./utils":399,"_process":507,"events":316,"mongodb-core":345,"util":563}],394:[function(require,module,exports){ (function (process){ 'use strict'; var ServerCapabilities = require('./topology_base').ServerCapabilities, TopologyBase = require('./topology_base').TopologyBase, MongoError = require('mongodb-core').MongoError, CMongos = require('mongodb-core').Mongos, Cursor = require('../cursor'), AggregationCursor = require('../aggregation_cursor'), CommandCursor = require('../command_cursor'), Define = require('../metadata'), Server = require('./server'), Store = require('./topology_base').Store, MAX_JS_INT = require('../utils').MAX_JS_INT, translateOptions = require('../utils').translateOptions, filterOptions = require('../utils').filterOptions, mergeOptions = require('../utils').mergeOptions; /** * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is * used to construct connections. * * **Mongos Should not be used, use MongoClient.connect** */ // Allowed parameters var legalOptionNames = [ 'ha', 'haInterval', 'acceptableLatencyMS', 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate', 'sslCA', 'sslCRL', 'sslCert', 'ciphers', 'ecdhCurve', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries', 'store', 'auto_reconnect', 'autoReconnect', 'emitError', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS', 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled', 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'promiseLibrary' ]; /** * Creates a new Mongos instance * @class * @deprecated * @param {Server[]} servers A seedlist of servers participating in the replicaset. * @param {object} [options=null] Optional settings. * @param {booelan} [options.ha=true] Turn on high availability monitoring. * @param {number} [options.haInterval=5000] Time between each replicaset status check. * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) * @param {array} [options.sslCRL=null] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) * @param {string} [options.ciphers=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. * @param {string} [options.ecdhCurve=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. * @param {object} [options.socketOptions=null] Socket options * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @fires Mongos#connect * @fires Mongos#ha * @fires Mongos#joined * @fires Mongos#left * @fires Mongos#fullsetup * @fires Mongos#open * @fires Mongos#close * @fires Mongos#error * @fires Mongos#timeout * @fires Mongos#parseError * @property {string} parserType the parser type used (c++ or js). * @return {Mongos} a Mongos instance. */ class Mongos extends TopologyBase { constructor(servers, options) { super(); options = options || {}; var self = this; // Filter the options options = filterOptions(options, legalOptionNames); // Ensure all the instances are Server for (var i = 0; i < servers.length; i++) { if (!(servers[i] instanceof Server)) { throw MongoError.create({ message: 'all seed list instances must be of the Server type', driver: true }); } } // Stored options var storeOptions = { force: false, bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT }; // Shared global store var store = options.store || new Store(self, storeOptions); // Build seed list var seedlist = servers.map(function(x) { return { host: x.host, port: x.port }; }); // Get the reconnect option var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; // Clone options var clonedOptions = mergeOptions( {}, { disconnectHandler: store, cursorFactory: Cursor, reconnect: reconnect, emitError: typeof options.emitError === 'boolean' ? options.emitError : true, size: typeof options.poolSize === 'number' ? options.poolSize : 5 } ); // Translate any SSL options and other connectivity options clonedOptions = translateOptions(clonedOptions, options); // Socket options var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 ? options.socketOptions : options; // Translate all the options to the mongodb-core ones clonedOptions = translateOptions(clonedOptions, socketOptions); // Build default client information clonedOptions.clientInfo = this.clientInfo; // Do we have an application specific string if (options.appname) { clonedOptions.clientInfo.application = { name: options.appname }; } // Internal state this.s = { // Create the Mongos coreTopology: new CMongos(seedlist, clonedOptions), // Server capabilities sCapabilities: null, // Debug turned on debug: clonedOptions.debug, // Store option defaults storeOptions: storeOptions, // Cloned options clonedOptions: clonedOptions, // Actual store of callbacks store: store, // Options options: options, // Server Session Pool sessionPool: null, // Promise library promiseLibrary: options.promiseLibrary || Promise }; } // Connect connect(_options, callback) { var self = this; if ('function' === typeof _options) (callback = _options), (_options = {}); if (_options == null) _options = {}; if (!('function' === typeof callback)) callback = null; _options = Object.assign({}, this.s.clonedOptions, _options); self.s.options = _options; // Update bufferMaxEntries self.s.storeOptions.bufferMaxEntries = typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; // Error handler var connectErrorHandler = function() { return function(err) { // Remove all event handlers var events = ['timeout', 'error', 'close']; events.forEach(function(e) { self.removeListener(e, connectErrorHandler); }); self.s.coreTopology.removeListener('connect', connectErrorHandler); // Force close the topology self.close(true); // Try to callback try { callback(err); } catch (err) { process.nextTick(function() { throw err; }); } }; }; // Actual handler var errorHandler = function(event) { return function(err) { if (event !== 'error') { self.emit(event, err); } }; }; // Error handler var reconnectHandler = function() { self.emit('reconnect'); self.s.store.execute(); }; // relay the event var relay = function(event) { return function(t, server) { self.emit(event, t, server); }; }; // Connect handler var connectHandler = function() { // Clear out all the current handlers left over var events = ['timeout', 'error', 'close', 'fullsetup']; events.forEach(function(e) { self.s.coreTopology.removeAllListeners(e); }); // Set up listeners self.s.coreTopology.once('timeout', errorHandler('timeout')); self.s.coreTopology.once('error', errorHandler('error')); self.s.coreTopology.once('close', errorHandler('close')); // Set up serverConfig listeners self.s.coreTopology.on('fullsetup', function() { self.emit('fullsetup', self); }); // Emit open event self.emit('open', null, self); // Return correctly try { callback(null, self); } catch (err) { process.nextTick(function() { throw err; }); } }; // Clear out all the current handlers left over var events = [ 'timeout', 'error', 'close', 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', 'topologyClosed', 'topologyDescriptionChanged' ]; events.forEach(function(e) { self.s.coreTopology.removeAllListeners(e); }); // Set up SDAM listeners self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); self.s.coreTopology.on('serverOpening', relay('serverOpening')); self.s.coreTopology.on('serverClosed', relay('serverClosed')); self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); // Set up listeners self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); self.s.coreTopology.once('error', connectErrorHandler('error')); self.s.coreTopology.once('close', connectErrorHandler('close')); self.s.coreTopology.once('connect', connectHandler); // Join and leave events self.s.coreTopology.on('joined', relay('joined')); self.s.coreTopology.on('left', relay('left')); // Reconnect server self.s.coreTopology.on('reconnect', reconnectHandler); // Start connection self.s.coreTopology.connect(_options); } } Object.defineProperty(Mongos.prototype, 'haInterval', { enumerable: true, get: function() { return this.s.coreTopology.s.haInterval; } }); const define = (Mongos.define = new Define('Mongos', Mongos, false)); define.classMethod('capabilities', { callback: false, promise: false, returns: [ServerCapabilities] }); define.classMethod('command', { callback: true, promise: false }); define.classMethod('insert', { callback: true, promise: false }); define.classMethod('update', { callback: true, promise: false }); define.classMethod('remove', { callback: true, promise: false }); define.classMethod('isConnected', { callback: false, promise: false, returns: [Boolean] }); define.classMethod('isDestroyed', { callback: false, promise: false, returns: [Boolean] }); define.classMethod('cursor', { callback: false, promise: false, returns: [Cursor, AggregationCursor, CommandCursor] }); define.classMethod('close', { callback: false, promise: false }); define.classMethod('auth', { callback: true, promise: false }); define.classMethod('logout', { callback: true, promise: false }); define.classMethod('connections', { callback: false, promise: false, returns: [Array] }); /** * A mongos connect event, used to verify that the connection is up and running * * @event Mongos#connect * @type {Mongos} */ /** * The mongos high availability event * * @event Mongos#ha * @type {function} * @param {string} type The stage in the high availability event (start|end) * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only * @param {number} data.id The id for this high availability request * @param {object} data.state An object containing the information about the current replicaset */ /** * A server member left the mongos set * * @event Mongos#left * @type {function} * @param {string} type The type of member that left (primary|secondary|arbiter) * @param {Server} server The server object that left */ /** * A server member joined the mongos set * * @event Mongos#joined * @type {function} * @param {string} type The type of member that joined (primary|secondary|arbiter) * @param {Server} server The server object that joined */ /** * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. * * @event Mongos#fullsetup * @type {Mongos} */ /** * Mongos open event, emitted when mongos can start processing commands. * * @event Mongos#open * @type {Mongos} */ /** * Mongos close event * * @event Mongos#close * @type {object} */ /** * Mongos error event, emitted if there is an error listener. * * @event Mongos#error * @type {MongoError} */ /** * Mongos timeout event * * @event Mongos#timeout * @type {object} */ /** * Mongos parseError event * * @event Mongos#parseError * @type {object} */ module.exports = Mongos; }).call(this,require('_process')) },{"../aggregation_cursor":376,"../command_cursor":384,"../cursor":385,"../metadata":392,"../utils":399,"./server":396,"./topology_base":397,"_process":507,"mongodb-core":345}],395:[function(require,module,exports){ (function (process){ 'use strict'; var Server = require('./server'), Cursor = require('../cursor'), AggregationCursor = require('../aggregation_cursor'), CommandCursor = require('../command_cursor'), MongoError = require('mongodb-core').MongoError, ServerCapabilities = require('./topology_base').ServerCapabilities, TopologyBase = require('./topology_base').TopologyBase, Store = require('./topology_base').Store, Define = require('../metadata'), CReplSet = require('mongodb-core').ReplSet, MAX_JS_INT = require('../utils').MAX_JS_INT, translateOptions = require('../utils').translateOptions, filterOptions = require('../utils').filterOptions, mergeOptions = require('../utils').mergeOptions; /** * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is * used to construct connections. * * **ReplSet Should not be used, use MongoClient.connect** */ // Allowed parameters var legalOptionNames = [ 'ha', 'haInterval', 'replicaSet', 'rs_name', 'secondaryAcceptableLatencyMS', 'connectWithNoPrimary', 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate', 'sslCA', 'sslCert', 'ciphers', 'ecdhCurve', 'sslCRL', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries', 'store', 'auto_reconnect', 'autoReconnect', 'emitError', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS', 'strategy', 'debug', 'family', 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled', 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'maxStalenessSeconds', 'promiseLibrary', 'minSize' ]; /** * Creates a new ReplSet instance * @class * @deprecated * @param {Server[]} servers A seedlist of servers participating in the replicaset. * @param {object} [options=null] Optional settings. * @param {boolean} [options.ha=true] Turn on high availability monitoring. * @param {number} [options.haInterval=10000] Time between each replicaset status check. * @param {string} [options.replicaSet] The name of the replicaset to connect to. * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) * @param {array} [options.sslCRL=null] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. * @param {string} [options.ciphers=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. * @param {string} [options.ecdhCurve=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. * @param {object} [options.socketOptions=null] Socket options * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); * @fires ReplSet#connect * @fires ReplSet#ha * @fires ReplSet#joined * @fires ReplSet#left * @fires ReplSet#fullsetup * @fires ReplSet#open * @fires ReplSet#close * @fires ReplSet#error * @fires ReplSet#timeout * @fires ReplSet#parseError * @property {string} parserType the parser type used (c++ or js). * @return {ReplSet} a ReplSet instance. */ class ReplSet extends TopologyBase { constructor(servers, options) { super(); options = options || {}; var self = this; // Filter the options options = filterOptions(options, legalOptionNames); // Ensure all the instances are Server for (var i = 0; i < servers.length; i++) { if (!(servers[i] instanceof Server)) { throw MongoError.create({ message: 'all seed list instances must be of the Server type', driver: true }); } } // Stored options var storeOptions = { force: false, bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT }; // Shared global store var store = options.store || new Store(self, storeOptions); // Build seed list var seedlist = servers.map(function(x) { return { host: x.host, port: x.port }; }); // Clone options var clonedOptions = mergeOptions( {}, { disconnectHandler: store, cursorFactory: Cursor, reconnect: false, emitError: typeof options.emitError === 'boolean' ? options.emitError : true, size: typeof options.poolSize === 'number' ? options.poolSize : 5 } ); // Translate any SSL options and other connectivity options clonedOptions = translateOptions(clonedOptions, options); // Socket options var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 ? options.socketOptions : options; // Translate all the options to the mongodb-core ones clonedOptions = translateOptions(clonedOptions, socketOptions); // Build default client information clonedOptions.clientInfo = this.clientInfo; // Do we have an application specific string if (options.appname) { clonedOptions.clientInfo.application = { name: options.appname }; } // Create the ReplSet var coreTopology = new CReplSet(seedlist, clonedOptions); // Listen to reconnect event coreTopology.on('reconnect', function() { self.emit('reconnect'); store.execute(); }); // Internal state this.s = { // Replicaset coreTopology: coreTopology, // Server capabilities sCapabilities: null, // Debug tag tag: options.tag, // Store options storeOptions: storeOptions, // Cloned options clonedOptions: clonedOptions, // Store store: store, // Options options: options, // Server Session Pool sessionPool: null, // Promise library promiseLibrary: options.promiseLibrary || Promise }; // Debug if (clonedOptions.debug) { // Last ismaster Object.defineProperty(this, 'replset', { enumerable: true, get: function() { return coreTopology; } }); } } // Connect method connect(_options, callback) { var self = this; if ('function' === typeof _options) (callback = _options), (_options = {}); if (_options == null) _options = {}; if (!('function' === typeof callback)) callback = null; _options = Object.assign({}, this.s.clonedOptions, _options); self.s.options = _options; // Update bufferMaxEntries self.s.storeOptions.bufferMaxEntries = typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; // Actual handler var errorHandler = function(event) { return function(err) { if (event !== 'error') { self.emit(event, err); } }; }; // Clear out all the current handlers left over var events = [ 'timeout', 'error', 'close', 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', 'topologyClosed', 'topologyDescriptionChanged', 'joined', 'left', 'ping', 'ha' ]; events.forEach(function(e) { self.s.coreTopology.removeAllListeners(e); }); // relay the event var relay = function(event) { return function(t, server) { self.emit(event, t, server); }; }; // Replset events relay var replsetRelay = function(event) { return function(t, server) { self.emit(event, t, server.lastIsMaster(), server); }; }; // Relay ha var relayHa = function(t, state) { self.emit('ha', t, state); if (t === 'start') { self.emit('ha_connect', t, state); } else if (t === 'end') { self.emit('ha_ismaster', t, state); } }; // Set up serverConfig listeners self.s.coreTopology.on('joined', replsetRelay('joined')); self.s.coreTopology.on('left', relay('left')); self.s.coreTopology.on('ping', relay('ping')); self.s.coreTopology.on('ha', relayHa); // Set up SDAM listeners self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); self.s.coreTopology.on('serverOpening', relay('serverOpening')); self.s.coreTopology.on('serverClosed', relay('serverClosed')); self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); self.s.coreTopology.on('fullsetup', function() { self.emit('fullsetup', self, self); }); self.s.coreTopology.on('all', function() { self.emit('all', null, self); }); // Connect handler var connectHandler = function() { // Set up listeners self.s.coreTopology.once('timeout', errorHandler('timeout')); self.s.coreTopology.once('error', errorHandler('error')); self.s.coreTopology.once('close', errorHandler('close')); // Emit open event self.emit('open', null, self); // Return correctly try { callback(null, self); } catch (err) { process.nextTick(function() { throw err; }); } }; // Error handler var connectErrorHandler = function() { return function(err) { ['timeout', 'error', 'close'].forEach(function(e) { self.s.coreTopology.removeListener(e, connectErrorHandler); }); self.s.coreTopology.removeListener('connect', connectErrorHandler); // Destroy the replset self.s.coreTopology.destroy(); // Try to callback try { callback(err); } catch (err) { if (!self.s.coreTopology.isConnected()) process.nextTick(function() { throw err; }); } }; }; // Set up listeners self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); self.s.coreTopology.once('error', connectErrorHandler('error')); self.s.coreTopology.once('close', connectErrorHandler('close')); self.s.coreTopology.once('connect', connectHandler); // Start connection self.s.coreTopology.connect(_options); } close(forceClosed) { var self = this; // Call destroy on the topology this.s.coreTopology.destroy({ force: typeof forceClosed === 'boolean' ? forceClosed : false }); // We need to wash out all stored processes if (forceClosed === true) { this.s.storeOptions.force = forceClosed; this.s.store.flush(); } var events = ['timeout', 'error', 'close', 'joined', 'left']; events.forEach(function(e) { self.removeAllListeners(e); }); } } Object.defineProperty(ReplSet.prototype, 'haInterval', { enumerable: true, get: function() { return this.s.coreTopology.s.haInterval; } }); const define = (ReplSet.define = new Define('ReplSet', ReplSet, false)); define.classMethod('capabilities', { callback: false, promise: false, returns: [ServerCapabilities] }); define.classMethod('command', { callback: true, promise: false }); define.classMethod('insert', { callback: true, promise: false }); define.classMethod('update', { callback: true, promise: false }); define.classMethod('remove', { callback: true, promise: false }); define.classMethod('isConnected', { callback: false, promise: false, returns: [Boolean] }); define.classMethod('cursor', { callback: false, promise: false, returns: [Cursor, AggregationCursor, CommandCursor] }); define.classMethod('close', { callback: false, promise: false }); define.classMethod('auth', { callback: true, promise: false }); define.classMethod('logout', { callback: true, promise: false }); define.classMethod('connections', { callback: false, promise: false, returns: [Array] }); /** * A replset connect event, used to verify that the connection is up and running * * @event ReplSet#connect * @type {ReplSet} */ /** * The replset high availability event * * @event ReplSet#ha * @type {function} * @param {string} type The stage in the high availability event (start|end) * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only * @param {number} data.id The id for this high availability request * @param {object} data.state An object containing the information about the current replicaset */ /** * A server member left the replicaset * * @event ReplSet#left * @type {function} * @param {string} type The type of member that left (primary|secondary|arbiter) * @param {Server} server The server object that left */ /** * A server member joined the replicaset * * @event ReplSet#joined * @type {function} * @param {string} type The type of member that joined (primary|secondary|arbiter) * @param {Server} server The server object that joined */ /** * ReplSet open event, emitted when replicaset can start processing commands. * * @event ReplSet#open * @type {Replset} */ /** * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. * * @event ReplSet#fullsetup * @type {Replset} */ /** * ReplSet close event * * @event ReplSet#close * @type {object} */ /** * ReplSet error event, emitted if there is an error listener. * * @event ReplSet#error * @type {MongoError} */ /** * ReplSet timeout event * * @event ReplSet#timeout * @type {object} */ /** * ReplSet parseError event * * @event ReplSet#parseError * @type {object} */ module.exports = ReplSet; }).call(this,require('_process')) },{"../aggregation_cursor":376,"../command_cursor":384,"../cursor":385,"../metadata":392,"../utils":399,"./server":396,"./topology_base":397,"_process":507,"mongodb-core":345}],396:[function(require,module,exports){ (function (process){ 'use strict'; var CServer = require('mongodb-core').Server, Cursor = require('../cursor'), AggregationCursor = require('../aggregation_cursor'), CommandCursor = require('../command_cursor'), ServerCapabilities = require('./topology_base').ServerCapabilities, TopologyBase = require('./topology_base').TopologyBase, Store = require('./topology_base').Store, Define = require('../metadata'), MongoError = require('mongodb-core').MongoError, MAX_JS_INT = require('../utils').MAX_JS_INT, translateOptions = require('../utils').translateOptions, filterOptions = require('../utils').filterOptions, mergeOptions = require('../utils').mergeOptions; /** * @fileOverview The **Server** class is a class that represents a single server topology and is * used to construct connections. * * **Server Should not be used, use MongoClient.connect** */ // Allowed parameters var legalOptionNames = [ 'ha', 'haInterval', 'acceptableLatencyMS', 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate', 'sslCA', 'sslCRL', 'sslCert', 'ciphers', 'ecdhCurve', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries', 'store', 'auto_reconnect', 'autoReconnect', 'emitError', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS', 'family', 'loggerLevel', 'logger', 'reconnectTries', 'reconnectInterval', 'monitoring', 'appname', 'domainsEnabled', 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'compression', 'promiseLibrary' ]; /** * Creates a new Server instance * @class * @deprecated * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. * @param {number} [port] The server port if IP4. * @param {object} [options=null] Optional settings. * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) * @param {array} [options.sslCRL=null] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) * @param {string} [options.ciphers=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. * @param {string} [options.ecdhCurve=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. * @param {object} [options.socketOptions=null] Socket options * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. * @fires Server#connect * @fires Server#close * @fires Server#error * @fires Server#timeout * @fires Server#parseError * @fires Server#reconnect * @property {string} parserType the parser type used (c++ or js). * @return {Server} a Server instance. */ class Server extends TopologyBase { constructor(host, port, options) { super(); var self = this; // Filter the options options = filterOptions(options, legalOptionNames); // Promise library const promiseLibrary = options.promiseLibrary; // Stored options var storeOptions = { force: false, bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT }; // Shared global store var store = options.store || new Store(self, storeOptions); // Detect if we have a socket connection if (host.indexOf('/') !== -1) { if (port != null && typeof port === 'object') { options = port; port = null; } } else if (port == null) { throw MongoError.create({ message: 'port must be specified', driver: true }); } // Get the reconnect option var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; // Clone options var clonedOptions = mergeOptions( {}, { host: host, port: port, disconnectHandler: store, cursorFactory: Cursor, reconnect: reconnect, emitError: typeof options.emitError === 'boolean' ? options.emitError : true, size: typeof options.poolSize === 'number' ? options.poolSize : 5 } ); // Translate any SSL options and other connectivity options clonedOptions = translateOptions(clonedOptions, options); // Socket options var socketOptions = options.socketOptions && Object.keys(options.socketOptions).length > 0 ? options.socketOptions : options; // Translate all the options to the mongodb-core ones clonedOptions = translateOptions(clonedOptions, socketOptions); // Build default client information clonedOptions.clientInfo = this.clientInfo; // Do we have an application specific string if (options.appname) { clonedOptions.clientInfo.application = { name: options.appname }; } // Define the internal properties this.s = { // Create an instance of a server instance from mongodb-core coreTopology: new CServer(clonedOptions), // Server capabilities sCapabilities: null, // Cloned options clonedOptions: clonedOptions, // Reconnect reconnect: clonedOptions.reconnect, // Emit error emitError: clonedOptions.emitError, // Pool size poolSize: clonedOptions.size, // Store Options storeOptions: storeOptions, // Store store: store, // Host host: host, // Port port: port, // Options options: options, // Server Session Pool sessionPool: null, // Promise library promiseLibrary: promiseLibrary || Promise }; } // Connect connect(_options, callback) { var self = this; if ('function' === typeof _options) (callback = _options), (_options = {}); if (_options == null) _options = this.s.clonedOptions; if (!('function' === typeof callback)) callback = null; _options = Object.assign({}, this.s.clonedOptions, _options); self.s.options = _options; // Update bufferMaxEntries self.s.storeOptions.bufferMaxEntries = typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; // Error handler var connectErrorHandler = function() { return function(err) { // Remove all event handlers var events = ['timeout', 'error', 'close']; events.forEach(function(e) { self.s.coreTopology.removeListener(e, connectHandlers[e]); }); self.s.coreTopology.removeListener('connect', connectErrorHandler); // Try to callback try { callback(err); } catch (err) { process.nextTick(function() { throw err; }); } }; }; // Actual handler var errorHandler = function(event) { return function(err) { if (event !== 'error') { self.emit(event, err); } }; }; // Error handler var reconnectHandler = function() { self.emit('reconnect', self); self.s.store.execute(); }; // Reconnect failed var reconnectFailedHandler = function(err) { self.emit('reconnectFailed', err); self.s.store.flush(err); }; // Destroy called on topology, perform cleanup var destroyHandler = function() { self.s.store.flush(); }; // relay the event var relay = function(event) { return function(t, server) { self.emit(event, t, server); }; }; // Connect handler var connectHandler = function() { // Clear out all the current handlers left over ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { self.s.coreTopology.removeAllListeners(e); }); // Set up listeners self.s.coreTopology.on('timeout', errorHandler('timeout')); self.s.coreTopology.once('error', errorHandler('error')); self.s.coreTopology.on('close', errorHandler('close')); // Only called on destroy self.s.coreTopology.on('destroy', destroyHandler); // Emit open event self.emit('open', null, self); // Return correctly try { callback(null, self); } catch (err) { console.log(err.stack); process.nextTick(function() { throw err; }); } }; // Set up listeners var connectHandlers = { timeout: connectErrorHandler('timeout'), error: connectErrorHandler('error'), close: connectErrorHandler('close') }; // Clear out all the current handlers left over [ 'timeout', 'error', 'close', 'serverOpening', 'serverDescriptionChanged', 'serverHeartbeatStarted', 'serverHeartbeatSucceeded', 'serverHeartbeatFailed', 'serverClosed', 'topologyOpening', 'topologyClosed', 'topologyDescriptionChanged' ].forEach(function(e) { self.s.coreTopology.removeAllListeners(e); }); // Add the event handlers self.s.coreTopology.once('timeout', connectHandlers.timeout); self.s.coreTopology.once('error', connectHandlers.error); self.s.coreTopology.once('close', connectHandlers.close); self.s.coreTopology.once('connect', connectHandler); // Reconnect server self.s.coreTopology.on('reconnect', reconnectHandler); self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); // Set up SDAM listeners self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); self.s.coreTopology.on('serverOpening', relay('serverOpening')); self.s.coreTopology.on('serverClosed', relay('serverClosed')); self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); self.s.coreTopology.on('monitoring', relay('monitoring')); // Start connection self.s.coreTopology.connect(_options); } } Object.defineProperty(Server.prototype, 'poolSize', { enumerable: true, get: function() { return this.s.coreTopology.connections().length; } }); Object.defineProperty(Server.prototype, 'autoReconnect', { enumerable: true, get: function() { return this.s.reconnect; } }); Object.defineProperty(Server.prototype, 'host', { enumerable: true, get: function() { return this.s.host; } }); Object.defineProperty(Server.prototype, 'port', { enumerable: true, get: function() { return this.s.port; } }); const define = (Server.define = new Define('Server', Server, false)); define.classMethod('capabilities', { callback: false, promise: false, returns: [ServerCapabilities] }); define.classMethod('command', { callback: true, promise: false }); define.classMethod('insert', { callback: true, promise: false }); define.classMethod('update', { callback: true, promise: false }); define.classMethod('remove', { callback: true, promise: false }); define.classMethod('isConnected', { callback: false, promise: false, returns: [Boolean] }); define.classMethod('isDestroyed', { callback: false, promise: false, returns: [Boolean] }); define.classMethod('cursor', { callback: false, promise: false, returns: [Cursor, AggregationCursor, CommandCursor] }); define.classMethod('close', { callback: false, promise: false }); define.classMethod('auth', { callback: true, promise: false }); define.classMethod('logout', { callback: true, promise: false }); define.classMethod('connections', { callback: false, promise: false, returns: [Array] }); /** * Server connect event * * @event Server#connect * @type {object} */ /** * Server close event * * @event Server#close * @type {object} */ /** * Server reconnect event * * @event Server#reconnect * @type {object} */ /** * Server error event * * @event Server#error * @type {MongoError} */ /** * Server timeout event * * @event Server#timeout * @type {object} */ /** * Server parseError event * * @event Server#parseError * @type {object} */ module.exports = Server; }).call(this,require('_process')) },{"../aggregation_cursor":376,"../command_cursor":384,"../cursor":385,"../metadata":392,"../utils":399,"./topology_base":397,"_process":507,"mongodb-core":345}],397:[function(require,module,exports){ (function (process){ 'use strict'; const EventEmitter = require('events'), MongoError = require('mongodb-core').MongoError, f = require('util').format, os = require('os'), translateReadPreference = require('../utils').translateReadPreference, ClientSession = require('mongodb-core').Sessions.ClientSession; // The store of ops var Store = function(topology, storeOptions) { var self = this; var storedOps = []; storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; // Internal state this.s = { storedOps: storedOps, storeOptions: storeOptions, topology: topology }; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return self.s.storedOps.length; } }); }; Store.prototype.add = function(opType, ns, ops, options, callback) { if (this.s.storeOptions.force) { return callback(MongoError.create({ message: 'db closed by application', driver: true })); } if (this.s.storeOptions.bufferMaxEntries === 0) { return callback( MongoError.create({ message: f( 'no connection available for operation and number of stored operation > %s', this.s.storeOptions.bufferMaxEntries ), driver: true }) ); } if ( this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries ) { while (this.s.storedOps.length > 0) { var op = this.s.storedOps.shift(); op.c( MongoError.create({ message: f( 'no connection available for operation and number of stored operation > %s', this.s.storeOptions.bufferMaxEntries ), driver: true }) ); } return; } this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); }; Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { if (this.s.storeOptions.force) { return callback(MongoError.create({ message: 'db closed by application', driver: true })); } if (this.s.storeOptions.bufferMaxEntries === 0) { return callback( MongoError.create({ message: f( 'no connection available for operation and number of stored operation > %s', this.s.storeOptions.bufferMaxEntries ), driver: true }) ); } if ( this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries ) { while (this.s.storedOps.length > 0) { var op = this.s.storedOps.shift(); op.c( MongoError.create({ message: f( 'no connection available for operation and number of stored operation > %s', this.s.storeOptions.bufferMaxEntries ), driver: true }) ); } return; } this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); }; Store.prototype.flush = function(err) { while (this.s.storedOps.length > 0) { this.s.storedOps .shift() .c( err || MongoError.create({ message: f('no connection available for operation'), driver: true }) ); } }; var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; var secondaryOptions = ['secondary', 'secondaryPreferred']; Store.prototype.execute = function(options) { options = options || {}; // Get current ops var ops = this.s.storedOps; // Reset the ops this.s.storedOps = []; // Unpack options var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; var executeSecondary = typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; // Execute all the stored ops while (ops.length > 0) { var op = ops.shift(); if (op.t === 'cursor') { if (executePrimary && executeSecondary) { op.o[op.m].apply(op.o, op.p); } else if ( executePrimary && op.o.options && op.o.options.readPreference && primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 ) { op.o[op.m].apply(op.o, op.p); } else if ( !executePrimary && executeSecondary && op.o.options && op.o.options.readPreference && secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 ) { op.o[op.m].apply(op.o, op.p); } } else if (op.t === 'auth') { this.s.topology[op.t].apply(this.s.topology, op.o); } else { if (executePrimary && executeSecondary) { this.s.topology[op.t](op.n, op.o, op.op, op.c); } else if ( executePrimary && op.op && op.op.readPreference && primaryOptions.indexOf(op.op.readPreference.mode) !== -1 ) { this.s.topology[op.t](op.n, op.o, op.op, op.c); } else if ( !executePrimary && executeSecondary && op.op && op.op.readPreference && secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 ) { this.s.topology[op.t](op.n, op.o, op.op, op.c); } } } }; Store.prototype.all = function() { return this.s.storedOps; }; // Server capabilities var ServerCapabilities = function(ismaster) { var setup_get_property = function(object, name, value) { Object.defineProperty(object, name, { enumerable: true, get: function() { return value; } }); }; // Capabilities var aggregationCursor = false; var writeCommands = false; var textSearch = false; var authCommands = false; var listCollections = false; var listIndexes = false; var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; var commandsTakeWriteConcern = false; var commandsTakeCollation = false; if (ismaster.minWireVersion >= 0) { textSearch = true; } if (ismaster.maxWireVersion >= 1) { aggregationCursor = true; authCommands = true; } if (ismaster.maxWireVersion >= 2) { writeCommands = true; } if (ismaster.maxWireVersion >= 3) { listCollections = true; listIndexes = true; } if (ismaster.maxWireVersion >= 5) { commandsTakeWriteConcern = true; commandsTakeCollation = true; } // If no min or max wire version set to 0 if (ismaster.minWireVersion == null) { ismaster.minWireVersion = 0; } if (ismaster.maxWireVersion == null) { ismaster.maxWireVersion = 0; } // Map up read only parameters setup_get_property(this, 'hasAggregationCursor', aggregationCursor); setup_get_property(this, 'hasWriteCommands', writeCommands); setup_get_property(this, 'hasTextSearch', textSearch); setup_get_property(this, 'hasAuthCommands', authCommands); setup_get_property(this, 'hasListCollectionsCommand', listCollections); setup_get_property(this, 'hasListIndexesCommand', listIndexes); setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); }; // Get package.json variable const driverVersion = require('../../package.json').version, nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), type = os.type(), name = process.platform, architecture = process.arch, release = os.release(); class TopologyBase extends EventEmitter { constructor() { super(); // Build default client information this.clientInfo = { driver: { name: 'nodejs', version: driverVersion }, os: { type: type, name: name, architecture: architecture, version: release }, platform: nodejsversion }; this.setMaxListeners(Infinity); } // Sessions related methods hasSessionSupport() { return this.logicalSessionTimeoutMinutes != null; } startSession(options) { return new ClientSession(this, this.s.sessionPool, options); } endSessions(sessions, callback) { return this.s.coreTopology.endSessions(sessions, callback); } // Server capabilities capabilities() { if (this.s.sCapabilities) return this.s.sCapabilities; if (this.s.coreTopology.lastIsMaster() == null) return null; this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); return this.s.sCapabilities; } // Command command(ns, cmd, options, callback) { this.s.coreTopology.command(ns, cmd, translateReadPreference(options), callback); } // Insert insert(ns, ops, options, callback) { this.s.coreTopology.insert(ns, ops, options, callback); } // Update update(ns, ops, options, callback) { this.s.coreTopology.update(ns, ops, options, callback); } // Remove remove(ns, ops, options, callback) { this.s.coreTopology.remove(ns, ops, options, callback); } // IsConnected isConnected(options) { options = options || {}; options = translateReadPreference(options); return this.s.coreTopology.isConnected(options); } // IsDestroyed isDestroyed() { return this.s.coreTopology.isDestroyed(); } // Cursor cursor(ns, cmd, options) { options = options || {}; options = translateReadPreference(options); options.disconnectHandler = this.s.store; options.topology = this; return this.s.coreTopology.cursor(ns, cmd, options); } lastIsMaster() { return this.s.coreTopology.lastIsMaster(); } getServer(options) { return this.s.coreTopology.getServer(options); } getConnection(options) { return this.s.coreTopology.getConnection(options); } /** * Unref all sockets * @method */ unref() { return this.s.coreTopology.unref(); } auth() { var args = Array.prototype.slice.call(arguments, 0); this.s.coreTopology.auth.apply(this.s.coreTopology, args); } logout() { var args = Array.prototype.slice.call(arguments, 0); this.s.coreTopology.logout.apply(this.s.coreTopology, args); } /** * All raw connections * @method * @return {array} */ connections() { return this.s.coreTopology.connections(); } close(forceClosed) { this.s.coreTopology.destroy({ force: typeof forceClosed === 'boolean' ? forceClosed : false }); // We need to wash out all stored processes if (forceClosed === true) { this.s.storeOptions.force = forceClosed; this.s.store.flush(); } } } // Properties Object.defineProperty(TopologyBase.prototype, 'isMasterDoc', { enumerable: true, get: function() { return this.s.coreTopology.lastIsMaster(); } }); Object.defineProperty(TopologyBase.prototype, 'bson', { enumerable: true, get: function() { return this.s.coreTopology.s.bson; } }); Object.defineProperty(TopologyBase.prototype, 'parserType', { enumerable: true, get: function() { return this.s.coreTopology.parserType; } }); Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { enumerable: true, get: function() { return this.s.coreTopology.logicalSessionTimeoutMinutes; } }); Object.defineProperty(TopologyBase.prototype, 'type', { enumerable: true, get: function() { return this.s.coreTopology.type; } }); exports.Store = Store; exports.ServerCapabilities = ServerCapabilities; exports.TopologyBase = TopologyBase; }).call(this,require('_process')) },{"../../package.json":400,"../utils":399,"_process":507,"events":316,"mongodb-core":345,"os":483,"util":563}],398:[function(require,module,exports){ 'use strict'; const ReadPreference = require('mongodb-core').ReadPreference, parser = require('url'), f = require('util').format, Logger = require('mongodb-core').Logger, dns = require('dns'); module.exports = function(url, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; let result = parser.parse(url, true); if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); } if (result.protocol === 'mongodb:') { return parseHandler(url, options, callback); } // Otherwise parse this as an SRV record if (result.hostname.split('.').length < 3) { return callback(new Error('URI does not have hostname, domain name and tld')); } result.domainLength = result.hostname.split('.').length; if (result.pathname && result.pathname.match(',')) { return callback(new Error('Invalid URI, cannot contain multiple hostnames')); } if (result.port) { return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); } let srvAddress = `_mongodb._tcp.${result.host}`; dns.resolveSrv(srvAddress, function(err, addresses) { if (err) return callback(err); if (addresses.length === 0) { return callback(new Error('No addresses found at host')); } for (let i = 0; i < addresses.length; i++) { if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { return callback(new Error('Server record does not share hostname with parent URI')); } } let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; let connectionStrings = addresses.map(function(address, i) { if (i === 0) return `${base}${address.name}:${address.port}`; else return `${address.name}:${address.port}`; }); let connectionString = connectionStrings.join(',') + '/'; let connectionStringOptions = []; // Default to SSL true if (!options.ssl && !result.search) { connectionStringOptions.push('ssl=true'); } else if (!options.ssl && result.search && !result.search.match('ssl')) { connectionStringOptions.push('ssl=true'); } // Keep original uri options if (result.search) { connectionStringOptions.push(result.search.replace('?', '')); } dns.resolveTxt(result.host, function(err, record) { if (err && err.code !== 'ENODATA') return callback(err); if (err && err.code === 'ENODATA') record = null; if (record) { if (record.length > 1) { return callback(new Error('Multiple text records not allowed')); } record = record[0]; if (record.length > 1) record = record.join(''); else record = record[0]; if (!record.includes('authSource') && !record.includes('replicaSet')) { return callback(new Error('Text record must only set `authSource` or `replicaSet`')); } connectionStringOptions.push(record); } // Add any options to the connection string if (connectionStringOptions.length) { connectionString += `?${connectionStringOptions.join('&')}`; } parseHandler(connectionString, options, callback); }); }); }; function matchesParentDomain(srvAddress, parentDomain) { let regex = /^.*?\./; let srv = `.${srvAddress.replace(regex, '')}`; let parent = `.${parentDomain.replace(regex, '')}`; if (srv.endsWith(parent)) return true; else return false; } function parseHandler(address, options, callback) { let result, err; try { result = parseConnectionString(address, options); } catch (e) { err = e; } return err ? callback(err, null) : callback(null, result); } function parseConnectionString(url, options) { // Variables let connection_part = ''; let auth_part = ''; let query_string_part = ''; let dbName = 'admin'; // Url parser result let result = parser.parse(url, true); if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { throw new Error('No hostname or hostnames provided in connection string'); } if (result.port === '0') { throw new Error('Invalid port (zero) with hostname'); } if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { throw new Error('Invalid port (larger than 65535) with hostname'); } if ( result.path && result.path.length > 0 && result.path[0] !== '/' && url.indexOf('.sock') === -1 ) { throw new Error('Missing delimiting slash between hosts and options'); } if (result.query) { for (let name in result.query) { if (name.indexOf('::') !== -1) { throw new Error('Double colon in host identifier'); } if (result.query[name] === '') { throw new Error('Query parameter ' + name + ' is an incomplete value pair'); } } } if (result.auth) { let parts = result.auth.split(':'); if (url.indexOf(result.auth) !== -1 && parts.length > 2) { throw new Error('Username with password containing an unescaped colon'); } if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { throw new Error('Username containing an unescaped at-sign'); } } // Remove query let clean = url.split('?').shift(); // Extract the list of hosts let strings = clean.split(','); let hosts = []; for (let i = 0; i < strings.length; i++) { let hostString = strings[i]; if (hostString.indexOf('mongodb') !== -1) { if (hostString.indexOf('@') !== -1) { hosts.push(hostString.split('@').pop()); } else { hosts.push(hostString.substr('mongodb://'.length)); } } else if (hostString.indexOf('/') !== -1) { hosts.push(hostString.split('/').shift()); } else if (hostString.indexOf('/') === -1) { hosts.push(hostString.trim()); } } for (let i = 0; i < hosts.length; i++) { let r = parser.parse(f('mongodb://%s', hosts[i].trim())); if (r.path && r.path.indexOf(':') !== -1) { // Not connecting to a socket so check for an extra slash in the hostname. // Using String#split as perf is better than match. if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { throw new Error('Slash in host identifier'); } else { throw new Error('Double colon in host identifier'); } } } // If we have a ? mark cut the query elements off if (url.indexOf('?') !== -1) { query_string_part = url.substr(url.indexOf('?') + 1); connection_part = url.substring('mongodb://'.length, url.indexOf('?')); } else { connection_part = url.substring('mongodb://'.length); } // Check if we have auth params if (connection_part.indexOf('@') !== -1) { auth_part = connection_part.split('@')[0]; connection_part = connection_part.split('@')[1]; } // Check there is not more than one unescaped slash if (connection_part.split('/').length > 2) { throw new Error( "Unsupported host '" + connection_part.split('?')[0] + "', hosts must be URL encoded and contain at most one unencoded slash" ); } // Check if the connection string has a db if (connection_part.indexOf('.sock') !== -1) { if (connection_part.indexOf('.sock/') !== -1) { dbName = connection_part.split('.sock/')[1]; // Check if multiple database names provided, or just an illegal trailing backslash if (dbName.indexOf('/') !== -1) { if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { throw new Error('Illegal trailing backslash after database name'); } throw new Error('More than 1 database name in URL'); } connection_part = connection_part.split( '/', connection_part.indexOf('.sock') + '.sock'.length ); } } else if (connection_part.indexOf('/') !== -1) { // Check if multiple database names provided, or just an illegal trailing backslash if (connection_part.split('/').length > 2) { if (connection_part.split('/')[2].length === 0) { throw new Error('Illegal trailing backslash after database name'); } throw new Error('More than 1 database name in URL'); } dbName = connection_part.split('/')[1]; connection_part = connection_part.split('/')[0]; } // URI decode the host information connection_part = decodeURIComponent(connection_part); // Result object let object = {}; // Pick apart the authentication part of the string let authPart = auth_part || ''; let auth = authPart.split(':', 2); // Decode the authentication URI components and verify integrity let user = decodeURIComponent(auth[0]); if (auth[0] !== encodeURIComponent(user)) { throw new Error('Username contains an illegal unescaped character'); } auth[0] = user; if (auth[1]) { let pass = decodeURIComponent(auth[1]); if (auth[1] !== encodeURIComponent(pass)) { throw new Error('Password contains an illegal unescaped character'); } auth[1] = pass; } // Add auth to final object if we have 2 elements if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; // if user provided auth options, use that if (options && options.auth != null) object.auth = options.auth; // Variables used for temporary storage let hostPart; let urlOptions; let servers; let compression; let serverOptions = { socketOptions: {} }; let dbOptions = { read_preference_tags: [] }; let replSetServersOptions = { socketOptions: {} }; let mongosOptions = { socketOptions: {} }; // Add server options to final object object.server_options = serverOptions; object.db_options = dbOptions; object.rs_options = replSetServersOptions; object.mongos_options = mongosOptions; // Let's check if we are using a domain socket if (url.match(/\.sock/)) { // Split out the socket part let domainSocket = url.substring( url.indexOf('mongodb://') + 'mongodb://'.length, url.lastIndexOf('.sock') + '.sock'.length ); // Clean out any auth stuff if any if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; domainSocket = decodeURIComponent(domainSocket); servers = [{ domain_socket: domainSocket }]; } else { // Split up the db hostPart = connection_part; // Deduplicate servers let deduplicatedServers = {}; // Parse all server results servers = hostPart .split(',') .map(function(h) { let _host, _port, ipv6match; //check if it matches [IPv6]:port, where the port number is optional if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { _host = ipv6match[1]; _port = parseInt(ipv6match[2], 10) || 27017; } else { //otherwise assume it's IPv4, or plain hostname let hostPort = h.split(':', 2); _host = hostPort[0] || 'localhost'; _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; // Check for localhost?safe=true style case if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; } // No entry returned for duplicate servr if (deduplicatedServers[_host + '_' + _port]) return null; deduplicatedServers[_host + '_' + _port] = 1; // Return the mapped object return { host: _host, port: _port }; }) .filter(function(x) { return x != null; }); } // Get the db name object.dbName = dbName || 'admin'; // Split up all the options urlOptions = (query_string_part || '').split(/[&;]/); // Ugh, we have to figure out which options go to which constructor manually. urlOptions.forEach(function(opt) { if (!opt) return; var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; // Options implementations switch (name) { case 'slaveOk': case 'slave_ok': serverOptions.slave_ok = value === 'true'; dbOptions.slaveOk = value === 'true'; break; case 'maxPoolSize': case 'poolSize': serverOptions.poolSize = parseInt(value, 10); replSetServersOptions.poolSize = parseInt(value, 10); break; case 'appname': object.appname = decodeURIComponent(value); break; case 'autoReconnect': case 'auto_reconnect': serverOptions.auto_reconnect = value === 'true'; break; case 'ssl': if (value === 'prefer') { serverOptions.ssl = value; replSetServersOptions.ssl = value; mongosOptions.ssl = value; break; } serverOptions.ssl = value === 'true'; replSetServersOptions.ssl = value === 'true'; mongosOptions.ssl = value === 'true'; break; case 'sslValidate': serverOptions.sslValidate = value === 'true'; replSetServersOptions.sslValidate = value === 'true'; mongosOptions.sslValidate = value === 'true'; break; case 'replicaSet': case 'rs_name': replSetServersOptions.rs_name = value; break; case 'reconnectWait': replSetServersOptions.reconnectWait = parseInt(value, 10); break; case 'retries': replSetServersOptions.retries = parseInt(value, 10); break; case 'readSecondary': case 'read_secondary': replSetServersOptions.read_secondary = value === 'true'; break; case 'fsync': dbOptions.fsync = value === 'true'; break; case 'journal': dbOptions.j = value === 'true'; break; case 'safe': dbOptions.safe = value === 'true'; break; case 'nativeParser': case 'native_parser': dbOptions.native_parser = value === 'true'; break; case 'readConcernLevel': dbOptions.readConcern = { level: value }; break; case 'connectTimeoutMS': serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); break; case 'socketTimeoutMS': serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); break; case 'w': dbOptions.w = parseInt(value, 10); if (isNaN(dbOptions.w)) dbOptions.w = value; break; case 'authSource': dbOptions.authSource = value; break; case 'gssapiServiceName': dbOptions.gssapiServiceName = value; break; case 'authMechanism': if (value === 'GSSAPI') { // If no password provided decode only the principal if (object.auth == null) { let urlDecodeAuthPart = decodeURIComponent(authPart); if (urlDecodeAuthPart.indexOf('@') === -1) throw new Error('GSSAPI requires a provided principal'); object.auth = { user: urlDecodeAuthPart, password: null }; } else { object.auth.user = decodeURIComponent(object.auth.user); } } else if (value === 'MONGODB-X509') { object.auth = { user: decodeURIComponent(authPart) }; } // Only support GSSAPI or MONGODB-CR for now if ( value !== 'GSSAPI' && value !== 'MONGODB-X509' && value !== 'MONGODB-CR' && value !== 'DEFAULT' && value !== 'SCRAM-SHA-1' && value !== 'PLAIN' ) throw new Error( 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism' ); // Authentication mechanism dbOptions.authMechanism = value; break; case 'authMechanismProperties': { // Split up into key, value pairs let values = value.split(','); let o = {}; // For each value split into key, value values.forEach(function(x) { let v = x.split(':'); o[v[0]] = v[1]; }); // Set all authMechanismProperties dbOptions.authMechanismProperties = o; // Set the service name value if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; if (typeof o.CANONICALIZE_HOST_NAME === 'string') dbOptions.gssapiCanonicalizeHostName = o.CANONICALIZE_HOST_NAME === 'true' ? true : false; } break; case 'wtimeoutMS': dbOptions.wtimeout = parseInt(value, 10); break; case 'readPreference': if (!ReadPreference.isValid(value)) throw new Error( 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' ); dbOptions.readPreference = value; break; case 'maxStalenessSeconds': dbOptions.maxStalenessSeconds = parseInt(value, 10); break; case 'readPreferenceTags': { // Decode the value value = decodeURIComponent(value); // Contains the tag object let tagObject = {}; if (value == null || value === '') { dbOptions.read_preference_tags.push(tagObject); break; } // Split up the tags let tags = value.split(/,/); for (let i = 0; i < tags.length; i++) { let parts = tags[i].trim().split(/:/); tagObject[parts[0]] = parts[1]; } // Set the preferences tags dbOptions.read_preference_tags.push(tagObject); } break; case 'compressors': { compression = serverOptions.compression || {}; let compressors = value.split(','); if ( !compressors.every(function(compressor) { return compressor === 'snappy' || compressor === 'zlib'; }) ) { throw new Error('Compressors must be at least one of snappy or zlib'); } compression.compressors = compressors; serverOptions.compression = compression; } break; case 'zlibCompressionLevel': { compression = serverOptions.compression || {}; let zlibCompressionLevel = parseInt(value, 10); if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); } compression.zlibCompressionLevel = zlibCompressionLevel; serverOptions.compression = compression; } break; case 'retryWrites': dbOptions.retryWrites = value === 'true'; break; case 'minSize': dbOptions.minSize = parseInt(value, 10); break; default: { let logger = Logger('URL Parser'); logger.warn(`${name} is not supported as a connection string option`); } break; } }); // No tags: should be null (not []) if (dbOptions.read_preference_tags.length === 0) { dbOptions.read_preference_tags = null; } // Validate if there are an invalid write concern combinations if ( (dbOptions.w === -1 || dbOptions.w === 0) && (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) ) throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); // If no read preference set it to primary if (!dbOptions.readPreference) { dbOptions.readPreference = 'primary'; } // make sure that user-provided options are applied with priority dbOptions = Object.assign(dbOptions, options); // Add servers to result object.servers = servers; // Returned parsed object return object; } },{"dns":123,"mongodb-core":345,"url":558,"util":563}],399:[function(require,module,exports){ (function (process){ 'use strict'; var MongoError = require('mongodb-core').MongoError, ReadPreference = require('mongodb-core').ReadPreference; var shallowClone = function(obj) { var copy = {}; for (var name in obj) copy[name] = obj[name]; return copy; }; // Figure out the read preference var translateReadPreference = function(options) { var r = null; if (options.readPreference) { r = options.readPreference; } else { return options; } if (typeof r === 'string') { options.readPreference = new ReadPreference(r); } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { const mode = r.mode || r.preference; if (mode && typeof mode === 'string') { options.readPreference = new ReadPreference(mode, r.tags, { maxStalenessSeconds: r.maxStalenessSeconds }); } } else if (!(r instanceof ReadPreference)) { throw new TypeError('Invalid read preference: ' + r); } return options; }; // Set simple property var getSingleProperty = function(obj, name, value) { Object.defineProperty(obj, name, { enumerable: true, get: function() { return value; } }); }; var formatSortValue = (exports.formatSortValue = function(sortDirection) { var value = ('' + sortDirection).toLowerCase(); switch (value) { case 'ascending': case 'asc': case '1': return 1; case 'descending': case 'desc': case '-1': return -1; default: throw new Error( 'Illegal sort clause, must be of the form ' + "[['field1', '(ascending|descending)'], " + "['field2', '(ascending|descending)']]" ); } }); var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { var orderBy = {}; if (sortValue == null) return null; if (Array.isArray(sortValue)) { if (sortValue.length === 0) { return null; } for (var i = 0; i < sortValue.length; i++) { if (sortValue[i].constructor === String) { orderBy[sortValue[i]] = 1; } else { orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); } } } else if (sortValue != null && typeof sortValue === 'object') { orderBy = sortValue; } else if (typeof sortValue === 'string') { orderBy[sortValue] = 1; } else { throw new Error( 'Illegal sort clause, must be of the form ' + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" ); } return orderBy; }); var checkCollectionName = function checkCollectionName(collectionName) { if ('string' !== typeof collectionName) { throw new MongoError('collection name must be a String'); } if (!collectionName || collectionName.indexOf('..') !== -1) { throw new MongoError('collection names cannot be empty'); } if ( collectionName.indexOf('$') !== -1 && collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null ) { throw new MongoError("collection names must not contain '$'"); } if (collectionName.match(/^\.|\.$/) != null) { throw new MongoError("collection names must not start or end with '.'"); } // Validate that we are not passing 0x00 in the colletion name if (collectionName.indexOf('\x00') !== -1) { throw new MongoError('collection names cannot contain a null character'); } }; var handleCallback = function(callback, err, value1, value2) { try { if (callback == null) return; if (callback) { return value2 ? callback(err, value1, value2) : callback(err, value1); } } catch (err) { process.nextTick(function() { throw err; }); return false; } return true; }; /** * Wrap a Mongo error document in an Error instance * @ignore * @api private */ var toError = function(error) { if (error instanceof Error) return error; var msg = error.err || error.errmsg || error.errMessage || error; var e = MongoError.create({ message: msg, driver: true }); // Get all object keys var keys = typeof error === 'object' ? Object.keys(error) : []; for (var i = 0; i < keys.length; i++) { try { e[keys[i]] = error[keys[i]]; } catch (err) { // continue } } return e; }; /** * @ignore */ var normalizeHintField = function normalizeHintField(hint) { var finalHint = null; if (typeof hint === 'string') { finalHint = hint; } else if (Array.isArray(hint)) { finalHint = {}; hint.forEach(function(param) { finalHint[param] = 1; }); } else if (hint != null && typeof hint === 'object') { finalHint = {}; for (var name in hint) { finalHint[name] = hint[name]; } } return finalHint; }; /** * Create index name based on field spec * * @ignore * @api private */ var parseIndexOptions = function(fieldOrSpec) { var fieldHash = {}; var indexes = []; var keys; // Get all the fields accordingly if ('string' === typeof fieldOrSpec) { // 'type' indexes.push(fieldOrSpec + '_' + 1); fieldHash[fieldOrSpec] = 1; } else if (Array.isArray(fieldOrSpec)) { fieldOrSpec.forEach(function(f) { if ('string' === typeof f) { // [{location:'2d'}, 'type'] indexes.push(f + '_' + 1); fieldHash[f] = 1; } else if (Array.isArray(f)) { // [['location', '2d'],['type', 1]] indexes.push(f[0] + '_' + (f[1] || 1)); fieldHash[f[0]] = f[1] || 1; } else if (isObject(f)) { // [{location:'2d'}, {type:1}] keys = Object.keys(f); keys.forEach(function(k) { indexes.push(k + '_' + f[k]); fieldHash[k] = f[k]; }); } else { // undefined (ignore) } }); } else if (isObject(fieldOrSpec)) { // {location:'2d', type:1} keys = Object.keys(fieldOrSpec); keys.forEach(function(key) { indexes.push(key + '_' + fieldOrSpec[key]); fieldHash[key] = fieldOrSpec[key]; }); } return { name: indexes.join('_'), keys: keys, fieldHash: fieldHash }; }; var isObject = (exports.isObject = function(arg) { return '[object Object]' === Object.prototype.toString.call(arg); }); var debugOptions = function(debugFields, options) { var finaloptions = {}; debugFields.forEach(function(n) { finaloptions[n] = options[n]; }); return finaloptions; }; var decorateCommand = function(command, options, exclude) { for (var name in options) { if (exclude[name] == null) command[name] = options[name]; } return command; }; var mergeOptions = function(target, source) { for (var name in source) { target[name] = source[name]; } return target; }; // Merge options with translation var translateOptions = function(target, source) { var translations = { // SSL translation options sslCA: 'ca', sslCRL: 'crl', sslValidate: 'rejectUnauthorized', sslKey: 'key', sslCert: 'cert', sslPass: 'passphrase', // SocketTimeout translation options socketTimeoutMS: 'socketTimeout', connectTimeoutMS: 'connectionTimeout', // Replicaset options replicaSet: 'setName', rs_name: 'setName', secondaryAcceptableLatencyMS: 'acceptableLatency', connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', // Mongos options acceptableLatencyMS: 'localThresholdMS' }; for (var name in source) { if (translations[name]) { target[translations[name]] = source[name]; } else { target[name] = source[name]; } } return target; }; var filterOptions = function(options, names) { var filterOptions = {}; for (var name in options) { if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; } // Filtered options return filterOptions; }; // Write concern keys var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; // Merge the write concern options var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { // Mix in any allowed options for (var i = 0; i < keys.length; i++) { if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { targetOptions[keys[i]] = sourceOptions[keys[i]]; } } // No merging of write concern if (!mergeWriteConcern) return targetOptions; // Found no write Concern options var found = false; for (i = 0; i < writeConcernKeys.length; i++) { if (targetOptions[writeConcernKeys[i]]) { found = true; break; } } if (!found) { for (i = 0; i < writeConcernKeys.length; i++) { if (sourceOptions[writeConcernKeys[i]]) { targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; } } } return targetOptions; }; /** * Executes the given operation with provided arguments. * * This method reduces large amounts of duplication in the entire codebase by providing * a single point for determining whether callbacks or promises should be used. Additionally * it allows for a single point of entry to provide features such as implicit sessions, which * are required by the Driver Sessions specification in the event that a ClientSession is * not provided * * @param {object} topology The topology to execute this operation on * @param {function} operation The operation to execute * @param {array} args Arguments to apply the provided operation * @param {object} [options] Options that modify the behavior of the method * @param {function]} [options.resultMutator] Allows for the result of the operation to be changed for custom return types */ const executeOperation = (topology, operation, args, options) => { if (topology == null) { throw new TypeError('This method requires a valid topology instance'); } if (!Array.isArray(args)) { throw new TypeError('This method requires an array of arguments to apply'); } options = options || {}; const Promise = topology.s.promiseLibrary; let resultMutator = options.resultMutator; let callback = args[args.length - 1]; // The driver sessions spec mandates that we implicitly create sessions for operations // that are not explicitly provided with a session. let session, opOptions; if (!options.skipSessions && topology.hasSessionSupport()) { opOptions = args[args.length - 2]; if (opOptions == null || opOptions.session == null) { session = topology.startSession(); Object.assign(args[args.length - 2], { session: session }); } else if (opOptions.session && opOptions.session.hasEnded) { throw new MongoError('Use of expired sessions is not permitted'); } } // Execute using callback if (typeof callback === 'function') { callback = args.pop(); args.push((err, result) => { if (session && !options.returnsCursor) { session.endSession(() => { delete opOptions.session; if (err) return callback(err, null); return resultMutator ? callback(null, resultMutator(result)) : callback(null, result); }); } else { if (err) return callback(err, null); return resultMutator ? callback(null, resultMutator(result)) : callback(null, result); } }); return operation.apply(null, args); } // Return a Promise if (args[args.length - 1] != null) { throw new TypeError('final argument to `executeOperation` must be a callback'); } return new Promise(function(resolve, reject) { args[args.length - 1] = (err, r) => { if (session && !options.returnsCursor) { session.endSession(() => { delete opOptions.session; if (err) return reject(err); if (resultMutator) return resolve(resultMutator(r)); resolve(r); }); } else { if (err) return reject(err); if (resultMutator) return resolve(resultMutator(r)); resolve(r); } }; operation.apply(null, args); }); }; exports.filterOptions = filterOptions; exports.mergeOptions = mergeOptions; exports.translateOptions = translateOptions; exports.shallowClone = shallowClone; exports.getSingleProperty = getSingleProperty; exports.checkCollectionName = checkCollectionName; exports.toError = toError; exports.formattedOrderClause = formattedOrderClause; exports.parseIndexOptions = parseIndexOptions; exports.normalizeHintField = normalizeHintField; exports.handleCallback = handleCallback; exports.decorateCommand = decorateCommand; exports.isObject = isObject; exports.debugOptions = debugOptions; exports.MAX_JS_INT = 0x20000000000000; exports.mergeOptionsAndWriteConcern = mergeOptionsAndWriteConcern; exports.translateReadPreference = translateReadPreference; exports.executeOperation = executeOperation; }).call(this,require('_process')) },{"_process":507,"mongodb-core":345}],400:[function(require,module,exports){ module.exports={ "name": "mongodb", "version": "3.0.2", "description": "The official MongoDB driver for Node.js", "main": "index.js", "repository": { "type": "git", "url": "git@github.com:mongodb/node-mongodb-native.git" }, "keywords": [ "mongodb", "driver", "official" ], "dependencies": { "mongodb-core": "3.0.2" }, "devDependencies": { "betterbenchmarks": "^0.1.0", "bluebird": "3.5.0", "bson": "^1.0.4", "chai": "^4.1.1", "co": "4.6.0", "conventional-changelog-cli": "^1.3.5", "coveralls": "^2.11.6", "eslint": "^4.5.0", "eslint-plugin-prettier": "^2.2.0", "istanbul": "^0.4.5", "jsdoc": "3.5.4", "mongodb-extended-json": "^1.10.0", "mongodb-mock-server": "^1.0.0", "mongodb-test-runner": "^1.1.18", "prettier": "^1.5.3", "semver": "5.4.1", "worker-farm": "^1.5.0" }, "author": "Christian Kvalheim", "license": "Apache-2.0", "engines": { "node": ">=4" }, "bugs": { "url": "https://github.com/mongodb/node-mongodb-native/issues" }, "scripts": { "test": "npm run lint && mongodb-test-runner -t 60000 test/unit test/functional", "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional", "lint": "eslint lib test", "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", "changelog": "conventional-changelog -p angular -i HISTORY.md -s" }, "homepage": "https://github.com/mongodb/node-mongodb-native" } },{}],401:[function(require,module,exports){ (function (Buffer){ /* eslint-env browser */ var DocumentProvider = require('./document_provider.js'); var 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'); /** * The Mongoose [Schema](#schema_Schema) constructor * * ####Example: * * var mongoose = require('mongoose'); * var Schema = mongoose.Schema; * var CatSchema = new Schema(..); * * @method Schema * @api public */ exports.Schema = require('./schema'); /** * The various Mongoose Types. * * ####Example: * * var mongoose = require('mongoose'); * var 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. * * var ObjectId = mongoose.Types.ObjectId; * var 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](#document-js) constructor. * * @method Document * @api public */ exports.Document = DocumentProvider(); /*! * Module exports. */ if (typeof window !== 'undefined') { window.mongoose = module.exports; window.Buffer = Buffer; } }).call(this,require("buffer").Buffer) },{"./document_provider.js":405,"./error":419,"./promise_provider":433,"./schema":434,"./schematype.js":452,"./types":466,"./utils.js":469,"./virtualtype":470,"buffer":144}],402:[function(require,module,exports){ /*! * Module dependencies. */ var NodeJSDocument = require('./document'); var EventEmitter = require('events').EventEmitter; var MongooseError = require('./error'); var Schema = require('./schema'); var ObjectId = require('./types/objectid'); var ValidationError = MongooseError.ValidationError; var InternalCache = require('./internal'); var applyHooks = require('./services/model/applyHooks'); var utils = require('./utils'); /** * 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 (utils.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); this.$__ = new InternalCache; this.$__.emitter = new EventEmitter(); this.isNew = true; this.errors = undefined; if (typeof fields === 'boolean') { this.$__.strictMode = fields; fields = undefined; } else { this.$__.strictMode = this.schema.options && this.schema.options.strict; this.$__.selected = fields; } var required = this.schema.requiredPaths(); for (var i = 0; i < required.length; ++i) { this.$__.activePaths.require(required[i]); } this.$__.emitter.setMaxListeners(0); this._doc = this.$__buildDoc(obj, fields, skipId); if (!skipInit && obj) { this.init(obj); } applyHooks(this, schema, { decorateDoc: true }); // apply methods for (var m in schema.methods) { this[m] = schema.methods[m]; } // apply statics for (var s in schema.statics) { this[s] = schema.statics[s]; } } /*! * Inherit from the NodeJS document */ Document.prototype = Object.create(NodeJSDocument.prototype); Document.prototype.constructor = Document; /*! * Browser doc exposes the event emitter API */ Document.$emitter = new EventEmitter(); utils.each( ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', 'removeAllListeners', 'addListener'], function(emitterFn) { Document[emitterFn] = function() { return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); }; }); /*! * Module exports. */ Document.ValidationError = ValidationError; module.exports = exports = Document; },{"./document":404,"./error":419,"./internal":430,"./schema":434,"./services/model/applyHooks":456,"./types/objectid":467,"./utils":469,"events":316}],403:[function(require,module,exports){ /*! * Module dependencies. */ var StrictModeError = require('./error/strict'); var Types = require('./schema/index'); var util = require('util'); var utils = require('./utils'); var 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)); } var paths = Object.keys(obj); var i = paths.length; var _keys; var any$conditionals; var schematype; var nested; var path; var type; var val; options = options || {}; while (i--) { path = paths[i]; val = obj[path]; if (path === '$or' || path === '$nor' || path === '$and') { var k = val.length; while (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 (!schema) { // no casting for Mixed types continue; } schematype = schema.path(path); if (!schematype) { // Handle potential embedded array queries var split = path.split('.'), j = split.length, pathFirstHalf, pathLastHalf, 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 (utils.isObject(val)) { // handle geo schemas that use object notation // { loc: { long: Number, lat: Number } var 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) { var numbertype = new Types.Number('__QueryCasting__'); var 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') { var 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 (utils.isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ transform: false, virtuals: false }); } value = value.$geometry.coordinates; } else if (geo === '$geoWithin') { if (value.$geometry) { if (utils.isMongooseObject(value.$geometry)) { value.$geometry = value.$geometry.toObject({ virtuals: false }); } var 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 (utils.isMongooseObject(value)) { value = value.toObject({ virtuals: false }); } } } _cast(value, numbertype, context); continue; } } if (options.upsert && options.strict && !schema.nested[path]) { 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 true.'); } else if (options.strictQuery) { delete obj[path]; } } else if (val === null || val === undefined) { obj[path] = null; continue; } else if (val.constructor.name === 'Object') { any$conditionals = Object.keys(val).some(function(k) { return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; }); if (!any$conditionals) { obj[path] = schematype.castForQueryWrapper({ val: val, context: context }); } else { var ks = Object.keys(val), $cond; 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 && _keys[0].charAt(0) === '$') { for (var 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 (val.constructor.name === 'Array' && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) { var casted = []; for (var valIndex = 0; valIndex < val.length; valIndex++) { casted.push(schematype.castForQueryWrapper({ val: val[valIndex], 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) || utils.isObject(item)) { return _cast(item, numbertype, context); } val[i] = numbertype.castForQueryWrapper({ val: item, context: context }); }); } else { var nearKeys = Object.keys(val); var nearLen = nearKeys.length; while (nearLen--) { var nkey = nearKeys[nearLen]; var item = val[nkey]; if (Array.isArray(item) || utils.isObject(item)) { _cast(item, numbertype, context); val[nkey] = item; } else { val[nkey] = numbertype.castForQuery({ val: item, context: context }); } } } } },{"./error/strict":426,"./schema/index":442,"./utils":469,"util":563}],404:[function(require,module,exports){ (function (Buffer,process){ 'use strict'; /*! * Module dependencies. */ var EventEmitter = require('events').EventEmitter; var MongooseError = require('./error'); var MixedSchema = require('./schema/mixed'); var Schema = require('./schema'); var ObjectExpectedError = require('./error/objectExpected'); var ObjectParameterError = require('./error/objectParameter'); var StrictModeError = require('./error/strict'); var ValidatorError = require('./schematype').ValidatorError; var VirtualType = require('./virtualtype'); var utils = require('./utils'); var clone = utils.clone; var isDefiningProjection = require('./services/projection/isDefiningProjection'); var isExclusive = require('./services/projection/isExclusive'); var isMongooseObject = utils.isMongooseObject; var inspect = require('util').inspect; var internalToObjectOptions = require('./options').internalToObjectOptions; var ValidationError = MongooseError.ValidationError; var InternalCache = require('./internal'); var cleanModifiedSubpaths = require('./services/document/cleanModifiedSubpaths'); var compile = require('./services/document/compile').compile; var deepEqual = utils.deepEqual; var defineKey = require('./services/document/compile').defineKey; var DocumentArray; var MongooseArray; var Embedded; var flatten = require('./services/common').flatten; var mpath = require('mpath'); var idGetter = require('./plugins/idGetter'); /** * 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 retreived 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) { this.$__ = new InternalCache; this.$__.emitter = new EventEmitter(); this.isNew = true; this.errors = undefined; this.$__.$options = options || {}; if (obj != null && typeof obj !== 'object') { throw new ObjectParameterError(obj, 'obj', 'Document'); } var schema = this.schema; if (typeof fields === 'boolean') { this.$__.strictMode = fields; fields = undefined; } else { this.$__.strictMode = schema.options && schema.options.strict; this.$__.selected = fields; } var required = schema.requiredPaths(true); for (var i = 0; i < required.length; ++i) { this.$__.activePaths.require(required[i]); } this.$__.emitter.setMaxListeners(0); let exclude = null; // determine if this doc is a result of a query with // excluded fields if (fields && utils.getFunctionName(fields.constructor) === 'Object') { exclude = isExclusive(fields); } let hasIncludedChildren = exclude === false && fields ? $__hasIncludedChildren(fields) : {}; this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren); if (obj) { if (obj instanceof Document) { this.isNew = obj.isNew; } // Skip set hooks if (this.$__original_set) { this.$__original_set(obj, undefined, true); } else { this.$set(obj, undefined, true); } } $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren); this.$__._id = this._id; if (!schema.options.strict && obj) { var _this = this, 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; /** * The documents schema. * * @api public * @property schema * @memberOf Document */ Document.prototype.schema; /** * Boolean flag specifying if the document is new. * * @api public * @property isNew * @memberOf Document */ 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 */ Document.prototype.id; /** * Hash containing current validation errors. * * @api public * @property errors * @memberOf Document */ Document.prototype.errors; /*! * ignore */ function $__hasIncludedChildren(fields) { let hasIncludedChildren = {}; let keys = Object.keys(fields); for (var j = 0; j < keys.length; ++j) { let parts = keys[j].split('.'); let c = []; for (var k = 0; k < parts.length; ++k) { c.push(parts[k]); hasIncludedChildren[c.join('.')] = 1; } } return hasIncludedChildren; } /*! * ignore */ function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren) { const paths = Object.keys(doc.schema.paths); const plen = paths.length; for (let i = 0; i < plen; ++i) { let def; let curPath = ''; let p = paths[i]; if (p === '_id' && skipId) { continue; } let type = doc.schema.paths[p]; let path = p.split('.'); let len = path.length; let included = false; let doc_ = doc._doc; for (let j = 0; j < len; ++j) { let 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 (fields && exclude !== null) { if (exclude === true) { // apply defaults to all non-excluded fields if (p in fields) { continue; } def = type.getDefault(doc, false); if (typeof def !== 'undefined') { doc_[piece] = def; doc.$__.activePaths.default(p); } } else if (included) { // selected field def = type.getDefault(doc, false); if (typeof def !== 'undefined') { doc_[piece] = def; doc.$__.activePaths.default(p); } } } else { def = type.getDefault(doc, false); 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 */ Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { const doc = {}; const paths = Object.keys(this.schema.paths); const plen = paths.length; let ii = 0; for (; ii < plen; ++ii) { var 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. * * @param {Object} doc document returned by mongo * @api public * @memberOf Document */ 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; // handle docs with populated paths // If doc._id is not null or undefined if (doc._id !== null && doc._id !== undefined && opts && opts.populated && opts.populated.length) { var id = String(doc._id); for (var i = 0; i < opts.populated.length; ++i) { var item = opts.populated[i]; if (item.isVirtual) { this.populated(item.path, utils.getValue(item.path, doc), item); } else { this.populated(item.path, item._docs[id], item); } } } init(this, doc, this._doc); this.emit('init', this); this.constructor.emit('init', this); this.$__._id = this._id; return this; }; /*! * 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, prefix) { prefix = prefix || ''; var keys = Object.keys(obj); var len = keys.length; var schema; var path; var i; var 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.isObject(obj[i]) && (!obj[i].constructor || utils.getFunctionName(obj[i].constructor) === 'Object')) { // assume nested object if (!doc[i]) { doc[i] = {}; } init(self, obj[i], doc[i], path + '.'); } else if (!schema) { doc[i] = obj[i]; } else { if (obj[i] === null) { doc[i] = null; } else if (obj[i] !== undefined) { if (schema) { 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 })); } } 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 */ Document.prototype.update = function update() { var args = utils.args(arguments); args.unshift({_id: this._id}); return this.constructor.update.apply(this.constructor, args); }; /** * 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 * @api public */ Document.prototype.$set = function $set(path, val, type, options) { if (type && utils.getFunctionName(type.constructor) === 'Object') { options = type; type = undefined; } options = options || {}; var merge = options.merge; var adhoc = type && type !== true; var constructing = type === true; var adhocs; var strict = 'strict' in options ? options.strict : this.$__.strictMode; if (adhoc) { adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); adhocs[path] = Schema.interpretAsType(path, type, this.schema.options); } if (typeof path !== 'string') { // new Document({ key: val }) if (path === null || path === void 0) { var _ = path; path = val; val = _; } else { var prefix = val ? val + '.' : ''; if (path instanceof Document) { if (path.$__isNested) { path = path.toObject(); } else { path = path._doc; } } var keys = Object.keys(path); var len = keys.length; var i = 0; var pathtype; var key; if (len === 0 && !this.schema.options.minimize) { if (val) { this.$set(val, {}); } return this; } while (i < len) { _handleIndex.call(this, i++); } return this; } } function _handleIndex(i) { key = keys[i]; var pathName = prefix + key; pathtype = this.schema.pathType(pathName); if (path[key] !== null && path[key] !== void 0 // need to know if plain object - no Buffer, ObjectId, ref, etc && utils.isObject(path[key]) && (!path[key].constructor || utils.getFunctionName(path[key].constructor) === 'Object') && pathtype !== 'virtual' && pathtype !== 'real' && !(this.$__path(pathName) instanceof MixedSchema) && !(this.schema.paths[pathName] && this.schema.paths[pathName].options && this.schema.paths[pathName].options.ref)) { this.$set(path[key], prefix + key, constructing); } else if (strict) { // Don't overwrite defaults with undefined keys (gh-3981) if (constructing && path[key] === void 0 && this.get(key) !== void 0) { return; } if (pathtype === 'real' || pathtype === 'virtual') { // Check for setting single embedded schema to document (gh-3535) var 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); } else if (pathtype === 'nested' && path[key] instanceof Document) { this.$set(prefix + key, path[key].toObject({transform: false}), constructing); } 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); } } var pathType = this.schema.pathType(path); if (pathType === 'nested' && val) { if (utils.isObject(val) && (!val.constructor || utils.getFunctionName(val.constructor) === 'Object')) { if (!merge) { this.setValue(path, null); cleanModifiedSubpaths(this, path); } if (Object.keys(val).length === 0) { this.setValue(path, {}); this.markModified(path); cleanModifiedSubpaths(this, path); } else { this.$set(val, path, constructing); } return this; } this.invalidate(path, new MongooseError.CastError('Object', val, path)); return this; } var schema; var parts = path.split('.'); if (pathType === 'adhocOrUndefined' && strict) { // check for roots that are Mixed types var mixed; for (i = 0; i < parts.length; ++i) { var subpath = parts.slice(0, i + 1).join('.'); schema = this.schema.path(subpath); if (schema instanceof MixedSchema) { // allow changes to sub paths of mixed types mixed = true; break; } // 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; } } if (!mixed) { 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 var cur = this._doc; var 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 v5. if (!this.isSelected(curPath)) { this.unmarkModified(curPath); } cur = this.getValue(curPath); } } var 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) { subpath = parts.slice(0, i + 1).join('.'); if (this.isDirectModified(subpath) // earlier prefixes that are already // marked as dirty have precedence || this.get(subpath) === null) { pathToMark = subpath; break; } } if (!pathToMark) { pathToMark = path; } } // if this doc is being constructed we should not trigger getters var priorVal = constructing ? undefined : this.getValue(path); if (!schema) { this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); return this; } var 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 var didPopulate = false; if (schema.options && schema.options.ref && val instanceof Document && (schema.options.ref === val.constructor.modelName || schema.options.ref === val.constructor.baseModelName)) { if (this.ownerDocument) { this.ownerDocument().populated(this.$__fullPath(path), val._id, {model: val.constructor}); } else { this.populated(path, val._id, {model: val.constructor}); } didPopulate = true; } var 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 && Array.isArray(val) && val.length > 0 && val[0] instanceof Document && val[0].constructor.modelName && (schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.baseModelName || schema.options[this.schema.options.typeKey][0].ref === val[0].constructor.modelName)) { if (this.ownerDocument) { popOpts = { model: val[0].constructor }; this.ownerDocument().populated(this.$__fullPath(path), val.map(function(v) { return v._id; }), popOpts); } else { popOpts = { model: val[0].constructor }; this.populated(path, val.map(function(v) { return v._id; }), popOpts); } didPopulate = true; } var setterContext = constructing && this.$__.$options.priorDoc ? this.$__.$options.priorDoc : this; val = schema.applySetters(val, setterContext, false, priorVal); if (!didPopulate && this.$__.populated) { delete this.$__.populated[path]; } this.$markValid(path); } catch (e) { 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 (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { cleanModifiedSubpaths(this, path); } return this; }; /** * 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 */ Document.prototype.set = Document.prototype.$set; /** * Determine if we should mark this change as modified. * * @return {Boolean} * @api private * @method $__shouldModify * @memberOf Document */ Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) { if (this.isNew) { return true; } if (undefined === val && !this.isSelected(path)) { // when a path is not selected in a query, its initial // value will be undefined. return true; } if (undefined === val && 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 || this.get(path))) { 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 */ Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) { Embedded = Embedded || require('./types/embedded'); var shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts, schema, val, priorVal); var _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.indexOf(path + '.') === 0) { _this.$__.activePaths.ignore(modifiedPath); } }); } } var obj = this._doc; var i = 0; var l = parts.length; var cur = ''; for (; i < l; i++) { var next = i + 1; var last = next === l; cur += (cur ? '.' + parts[i] : parts[i]); if (last) { obj[parts[i]] = val; } else { if (obj[parts[i]] && utils.getFunctionName(obj[parts[i]].constructor) === 'Object') { 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 * @api public */ Document.prototype.get = function(path, type) { var adhoc; if (type) { adhoc = Schema.interpretAsType(path, type, this.schema.options); } var schema = this.$__path(path) || this.schema.virtualpath(path); var pieces = path.split('.'); var obj = this._doc; if (schema instanceof VirtualType) { return schema.applyGetters(null, this); } for (var i = 0, l = pieces.length; i < l; i++) { obj = obj === null || obj === void 0 ? undefined : obj[pieces[i]]; } if (adhoc) { obj = adhoc.cast(obj); } if (schema) { obj = schema.applyGetters(obj, this); } return obj; }; /** * Returns the schematype for the given `path`. * * @param {String} path * @api private * @method $__path * @memberOf Document */ Document.prototype.$__path = function(path) { var adhocs = this.$__.adhocPaths, adhocType = adhocs && adhocs[path]; 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 * @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 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` * @return {Array} * @api public */ Document.prototype.modifiedPaths = function(options) { options = options || {}; var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); var _this = this; return directModifiedPaths.reduce(function(list, path) { var 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; } var cur = _this.get(path); if (cur != null && typeof cur === 'object') { if (cur._doc) { cur = cur._doc; } Object.keys(cur). filter(function(key) { return list.indexOf(path + '.' + key) === -1; }). forEach(function(key) { list.push(path + '.' + key); }); } return list; }, []); }; /** * Returns true if this document was modified, else false. * * 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(' '); } var modified = modifiedPaths || this.modifiedPaths(); var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); var isModifiedChild = paths.some(function(path) { return !!~modified.indexOf(path); }); return isModifiedChild || paths.some(function(path) { return directModifiedPaths.some(function(mod) { return mod === path || path.indexOf(mod + '.') === 0; }); }); } return this.$__.activePaths.some('modify'); }; /** * Checks if a path is set to its default. * * ####Example * * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); * var m = new MyModel(); * m.$isDefault('name'); // true * * @memberOf Document * @method $isDefault * @param {String} [path] * @return {Boolean} * @api public */ Document.prototype.$isDefault = function(path) { return (path in this.$__.activePaths.states.default); }; /** * 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 * @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} path * @return {Boolean} * @api public */ Document.prototype.isDirectModified = function(path) { return (path in this.$__.activePaths.states.modify); }; /** * Checks if `path` was initialized. * * @param {String} path * @return {Boolean} * @api public */ Document.prototype.isInit = function(path) { return (path in this.$__.activePaths.states.init); }; /** * 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} path * @return {Boolean} * @api public */ Document.prototype.isSelected = function isSelected(path) { if (this.$__.selected) { if (path === '_id') { return this.$__.selected._id !== 0; } var paths = Object.keys(this.$__.selected); var i = paths.length; var inclusive = null; var cur; if (i === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } while (i--) { cur = paths[i]; 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; } i = paths.length; var pathDot = path + '.'; while (i--) { cur = paths[i]; if (cur === '_id') { continue; } if (cur.indexOf(pathDot) === 0) { return inclusive || cur !== pathDot; } if (pathDot.indexOf(cur + '.') === 0) { return inclusive; } } return !inclusive; } return true; }; /** * 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) { if (path === '_id') { return this.$__.selected._id !== 0; } var paths = Object.keys(this.$__.selected); var i = paths.length; var inclusive = null; var cur; if (i === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } while (i--) { cur = paths[i]; 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; } return !inclusive; } return true; }; /** * 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 {Object} optional options internal options * @param {Function} callback optional callback called after validation completes, passing an error if one occurred * @return {Promise} Promise * @api public */ Document.prototype.validate = function(options, callback) { if (typeof options === 'function') { callback = options; options = null; } return utils.promiseOrCallback(callback, cb => this.$__validate(function(error) { cb(error); })); }; /*! * ignore */ function _getPathsToValidate(doc) { var i; var len; // only validate required fields when necessary var paths = Object.keys(doc.$__.activePaths.states.require).filter(function(path) { if (!doc.isSelected(path) && !doc.isModified(path)) { return false; } var p = doc.schema.path(path); if (typeof p.originalRequiredValue === 'function') { return p.originalRequiredValue.call(doc); } return true; }); paths = paths.concat(Object.keys(doc.$__.activePaths.states.init)); paths = paths.concat(Object.keys(doc.$__.activePaths.states.modify)); paths = paths.concat(Object.keys(doc.$__.activePaths.states.default)); if (!doc.ownerDocument) { var subdocs = doc.$__getAllSubdocs(); var subdoc; len = subdocs.length; var modifiedPaths = doc.modifiedPaths(); for (i = 0; i < len; ++i) { subdoc = subdocs[i]; if (doc.isModified(subdoc.$basePath, modifiedPaths) && !doc.isDirectModified(subdoc.$basePath)) { // Remove child paths for now, because we'll be validating the whole // subdoc paths = paths.filter(function(p) { return p != null && p.indexOf(subdoc.$basePath + '.') !== 0; }); paths.push(subdoc.$basePath); } } } // gh-661: if a whole array is modified, make sure to run validation on all // the children as well len = paths.length; for (i = 0; i < len; ++i) { var path = paths[i]; var _pathType = doc.schema.path(path); if (!_pathType || !_pathType.$isMongooseArray || _pathType.$isMongooseDocumentArray) { continue; } var val = doc.getValue(path); if (val) { var numElements = val.length; for (var j = 0; j < numElements; ++j) { paths.push(path + '.' + j); } } } var flattenOptions = { skipArrays: true }; len = paths.length; for (i = 0; i < len; ++i) { var pathToCheck = paths[i]; if (doc.schema.nested[pathToCheck]) { var _v = doc.getValue(pathToCheck); if (isMongooseObject(_v)) { _v = _v.toObject({ transform: false }); } var flat = flatten(_v, '', flattenOptions); var _subpaths = Object.keys(flat).map(function(p) { return pathToCheck + '.' + p; }); paths = paths.concat(_subpaths); } } return paths; } /*! * ignore */ Document.prototype.$__validate = function(callback) { const _this = this; const _complete = function() { var err = _this.$__.validationError; _this.$__.validationError = undefined; _this.emit('validate', _this); _this.constructor.emit('validate', _this); if (err) { for (var key in err.errors) { // Make sure cast errors persist if (!_this.__parent && err.errors[key] instanceof MongooseError.CastError) { _this.invalidate(key, err.errors[key]); } } return err; } }; // only validate required fields when necessary const paths = _getPathsToValidate(this); 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; var 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); }; var validatePath = function(path) { if (path == null || validated[path]) { return; } validated[path] = true; total++; process.nextTick(function() { const p = _this.schema.path(path); if (!p) { return --total || complete(); } // If user marked as invalid or there was a cast error, don't validate if (!_this.$isValid(path)) { --total || complete(); return; } const val = _this.getValue(path); const scope = path in _this.$__.pathsToScopes ? _this.$__.pathsToScopes[path] : _this; p.doValidate(val, function(err) { if (err) { _this.invalidate(path, err, undefined, true); } --total || complete(); }, scope); }); }; const numPaths = paths.length; for (let i = 0; i < numPaths; ++i) { validatePath(paths[i]); } }; /** * Executes registered validation rules (skipping asynchronous validators) for this document. * * ####Note: * * This method is useful if you need synchronous validation. * * ####Example: * * var err = doc.validateSync(); * if ( err ){ * handleError( err ); * } else { * // validation passed * } * * @param {Array|string} pathsToValidate only validate the given paths * @return {MongooseError|undefined} MongooseError if there are errors during validation, or undefined if there is no error. * @api public */ Document.prototype.validateSync = function(pathsToValidate) { var _this = this; if (typeof pathsToValidate === 'string') { pathsToValidate = pathsToValidate.split(' '); } // only validate required fields when necessary var paths = _getPathsToValidate(this); if (pathsToValidate && pathsToValidate.length) { var tmp = []; for (var i = 0; i < paths.length; ++i) { if (pathsToValidate.indexOf(paths[i]) !== -1) { tmp.push(paths[i]); } } paths = tmp; } var validating = {}; paths.forEach(function(path) { if (validating[path]) { return; } validating[path] = true; var p = _this.schema.path(path); if (!p) { return; } if (!_this.$isValid(path)) { return; } var val = _this.getValue(path); var err = p.doValidateSync(val, _this); if (err) { _this.invalidate(path, err, undefined, true); } }); var err = _this.$__.validationError; _this.$__.validationError = undefined; _this.emit('validate', _this); _this.constructor.emit('validate', _this); if (err) { for (var 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 * @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 * @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; } }; /** * Saves this document. * * ####Example: * * product.sold = Date.now(); * product.save(function (err, product, numAffected) { * if (err) .. * }) * * The callback will receive three parameters * * 1. `err` if an error occurred * 2. `product` which is the saved `product` * 3. `numAffected` will be 1 when the document was successfully persisted to MongoDB, otherwise 0. Unless you tweak mongoose's internals, you don't need to worry about checking this parameter for errors - checking `err` is sufficient to make sure your document was properly saved. * * As an extra measure of flow control, save will return a Promise. * ####Example: * product.save().then(function(product) { * ... * }); * * @param {Object} [options] options optional options * @param {Object} [options.safe] overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe) * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. * @param {Function} [fn] optional callback * @method save * @memberOf Document * @return {Promise} Promise * @api public * @see middleware http://mongoosejs.com/docs/middleware.html */ /** * Checks if a path is invalid * * @param {String} path the field to check * @method $isValid * @memberOf Document * @api private */ Document.prototype.$isValid = function(path) { return !this.$__.validationError || !this.$__.validationError.errors[path]; }; /** * Resets the internal modified state of this document. * * @api private * @return {Document} * @method $__reset * @memberOf Document */ Document.prototype.$__reset = function reset() { var _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) { var i = array.length; while (i--) { var doc = array[i]; if (!doc) { continue; } doc.$__reset(); } }); this.$__.activePaths. map('init', 'modify', function(i) { return _this.getValue(i); }). filter(function(val) { return val && val.$isSingleNested; }). forEach(function(doc) { doc.$__reset(); }); // clear atomics this.$__dirty().forEach(function(dirt) { var type = dirt.value; if (type && type._atomics) { type._atomics = {}; } }); // 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; }; /** * Returns this documents dirty paths / vals. * * @api private * @method $__dirty * @memberOf Document */ Document.prototype.$__dirty = function() { var _this = this; var 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)) { 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. var minimal = [], lastPath, top; all.forEach(function(item) { if (!item) { return; } if (item.path.indexOf(lastPath) !== 0) { lastPath = item.path + '.'; minimal.push(item); top = item; } else { // special case for top level MongooseArrays if (top.value && top.value._atomics && top.value.hasAtomics()) { // 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._atomics = {}; top.value._atomics.$set = top.value; } } }); top = lastPath = null; return minimal; }; /** * Assigns/compiles `schema` into this documents prototype. * * @param {Schema} schema * @api private * @method $__setSchema * @memberOf Document */ Document.prototype.$__setSchema = function(schema) { schema.plugin(idGetter, { deduplicate: true }); compile(schema.tree, this, undefined, schema.options); this.schema = schema; }; /** * Get active path that were changed and are arrays * * @api private * @method $__getArrayPathsToValidate * @memberOf Document */ 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 */ Document.prototype.$__getAllSubdocs = function() { DocumentArray || (DocumentArray = require('./types/documentarray')); Embedded = Embedded || require('./types/embedded'); function docReducer(doc, seed, path) { var val = doc[path]; if (val instanceof Embedded) { seed.push(val); } if (val && val.$isSingleNested) { seed = Object.keys(val._doc).reduce(function(seed, path) { return docReducer(val._doc, seed, path); }, seed); seed.push(val); } if (val && val.isMongooseDocumentArray) { val.forEach(function _docReduce(doc) { if (!doc || !doc._doc) { return; } if (doc instanceof Embedded) { seed.push(doc); } seed = Object.keys(doc._doc).reduce(function(seed, path) { return docReducer(doc._doc, seed, path); }, seed); }); } else if (val instanceof Document && val.$__isNested) { if (val) { seed = Object.keys(val).reduce(function(seed, path) { return docReducer(val, seed, path); }, seed); } } return seed; } var _this = this; var subDocs = Object.keys(this._doc).reduce(function(seed, path) { return docReducer(_this, seed, path); }, []); return subDocs; }; /*! * Runs queued functions */ function applyQueue(doc) { var q = doc.schema && doc.schema.callQueue; if (!q.length) { return; } var pair; for (var i = 0; i < q.length; ++i) { pair = q[i]; 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); } else if (this.listeners && this.listeners('error').length) { this.emit('error', err); } }; /** * Internal helper for toObject() and toJSON() that doesn't manipulate options * * @api private * @method $toObject * @memberOf Document */ Document.prototype.$toObject = function(options, json) { let defaultOptions = { transform: true, flattenDecimals: true }; // merge base default options with Schema's set default options if available. // `clone` is necessary here because `utils.options` directly modifies the second input. if (json && this.schema.options.toJSON) { defaultOptions = utils.options(defaultOptions, clone(this.schema.options.toJSON)); } else if (this.schema.options.toObject) { defaultOptions = utils.options(defaultOptions, clone(this.schema.options.toObject)); } // If options do not exist or is not an object, set it to empty object options = options && utils.getFunctionName(options.constructor) === 'Object' ? clone(options) : {}; let _minimize; if (options.minimize != null) { _minimize = options.minimize; } else if (defaultOptions.minimize != null) { _minimize = defaultOptions.minimize; } else { _minimize = this.schema.options.minimize; } const cloneOptions = Object.assign(utils.clone(options), { _isNested: true, json: json, minimize: _minimize }); // _isNested will only be true if this is not the top level document, we // should never depopulate if (options.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; // remember the root transform function // to save it from being overwritten by sub-transform functions var originalTransform = options.transform; var ret = clone(this._doc, cloneOptions) || {}; if (options.getters) { applyGetters(this, ret, 'paths', cloneOptions); // applyGetters for paths will add nested empty objects; // if minimize is set, we need to remove them. if (options.minimize) { ret = minimize(ret) || {}; } } if (options.virtuals || options.getters && options.virtuals !== false) { applyGetters(this, ret, 'virtuals', cloneOptions); } if (options.versionKey === false && this.schema.options.versionKey) { delete ret[this.schema.options.versionKey]; } var 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 === true || (this.schema.options.toObject && transform)) { var opts = options.json ? this.schema.options.toJSON : this.schema.options.toObject; if (opts) { transform = (typeof options.transform === 'function' ? options.transform : opts.transform); } } else { options.transform = originalTransform; } if (typeof transform === 'function') { var xformed = transform(this, ret, options); if (typeof xformed !== 'undefined') { ret = xformed; } } return ret; }; /** * Converts this document into a plain javascript object, ready for storage in MongoDB. * * 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) * - `virtuals` apply virtual getters (can override `getters` option) * - `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) * * ####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`: * * if (!schema.options.toObject) schema.options.toObject = {}; * 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; * } * * var 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' } * * Transforms are applied _only to the document and are not applied to sub-documents_. * * Transforms, like all of these options, are also available for `toJSON`. * * 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] * @return {Object} js object * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html * @api public * @memberOf Document */ 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) { var keys = Object.keys(obj), i = keys.length, hasKeys, key, 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`. * * @param {Document} self * @param {Object} json * @param {String} type either `virtuals` or `paths` * @return {Object} `json` */ function applyGetters(self, json, type, options) { var schema = self.schema; var paths = Object.keys(schema[type]); var i = paths.length; var numPaths = i; var path; var cur = self._doc; var v; if (!cur) { return json; } if (type === 'virtuals') { for (i = 0; i < numPaths; ++i) { path = paths[i]; parts = path.split('.'); v = clone(self.get(path), options); if (v === void 0) { continue; } plen = parts.length; cur = json; for (var j = 0; j < plen - 1; ++j) { cur[parts[j]] = cur[parts[j]] || {}; cur = cur[parts[j]]; } cur[parts[plen - 1]] = v; } return json; } while (i--) { path = paths[i]; var parts = path.split('.'); var plen = parts.length; var last = plen - 1; var branch = json; var part; cur = self._doc; for (var ii = 0; ii < plen; ++ii) { part = parts[ii]; v = cur[part]; if (ii === last) { branch[part] = clone(self.get(path), options); } else if (v == null) { if (part in cur) { branch[part] = v; } break; } else { branch = branch[part] || (branch[part] = {}); } cur = v; } } 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 * @api public * @memberOf Document */ Document.prototype.toJSON = function(options) { return this.$toObject(options, true); }; /** * Helper for console.log * * @api public * @method inspect * @memberOf Document */ Document.prototype.inspect = function(options) { var isPOJO = options && utils.getFunctionName(options.constructor) === 'Object'; var opts; if (isPOJO) { opts = options; opts.minimize = false; } return this.toObject(opts); }; /** * Helper for console.log * * @api public * @method toString * @memberOf Document */ Document.prototype.toString = function() { return inspect(this.inspect()); }; /** * Returns true if the Document stores the same data as doc. * * 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 */ Document.prototype.equals = function(doc) { if (!doc) { return false; } var tid = this.get('_id'); var docid = doc.get ? doc.get('_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 */ Document.prototype.populate = function populate() { if (arguments.length === 0) { return this; } var pop = this.$__.populate || (this.$__.populate = {}); var args = utils.args(arguments); var fn; if (typeof args[args.length - 1] === 'function') { fn = args.pop(); } // allow `doc.populate(callback)` if (args.length) { // use hash to remove duplicate paths var res = utils.populate.apply(null, args); for (var i = 0; i < res.length; ++i) { pop[res[i].path] = res[i]; } } if (fn) { var paths = utils.object.vals(pop); this.$__.populate = undefined; paths.__noPromise = true; var topLevelModel = this.constructor; if (this.$__isNested) { topLevelModel = this.$__.scope.constructor; var nestedPath = this.$__.nestedPath; paths.forEach(function(populateOptions) { populateOptions.path = nestedPath + '.' + populateOptions.path; }); } topLevelModel.populate(this, paths, fn); } return this; }; /** * Explicitly executes population and returns a promise. Useful for ES2015 * integration. * * ####Example: * * var promise = doc. * populate('company'). * populate({ * path: 'notes', * match: /airline/, * select: 'text', * model: 'modelName' * options: opts * }). * execPopulate(); * * // summary * doc.execPopulate().then(resolve, reject); * * * @see Document.populate #document_Document-populate * @api public * @return {Promise} promise that resolves to the document when population is done * @memberOf Document */ Document.prototype.execPopulate = function() { return utils.promiseOrCallback(null, cb => { this.populate(cb); }); }; /** * 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, undefined is returned. * * @param {String} path * @return {Array|ObjectId|Number|Buffer|String|undefined} * @memberOf Document * @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; } var 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}; 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 */ Document.prototype.depopulate = function(path) { if (typeof path === 'string') { path = path.split(' '); } var i; var populatedIds; if (arguments.length === 0) { // Depopulate all var keys = Object.keys(this.$__.populated); for (i = 0; i < keys.length; i++) { populatedIds = this.populated(keys[i]); if (!populatedIds) { continue; } delete this.$__.populated[keys[i]]; this.$set(keys[i], populatedIds); } return this; } for (i = 0; i < path.length; i++) { populatedIds = this.populated(path[i]); if (!populatedIds) { continue; } delete this.$__.populated[path[i]]; this.$set(path[i], populatedIds); } return this; }; /** * Returns the full path to this document. * * @param {String} [path] * @return {String} * @api private * @method $__fullPath * @memberOf Document */ Document.prototype.$__fullPath = function(path) { // overridden in SubDocuments return path || ''; }; /*! * Module exports. */ Document.ValidationError = ValidationError; module.exports = exports = Document; }).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) },{"../../is-buffer/index.js":335,"./error":419,"./error/objectExpected":423,"./error/objectParameter":424,"./error/strict":426,"./internal":430,"./options":431,"./plugins/idGetter":432,"./schema":434,"./schema/mixed":443,"./schematype":452,"./services/common":453,"./services/document/cleanModifiedSubpaths":454,"./services/document/compile":455,"./services/projection/isDefiningProjection":458,"./services/projection/isExclusive":459,"./types/array":461,"./types/documentarray":464,"./types/embedded":465,"./utils":469,"./virtualtype":470,"_process":507,"events":316,"mpath":471,"util":563}],405:[function(require,module,exports){ 'use strict'; /* eslint-env browser */ /*! * Module dependencies. */ var Document = require('./document.js'); var BrowserDocument = require('./browserDocument.js'); var 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":402,"./document.js":404}],406:[function(require,module,exports){ /*! * ignore */ module.exports = function() {}; },{}],407:[function(require,module,exports){ /*! * Module dependencies. */ var Binary = require('bson').Binary; /*! * Module exports. */ module.exports = exports = Binary; },{"bson":125}],408:[function(require,module,exports){ /*! * ignore */ module.exports = require('bson').Decimal128; },{"bson":125}],409:[function(require,module,exports){ /*! * Module exports. */ exports.Binary = require('./binary'); exports.Decimal128 = require('./decimal128'); exports.ObjectId = require('./objectid'); exports.ReadPreference = require('./ReadPreference'); },{"./ReadPreference":406,"./binary":407,"./decimal128":408,"./objectid":410}],410:[function(require,module,exports){ /*! * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId * @constructor NodeMongoDbObjectId * @see ObjectId */ var ObjectId = require('bson').ObjectID; /*! * ignore */ module.exports = exports = ObjectId; },{"bson":125}],411:[function(require,module,exports){ (function (global){ /*! * ignore */ var driver; if (typeof window === 'undefined') { driver = require('./node-mongodb-native'); if (global.MONGOOSE_DRIVER_PATH) { driver = require(global.MONGOOSE_DRIVER_PATH); } } else { driver = require('./browser'); } /*! * ignore */ module.exports = driver; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./browser":409,"./node-mongodb-native":415}],412:[function(require,module,exports){ /*! * Module dependencies. */ var mongodb = require('mongodb'); var ReadPref = mongodb.ReadPreference; /*! * Converts arguments to ReadPrefs the driver * can understand. * * @param {String|Array} pref * @param {Array} [tags] */ module.exports = function readPref(pref, tags) { if (Array.isArray(pref)) { tags = pref[1]; pref = pref[0]; } if (pref instanceof ReadPref) { return 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 new ReadPref(pref, tags); }; },{"mongodb":374}],413:[function(require,module,exports){ /*! * Module dependencies. */ var Binary = require('mongodb').Binary; module.exports = exports = Binary; },{"mongodb":374}],414:[function(require,module,exports){ /*! * ignore */ module.exports = require('mongodb').Decimal128; },{"mongodb":374}],415:[function(require,module,exports){ arguments[4][409][0].apply(exports,arguments) },{"./ReadPreference":412,"./binary":413,"./decimal128":414,"./objectid":416,"dup":409}],416:[function(require,module,exports){ /*! * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId * @constructor NodeMongoDbObjectId * @see ObjectId */ var ObjectId = require('mongodb').ObjectId; /*! * ignore */ module.exports = exports = ObjectId; },{"mongodb":374}],417:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); var util = require('util'); /** * Casting Error constructor. * * @param {String} type * @param {String} value * @inherits MongooseError * @api private */ function CastError(type, value, path, reason) { var stringValue = util.inspect(value); stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"'); if (stringValue.charAt(0) !== '"') { stringValue = '"' + stringValue + '"'; } MongooseError.call(this, 'Cast to ' + type + ' failed for value ' + stringValue + ' at path "' + path + '"'); this.name = 'CastError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.stringValue = stringValue; this.kind = type; this.value = value; this.path = path; this.reason = reason; } /*! * Inherits from MongooseError. */ CastError.prototype = Object.create(MongooseError.prototype); CastError.prototype.constructor = MongooseError; /*! * ignore */ CastError.prototype.setModel = function(model) { this.model = model; this.message = 'Cast to ' + this.kind + ' failed for value ' + this.stringValue + ' at path "' + this.path + '"' + ' for model "' + model.modelName + '"'; }; /*! * exports */ module.exports = CastError; },{"./":419,"util":563}],418:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); /*! * DivergentArrayError constructor. * * @inherits MongooseError */ function DivergentArrayError(paths) { var 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 MongooseError.call(this, msg); this.name = 'DivergentArrayError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } } /*! * Inherits from MongooseError. */ DivergentArrayError.prototype = Object.create(MongooseError.prototype); DivergentArrayError.prototype.constructor = MongooseError; /*! * exports */ module.exports = DivergentArrayError; },{"./":419}],419:[function(require,module,exports){ /** * MongooseError constructor * * @param {String} msg Error message * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error */ function MongooseError(msg) { Error.call(this); if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.message = msg; this.name = 'MongooseError'; } /*! * Inherits from Error. */ MongooseError.prototype = Object.create(Error.prototype); MongooseError.prototype.constructor = Error; /*! * Module exports. */ module.exports = exports = MongooseError; /** * The default built-in validator error messages. * * @see Error.messages #error_messages_MongooseError-messages * @api public */ 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 */ MongooseError.DocumentNotFoundError = require('./notFound'); /** * An instance of this error class will be returned when mongoose failed to * cast a value. * * @api public */ MongooseError.CastError = require('./cast'); /** * An instance of this error class will be returned when [validation](/docs/validation.html) failed. * * @api public */ MongooseError.ValidationError = require('./validation'); /** * A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances * * @api public */ 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 */ MongooseError.VersionError = require('./version'); /** * 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 */ MongooseError.OverwriteModelError = require('./overwriteModel'); /** * Thrown when you try to access a model that has not been registered yet * * @api public */ 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 */ MongooseError.DivergentArrayError = require('./divergentArray'); },{"./cast":417,"./divergentArray":418,"./messages":420,"./missingSchema":421,"./notFound":422,"./overwriteModel":425,"./validation":427,"./validator":428,"./version":429}],420:[function(require,module,exports){ /** * The default built-in validator error messages. These may be customized. * * // customize within each schema or globally like so * var 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 */ var 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.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}).'; },{}],421:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); /*! * MissingSchema Error constructor. * * @inherits MongooseError */ function MissingSchemaError(name) { var msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + 'Use mongoose.model(name, schema)'; MongooseError.call(this, msg); this.name = 'MissingSchemaError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } } /*! * Inherits from MongooseError. */ MissingSchemaError.prototype = Object.create(MongooseError.prototype); MissingSchemaError.prototype.constructor = MongooseError; /*! * exports */ module.exports = MissingSchemaError; },{"./":419}],422:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ var MongooseError = require('./'); var util = require('util'); /*! * OverwriteModel Error constructor. * * @inherits MongooseError */ function DocumentNotFoundError(query) { var msg; var messages = MongooseError.messages; if (messages.DocumentNotFoundError != null) { msg = typeof messages.DocumentNotFoundError === 'function' ? messages.DocumentNotFoundError(query) : messages.DocumentNotFoundError; } else { msg = 'No document found for query "' + util.inspect(query) + '"'; } MongooseError.call(this, msg); this.name = 'DocumentNotFoundError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.query = query; } /*! * Inherits from MongooseError. */ DocumentNotFoundError.prototype = Object.create(MongooseError.prototype); DocumentNotFoundError.prototype.constructor = MongooseError; /*! * exports */ module.exports = DocumentNotFoundError; },{"./":419,"util":563}],423:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); /** * Strict mode error constructor * * @param {String} type * @param {String} value * @inherits MongooseError * @api private */ function ObjectExpectedError(path, val) { MongooseError.call(this, 'Tried to set nested object field `' + path + '` to primitive value `' + val + '` and strict mode is set to throw.'); this.name = 'ObjectExpectedError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.path = path; } /*! * Inherits from MongooseError. */ ObjectExpectedError.prototype = Object.create(MongooseError.prototype); ObjectExpectedError.prototype.constructor = MongooseError; module.exports = ObjectExpectedError; },{"./":419}],424:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); /** * 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 * @inherits MongooseError * @api private */ function ObjectParameterError(value, paramName, fnName) { MongooseError.call(this, 'Parameter "' + paramName + '" to ' + fnName + '() must be an object, got ' + value.toString()); this.name = 'ObjectParameterError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } } /*! * Inherits from MongooseError. */ ObjectParameterError.prototype = Object.create(MongooseError.prototype); ObjectParameterError.prototype.constructor = MongooseError; module.exports = ObjectParameterError; },{"./":419}],425:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); /*! * OverwriteModel Error constructor. * * @inherits MongooseError */ function OverwriteModelError(name) { MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); this.name = 'OverwriteModelError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } } /*! * Inherits from MongooseError. */ OverwriteModelError.prototype = Object.create(MongooseError.prototype); OverwriteModelError.prototype.constructor = MongooseError; /*! * exports */ module.exports = OverwriteModelError; },{"./":419}],426:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); /** * Strict mode error constructor * * @param {String} type * @param {String} value * @inherits MongooseError * @api private */ function StrictModeError(path, msg) { msg = msg || 'Field `' + path + '` is not in schema and strict ' + 'mode is set to throw.'; MongooseError.call(this, msg); this.name = 'StrictModeError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.path = path; } /*! * Inherits from MongooseError. */ StrictModeError.prototype = Object.create(MongooseError.prototype); StrictModeError.prototype.constructor = MongooseError; module.exports = StrictModeError; },{"./":419}],427:[function(require,module,exports){ /*! * Module requirements */ const MongooseError = require('./'); /** * Document Validation Error * * @api private * @param {Document} instance * @inherits MongooseError */ function ValidationError(instance) { this.errors = {}; this._message = ''; if (instance && instance.constructor.name === 'model') { this._message = instance.constructor.modelName + ' validation failed'; MongooseError.call(this, this._message); } else { this._message = 'Validation failed'; MongooseError.call(this, this._message); } this.name = 'ValidationError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } if (instance) { instance.errors = this.errors; } } /*! * Inherits from MongooseError. */ ValidationError.prototype = Object.create(MongooseError.prototype); ValidationError.prototype.constructor = MongooseError; /** * Console.log helper */ ValidationError.prototype.toString = function() { return this.name + ': ' + _generateMessage(this); }; /*! * inspect helper */ ValidationError.prototype.inspect = function() { return Object.assign(new Error(this.message), this); }; /*! * Helper for JSON.stringify */ ValidationError.prototype.toJSON = function() { return Object.assign({}, this, { message: this.message }); }; /*! * add message */ ValidationError.prototype.addError = function(path, error) { this.errors[path] = error; this.message = this._message + ': ' + _generateMessage(this); }; /*! * ignore */ function _generateMessage(err) { var keys = Object.keys(err.errors || {}); var len = keys.length; var msgs = []; var key; for (var 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 = exports = ValidationError; },{"./":419}],428:[function(require,module,exports){ /*! * Module dependencies. */ var MongooseError = require('./'); /** * Schema validator error * * @param {Object} properties * @inherits MongooseError * @api private */ function ValidatorError(properties) { var msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } var message = this.formatMessage(msg, properties); MongooseError.call(this, message); this.name = 'ValidatorError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.properties = properties; this.kind = properties.type; this.path = properties.path; this.value = properties.value; this.reason = properties.reason; } /*! * Inherits from MongooseError */ ValidatorError.prototype = Object.create(MongooseError.prototype); ValidatorError.prototype.constructor = MongooseError; /*! * 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 }); /*! * Formats error messages */ ValidatorError.prototype.formatMessage = function(msg, properties) { var propertyNames = Object.keys(properties); for (var i = 0; i < propertyNames.length; ++i) { var propertyName = propertyNames[i]; if (propertyName === 'message') { continue; } msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); } return msg; }; /*! * toString helper */ ValidatorError.prototype.toString = function() { return this.message; }; /*! * exports */ module.exports = ValidatorError; },{"./":419}],429:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ var MongooseError = require('./'); /** * Version Error constructor. * * @inherits MongooseError * @api private */ function VersionError(doc) { MongooseError.call(this, 'No matching document found for id "' + doc._id + '"'); this.name = 'VersionError'; } /*! * Inherits from MongooseError. */ VersionError.prototype = Object.create(MongooseError.prototype); VersionError.prototype.constructor = MongooseError; /*! * exports */ module.exports = VersionError; },{"./":419}],430:[function(require,module,exports){ /*! * Dependencies */ var StateMachine = require('./statemachine'); var 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.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 = {}; // embedded docs this.ownerDocument = undefined; this.fullPath = undefined; } },{"./statemachine":460}],431:[function(require,module,exports){ 'use strict'; /*! * ignore */ exports.internalToObjectOptions = { transform: false, virtuals: false, getters: false, _skipDepopulateTopLevel: true, depopulate: true, flattenDecimals: false }; },{}],432:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function(schema) { // ensure the documents receive an id getter unless disabled var autoIdGetter = !schema.paths['id'] && (!schema.options.noVirtualId && schema.options.id); if (autoIdGetter) { 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; } },{}],433:[function(require,module,exports){ (function (global){ /*! * ignore */ const assert = require('assert'); const mquery = require('mquery'); /** * Helper for multiplexing promise implementations * * @api private */ var 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":88,"mquery":477}],434:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ var readPref = require('./drivers').ReadPreference; var EventEmitter = require('events').EventEmitter; var VirtualType = require('./virtualtype'); var utils = require('./utils'); var MongooseTypes; var Kareem = require('kareem'); var SchemaType = require('./schematype'); var mpath = require('mpath'); /** * Schema constructor. * * ####Example: * * var child = new Schema({ name: String }); * var schema = new Schema({ name: String, age: Number, children: [child] }); * var 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) * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true * - [capped](/docs/guide.html#capped): bool - defaults to false * - [collection](/docs/guide.html#collection): string - no default * - [emitIndexErrors](/docs/guide.html#emitIndexErrors): bool - defaults to false. * - [id](/docs/guide.html#id): bool - defaults to true * - [_id](/docs/guide.html#_id): bool - defaults to true * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true * - [read](/docs/guide.html#read): string * - [safe](/docs/guide.html#safe): bool - defaults to true. * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null` * - [strict](/docs/guide.html#strict): bool - defaults to true * - [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' * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` * - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v" * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) * * ####Note: * * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ * * @param {Object} definition * @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.statics = {}; this.tree = {}; this.query = {}; this.childSchemas = []; this.plugins = []; this.s = { hooks: new Kareem() }; this.options = this.defaultOptions(options); // build paths if (obj) { this.add(obj); } // check if _id's value is a subdocument (gh-2276) var _idSubDoc = obj && obj._id && utils.isObject(obj._id); // ensure the documents get an auto _id unless disabled var auto_id = !this.paths['_id'] && (!this.options.noId && this.options._id) && !_idSubDoc; if (auto_id) { var _obj = {_id: {auto: true}}; _obj._id[this.options.typeKey] = Schema.ObjectId; this.add(_obj); } if (this.options.timestamps) { this.setupTimestamp(this.options.timestamps); } // Assign virtual properties based on alias option aliasFields(this); } /*! * Create virtual properties with alias field */ function aliasFields(schema) { for (var path in schema.paths) { if (!schema.paths[path].options) continue; var prop = schema.paths[path].path; var alias = schema.paths[path].options.alias; if (alias) { if ('string' === typeof alias && alias.length > 0) { if (schema.aliases[alias]) { throw new Error('Duplicate alias, alias ' + alias + ' is used more than once'); } else { 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)); } else { throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias); } } } } /*! * Inherit from EventEmitter. */ Schema.prototype = Object.create(EventEmitter.prototype); Schema.prototype.constructor = Schema; Schema.prototype.instanceOfSchema = 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 */ Object.defineProperty(Schema.prototype, 'childSchemas', { configurable: false, enumerable: true, writable: true }); /** * The original object passed to the schema constructor * * ####Example: * * var schema = new Schema({ a: String }).add({ b: String }); * schema.obj; // { a: String } * * @api public * @property obj * @memberOf Schema */ Schema.prototype.obj; /** * Schema as flat paths * * ####Example: * { * '_id' : SchemaType, * , 'nested.key' : SchemaType, * } * * @api private * @property paths * @memberOf Schema */ Schema.prototype.paths; /** * Schema as a tree * * ####Example: * { * '_id' : ObjectId * , 'nested' : { * 'key' : String * } * } * * @api private * @property tree * @memberOf Schema */ Schema.prototype.tree; /** * Returns a deep copy of the schema * * @return {Schema} the cloned schema * @api public * @memberOf Schema */ Schema.prototype.clone = function() { var s = new Schema(this.paths, this.options); var cloneOpts = {}; s.callQueue = this.callQueue.map(function(f) { return f; }); s.methods = utils.clone(this.methods, cloneOpts); s.statics = utils.clone(this.statics, cloneOpts); s.query = utils.clone(this.query, cloneOpts); s.plugins = Array.prototype.slice.call(this.plugins); s._indexes = utils.clone(this._indexes, cloneOpts); s.s.hooks = this.s.hooks.clone(); s.virtuals = utils.clone(this.virtuals, cloneOpts); return s; }; /** * 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 = utils.clone(options); options = utils.options({ strict: true, bufferCommands: true, capped: false, // { size, max, autoIndexId } versionKey: '__v', 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' }, options); if (options.read) { options.read = readPref(options.read); } return options; }; /** * Adds key path / schema type pairs to this schema. * * ####Example: * * var ToySchema = new Schema; * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); * * @param {Object} obj * @param {String} prefix * @api public */ Schema.prototype.add = function add(obj, prefix) { prefix = prefix || ''; var keys = Object.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (obj[key] == null) { throw new TypeError('Invalid value for schema path `' + prefix + key + '`'); } if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { throw new TypeError('Invalid value for schema Array path `' + prefix + key + '`'); } if (utils.isObject(obj[key]) && (!obj[key].constructor || utils.getFunctionName(obj[key].constructor) === 'Object') && (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) { if (Object.keys(obj[key]).length) { // nested object { last: { name: String }} this.nested[prefix + key] = true; this.add(obj[key], prefix + key + '.'); } else { if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(prefix + key, obj[key]); // mixed type } } else { if (prefix) { this.nested[prefix.substr(0, prefix.length - 1)] = true; } this.path(prefix + key, obj[key]); } } }; /** * Reserved document keys. * * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error. * * on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject * * _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. * * var schema = new Schema(..); * schema.methods.init = function () {} // potentially breaking */ Schema.reserved = Object.create(null); var reserved = Schema.reserved; // Core object reserved['prototype'] = // EventEmitter reserved.emit = reserved.on = reserved.once = reserved.listeners = reserved.removeListener = // document properties and functions reserved.collection = reserved.db = reserved.errors = reserved.init = reserved.isModified = reserved.isNew = reserved.get = reserved.modelName = reserved.save = reserved.schema = reserved.toObject = reserved.validate = reserved.remove = // hooks.js reserved._pres = reserved._posts = 1; /*! * Document keys to print warnings for */ var warnings = {}; warnings.increment = '`increment` should not be used as a schema path name ' + 'unless you have disabled versioning.'; /** * 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) { if (obj === undefined) { if (this.paths[path]) { return this.paths[path]; } if (this.subpaths[path]) { return this.subpaths[path]; } if (this.singleNestedPaths[path]) { return this.singleNestedPaths[path]; } // subpaths? return /\.\d+\.?.*$/.test(path) ? getPositionalPath(this, path) : undefined; } // some path names conflict with document methods if (reserved[path]) { throw new Error('`' + path + '` may not be used as a schema pathname'); } if (warnings[path]) { console.log('WARN: ' + warnings[path]); } // update the tree var subpaths = path.split(/\./), last = subpaths.pop(), branch = this.tree; subpaths.forEach(function(sub, i) { if (!branch[sub]) { branch[sub] = {}; } if (typeof branch[sub] !== 'object') { var msg = 'Cannot set nested path `' + path + '`. ' + 'Parent path `' + subpaths.slice(0, i).concat([sub]).join('.') + '` already set to type ' + branch[sub].name + '.'; throw new Error(msg); } branch = branch[sub]; }); branch[last] = utils.clone(obj); this.paths[path] = Schema.interpretAsType(path, obj, this.options); if (this.paths[path].$isSingleNested) { for (var key in this.paths[path].schema.paths) { this.singleNestedPaths[path + '.' + key] = this.paths[path].schema.paths[key]; } for (key in this.paths[path].schema.singleNestedPaths) { this.singleNestedPaths[path + '.' + key] = this.paths[path].schema.singleNestedPaths[key]; } this.childSchemas.push({ schema: this.paths[path].schema, model: this.paths[path].caster }); } else if (this.paths[path].$isMongooseDocumentArray) { this.childSchemas.push({ schema: this.paths[path].schema, model: this.paths[path].casterConstructor }); } else if (this.paths[path].path === '_id' && this.paths[path].options && this.paths[path].options.unique) { throw new Error('Cannot put unique index on _id'); } return this; }; /** * Converts type arguments into Mongoose Types. * * @param {String} path * @param {Object} obj constructor * @api private */ Schema.interpretAsType = function(path, obj, options) { if (obj instanceof SchemaType) { return obj; } if (obj.constructor) { var constructorName = utils.getFunctionName(obj.constructor); if (constructorName !== 'Object') { var 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' } } var type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) ? obj[options.typeKey] : {}; if (utils.getFunctionName(type.constructor) === 'Object' || type === 'mixed') { return new MongooseTypes.Mixed(path, obj); } if (Array.isArray(type) || Array === type || type === 'array') { // if it was specified through { type } look for `cast` var cast = (Array === type || type === 'array') ? obj.cast : 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], cast); } if (Array.isArray(cast)) { return new MongooseTypes.Array(path, Schema.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.getFunctionName(cast.constructor) === 'Object') { if (Object.keys(cast).length) { // The `minimize` and `typeKey` options propagate to child schemas // declared inline, like `{ arr: [{ val: { $type: String } }] }`. // See gh-3560 var 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; } var 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 (!(name in MongooseTypes)) { throw new TypeError('Undefined type `' + name + '` at array `' + path + '`'); } } return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); } if (type && type.instanceOfSchema) { return new MongooseTypes.Embedded(type, path, obj); } var name; if (Buffer.isBuffer(type)) { name = 'Buffer'; } else { name = typeof type === 'string' ? type // If not string, `type` is a function. Outside of IE, function.name // gives you the function name. In IE, you need to compute it : type.schemaName || utils.getFunctionName(type); } if (name) { name = name.charAt(0).toUpperCase() + name.substring(1); } if (undefined == MongooseTypes[name]) { throw new TypeError('Undefined type `' + name + '` at `' + path + '`\n Did you try nesting Schemas? ' + 'You can only nest using refs or arrays.'); } return new MongooseTypes[name](path, obj); }; /** * Iterates the schemas paths similar to Array#forEach. * * The callback is passed the pathname and schemaType as arguments on each iteration. * * @param {Function} fn callback function * @return {Schema} this * @api public */ Schema.prototype.eachPath = function(fn) { var keys = Object.keys(this.paths), len = keys.length; for (var 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. * * @api public * @param {Boolean} invalidate refresh the cache * @return {Array} */ Schema.prototype.requiredPaths = function requiredPaths(invalidate) { if (this._requiredpaths && !invalidate) { return this._requiredpaths; } var paths = Object.keys(this.paths), i = paths.length, ret = []; while (i--) { var 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. * * @param {String} path * @return {String} * @api public */ Schema.prototype.pathType = function(path) { if (path in this.paths) { return 'real'; } if (path in this.virtuals) { return 'virtual'; } if (path in this.nested) { return 'nested'; } if (path in this.subpaths) { return 'real'; } if (path in this.singleNestedPaths) { 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) { var subpaths = path.split(/\./g); path = ''; for (var 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 true; } } return false; }; /** * Setup updatedAt and createdAt timestamps to documents if enabled * * @param {Boolean|Object} timestamps timestamps options * @api private */ Schema.prototype.setupTimestamp = function(timestamps) { if (timestamps) { var createdAt = handleTimestampOption(timestamps, 'createdAt'); var updatedAt = handleTimestampOption(timestamps, 'updatedAt'); var schemaAdditions = {}; if (updatedAt && !this.paths[updatedAt]) { schemaAdditions[updatedAt] = Date; } if (createdAt && !this.paths[createdAt]) { schemaAdditions[createdAt] = Date; } this.add(schemaAdditions); this.pre('save', function(next) { var defaultTimestamp = new Date(); var auto_id = this._id && this._id.auto; if (createdAt != null && !this.get(createdAt) && this.isSelected(createdAt)) { this.set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp); } if (updatedAt != null && (this.isNew || this.isModified())) { var ts = defaultTimestamp; if (this.isNew) { if (createdAt != null) { ts = this.get(createdAt); } else if (auto_id) { ts = this._id.getTimestamp(); } } this.set(updatedAt, ts); } next(); }); var genUpdates = function(currentUpdate, overwrite) { var now = new Date(); var updates = {}; var _updates = updates; if (overwrite) { if (currentUpdate && currentUpdate.$set) { currentUpdate = currentUpdate.$set; updates.$set = {}; _updates = updates.$set; } if (updatedAt != null && !currentUpdate[updatedAt]) { _updates[updatedAt] = now; } if (createdAt != null && !currentUpdate[createdAt]) { _updates[createdAt] = now; } return updates; } updates = { $set: {} }; currentUpdate = currentUpdate || {}; if (updatedAt != null && (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { updates.$set[updatedAt] = now; } if (createdAt != null) { if (currentUpdate[createdAt]) { delete currentUpdate[createdAt]; } if (currentUpdate.$set && currentUpdate.$set[createdAt]) { delete currentUpdate.$set[createdAt]; } updates.$setOnInsert = {}; updates.$setOnInsert[createdAt] = now; } return updates; }; this.methods.initializeTimestamps = function() { if (!this.get(createdAt)) { this.set(createdAt, new Date()); } if (!this.get(updatedAt)) { this.set(updatedAt, new Date()); } return this; }; this.pre('findOneAndUpdate', function(next) { var overwrite = this.options.overwrite; this.findOneAndUpdate({}, genUpdates(this.getUpdate(), overwrite), { overwrite: overwrite }); applyTimestampsToChildren(this); next(); }); this.pre('update', function(next) { var overwrite = this.options.overwrite; this.update({}, genUpdates(this.getUpdate(), overwrite), { overwrite: overwrite }); applyTimestampsToChildren(this); next(); }); } }; /*! * ignore */ function handleTimestampOption(arg, prop) { 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]; } /*! * ignore */ function applyTimestampsToChildren(query) { var now = new Date(); var update = query.getUpdate(); var keys = Object.keys(update); var key; var schema = query.model.schema; var len; var createdAt; var updatedAt; var timestamps; var path; var hasDollarKey = keys.length && keys[0].charAt(0) === '$'; if (hasDollarKey) { if (update.$push) { for (key in update.$push) { var $path = schema.path(key); if (update.$push[key] && $path && $path.$isMongooseDocumentArray && $path.schema.options.timestamps) { timestamps = $path.schema.options.timestamps; createdAt = handleTimestampOption(timestamps, 'createdAt'); 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) { for (key in update.$set) { path = schema.path(key); if (!path) { continue; } if (Array.isArray(update.$set[key]) && path.$isMongooseDocumentArray) { len = update.$set[key].length; timestamps = schema.path(key).schema.options.timestamps; if (timestamps) { createdAt = handleTimestampOption(timestamps, 'createdAt'); updatedAt = handleTimestampOption(timestamps, 'updatedAt'); for (var i = 0; i < len; ++i) { if (updatedAt != null) { update.$set[key][i][updatedAt] = now; } if (createdAt != null) { update.$set[key][i][createdAt] = now; } } } } else if (update.$set[key] && path.$isSingleNested) { timestamps = schema.path(key).schema.options.timestamps; if (timestamps) { createdAt = handleTimestampOption(timestamps, 'createdAt'); updatedAt = handleTimestampOption(timestamps, 'updatedAt'); if (updatedAt != null) { update.$set[key][updatedAt] = now; } if (createdAt != null) { update.$set[key][createdAt] = now; } } } } } } } /*! * ignore */ function getPositionalPathType(self, path) { var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); if (subpaths.length < 2) { return self.paths[subpaths[0]]; } var val = self.path(subpaths[0]); var isNested = false; if (!val) { return val; } var last = subpaths.length - 1, subpath, i = 1; for (; i < subpaths.length; ++i) { isNested = false; subpath = subpaths[i]; if (i === last && val && !/\D/.test(subpath)) { if (val.$isMongooseDocumentArray) { var oldVal = val; val = new SchemaType(subpath); val.cast = function(value, doc, init) { return oldVal.cast(value, doc, init)[0]; }; val.caster = oldVal.caster; val.schema = oldVal.schema; } 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)) { continue; } if (!(val && val.schema)) { val = undefined; break; } var 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. * * @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 document. * * ####Example * * var toySchema = new Schema(..); * * 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(); * }) * * @param {String} method * @param {Function} callback * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 * @api public */ Schema.prototype.pre = function() { this.s.hooks.pre.apply(this.s.hooks, arguments); return this; }; /** * Defines a post hook for the document * * var 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 run a find query'); * }); * * var Model = mongoose.model('Model', schema); * * var 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} method name of the method to hook * @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() { this.s.hooks.post.apply(this.s.hooks, arguments); return this; }; /** * Registers a plugin for this schema. * * @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 (var i = 0; i < this.plugins.length; ++i) { if (this.plugins[i].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 * * var schema = kittySchema = new Schema(..); * * schema.method('meow', function () { * console.log('meeeeeoooooooooooow'); * }) * * var Kitty = mongoose.model('Kitty', schema); * * var 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(); * * @param {String|Object} method name * @param {Function} [fn] * @api public */ Schema.prototype.method = function(name, fn) { if (typeof name !== 'string') { for (var i in name) { this.methods[i] = name[i]; } } else { this.methods[name] = fn; } return this; }; /** * Adds static "class" methods to Models compiled from this schema. * * ####Example * * var schema = new Schema(..); * schema.static('findByName', function (name, callback) { * return this.find({ name: name }, callback); * }); * * var Drink = mongoose.model('Drink', schema); * Drink.findByName('sanpellegrino', function (err, drinks) { * // * }); * * 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 */ Schema.prototype.static = function(name, fn) { if (typeof name !== 'string') { for (var 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/gets 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); break; case 'safe': this.options[key] = value === false ? {w: 0} : value; break; case 'timestamps': this.setupTimestamp(value); this.options[key] = value; break; default: this.options[key] = value; } return this; }; /** * Gets a schema option. * * @param {String} key option name * @api public */ Schema.prototype.get = function(key) { return this.options[key]; }; /** * The allowed index types * * @static indexTypes * @receiver Schema * @api public */ var 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. * * @api public */ Schema.prototype.indexes = function() { 'use strict'; var indexes = []; var schemaStack = []; var collectIndexes = function(schema, prefix) { // Ignore infinitely nested schemas, if we've already seen this schema // along this path there must be a cycle if (schemaStack.indexOf(schema) !== -1) { return; } schemaStack.push(schema); prefix = prefix || ''; var key, path, index, field, isObject, options, type; var keys = Object.keys(schema.paths); for (var i = 0; i < keys.length; ++i) { key = keys[i]; path = schema.paths[key]; if ((path instanceof MongooseTypes.DocumentArray) || path.$isSingleNested) { if (path.options.excludeIndexes !== true) { collectIndexes(path.schema, prefix + key + '.'); } // Retained to minimize risk of backwards breaking changes due to // gh-6113 if ((path instanceof MongooseTypes.DocumentArray)) { continue; } } index = path._index || (path.caster && path.caster._index); if (index !== false && index !== null && index !== undefined) { field = {}; isObject = utils.isObject(index); options = isObject ? index : {}; type = typeof index === 'string' ? index : isObject ? index.type : false; if (type && ~Schema.indexTypes.indexOf(type)) { field[prefix + key] = type; } else if (options.text) { field[prefix + key] = 'text'; delete options.text; } else { field[prefix + key] = 1; } delete options.type; if (!('background' in options)) { options.background = true; } indexes.push([field, options]); } } schemaStack.pop(); 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); } }; collectIndexes(this); return 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) { var subindexes = schema._indexes, len = subindexes.length, indexObj, newindex, klen, keys, key, i = 0, j; for (i = 0; i < len; ++i) { indexObj = subindexes[i][0]; keys = Object.keys(indexObj); klen = keys.length; newindex = {}; // use forward iteration, order matters for (j = 0; j < klen; ++j) { key = keys[j]; newindex[prefix + key] = indexObj[key]; } indexes.push([newindex, subindexes[i][1]]); } } }; /** * Creates a virtual type with the given name. * * @param {String} name * @param {Object} [options] * @return {VirtualType} */ Schema.prototype.virtual = function(name, options) { if (options && options.ref) { if (!options.localField) { throw new Error('Reference virtuals require `localField` option'); } if (!options.foreignField) { throw new Error('Reference virtuals require `foreignField` option'); } this.pre('init', function(obj) { if (mpath.has(name, obj)) { var _v = mpath.get(name, obj); if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } if (options.justOne) { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; } else { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v : _v == null ? [] : [_v]; } mpath.unset(name, obj); } }); var virtual = this.virtual(name); virtual.options = options; return virtual. get(function() { if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } if (name in this.$$populatedVirtuals) { return this.$$populatedVirtuals[name]; } return null; }). set(function(_v) { if (!this.$$populatedVirtuals) { this.$$populatedVirtuals = {}; } if (options.justOne) { this.$$populatedVirtuals[name] = Array.isArray(_v) ? _v[0] : _v; if (typeof this.$$populatedVirtuals[name] !== 'object') { this.$$populatedVirtuals[name] = 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'; }); } }); } var virtuals = this.virtuals; var 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); return virtuals[name]; }; /*! * ignore */ Schema.prototype._getVirtual = function(name) { return _getVirtual(this, name); }; /*! * ignore */ function _getVirtual(schema, name) { if (schema.virtuals[name]) { return schema.virtuals[name]; } var parts = name.split('.'); var cur = ''; var nestedSchemaPath = ''; for (var i = 0; i < parts.length; ++i) { cur += (cur.length > 0 ? '.' : '') + parts[i]; if (schema.virtuals[cur]) { if (i === parts.length - 1) { schema.virtuals[cur].$nestedSchemaPath = nestedSchemaPath; return schema.virtuals[cur]; } continue; } else if (schema.paths[cur] && schema.paths[cur].schema) { schema = schema.paths[cur].schema; nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur; cur = ''; } else { return null; } } } /** * Returns the virtual type with the given `name`. * * @param {String} name * @return {VirtualType} */ Schema.prototype.virtualpath = function(name) { return this.virtuals[name]; }; /** * Removes the given `path` (or [`paths`]). * * @param {String|Array} path * * @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)) { delete this.paths[name]; var pieces = name.split('.'); var last = pieces.pop(); var branch = this.tree; for (var i = 0; i < pieces.length; ++i) { branch = branch[pieces[i]]; } delete branch[last]; } }, this); } }; /** * Loads an ES6 class into a schema. Maps setters + getters, static methods, and instance methods to schema virtuals, statics, and methods. * * @param {Function} model */ 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; } var 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; } var 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) { var _this = this; var pathschema = _this.path(path); var resultPath = []; if (pathschema) { pathschema.$fullPath = path; return pathschema; } function search(parts, schema) { var p = parts.length + 1; var foundschema; var 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 && foundschema.schema) { var 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; } } foundschema.$fullPath = resultPath.join('.'); return foundschema; } } } // look for arrays var parts = path.split('.'); for (var 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) { var _this = this; var pathschema = _this.path(path); if (pathschema) { return 'real'; } function search(parts, schema) { var 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.indexOf('$[') === 0 && piece.lastIndexOf(']') === piece.length - 1; } /*! * Module exports. */ module.exports = exports = Schema; // require down here because of reference issues /** * The various built-in Mongoose Schema Types. * * ####Example: * * var mongoose = require('mongoose'); * var 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. * * var 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":335,"./drivers":411,"./schema/index":442,"./schematype":452,"./utils":469,"./virtualtype":470,"events":316,"kareem":337,"mpath":471}],435:[function(require,module,exports){ /*! * Module dependencies. */ var $exists = require('./operators/exists'); var $type = require('./operators/type'); var SchemaType = require('../schematype'); var CastError = SchemaType.CastError; var Types = { Array: SchemaArray, Boolean: require('./boolean'), Date: require('./date'), Number: require('./number'), String: require('./string'), ObjectId: require('./objectid'), Buffer: require('./buffer') }; var Mixed = require('./mixed'); var cast = require('../cast'); var get = require('lodash.get'); var util = require('util'); var utils = require('../utils'); var castToNumber = require('./operators/helpers').castToNumber; var geospatial = require('./operators/geospatial'); var MongooseArray; var EmbeddedDoc; /** * 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); var typeKey = 'type'; if (schemaOptions && schemaOptions.typeKey) { typeKey = schemaOptions.typeKey; } if (cast) { var castOptions = {}; if (utils.getFunctionName(cast.constructor) === 'Object') { if (cast[typeKey]) { // support { type: Woot } castOptions = utils.clone(cast); // do not alter user arguments delete castOptions[typeKey]; cast = cast[typeKey]; } else { cast = Mixed; } } // support { type: 'String' } var name = typeof cast === 'string' ? cast : utils.getFunctionName(cast); var caster = name in Types ? Types[name] : cast; this.casterConstructor = caster; if (typeof caster === 'function' && !caster.$isArraySubdocument) { this.caster = new caster(null, castOptions); } else { this.caster = caster; } if (!(this.caster instanceof EmbeddedDoc)) { this.caster.path = key; } } this.$isMongooseArray = true; SchemaType.call(this, key, options, 'Array'); var defaultArr; var fn; if (this.defaultValue != null) { defaultArr = this.defaultValue; fn = typeof defaultArr === 'function'; } if (!('defaultValue' in this) || this.defaultValue !== void 0) { this.default(function() { var arr = []; if (fn) { arr = defaultArr(); } else if (defaultArr != null) { arr = arr.concat(defaultArr); } // Leave it up to `cast()` to convert the array return arr; }); } } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaArray.schemaName = 'Array'; /*! * Inherits from SchemaType. */ SchemaArray.prototype = Object.create(SchemaType.prototype); SchemaArray.prototype.constructor = SchemaArray; /** * Adds an enum validator if this is an array of strings. Equivalent to * `SchemaString.prototype.enum()` * * @param {String|Object} [args...] enumeration values * @return {SchemaType} this */ SchemaArray.prototype.enum = function() { const instance = get(this, 'caster.instance'); if (instance !== 'String') { throw new Error('`enum` can only be set on an array of strings, not ' + instance); } this.caster.enum.apply(this.caster, arguments); return this; }; /** * Check if the given value satisfies a required validator. The given value * must be not null nor undefined, and have a positive length. * * @param {Any} value * @return {Boolean} * @api public */ SchemaArray.prototype.checkRequired = function(value) { return Array.isArray(value); }; /** * 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); }; /** * 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) { // lazy load MongooseArray || (MongooseArray = require('../types').Array); if (Array.isArray(value)) { if (!value.length && doc) { var indexes = doc.schema.indexedPaths(); for (var i = 0, l = indexes.length; i < l; ++i) { var pathIndex = indexes[i][0][this.path]; if (pathIndex === '2dsphere' || pathIndex === '2d') { return; } } } if (!(value && value.isMongooseArray)) { value = new MongooseArray(value, this.path, doc); } else if (value && value.isMongooseArray) { // We need to create a new array, otherwise change tracking will // update the old doc (gh-4449) value = new MongooseArray(value, this.path, doc); } if (this.caster) { try { for (i = 0, l = value.length; i < l; i++) { value[i] = this.caster.cast(value[i], doc, init); } } catch (e) { // rethrow throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e); } } return value; } // 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); }; /** * Casts values for queries. * * @param {String} $conditional * @param {any} [value] * @api private */ SchemaArray.prototype.castForQuery = function($conditional, value) { var handler, 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; var Constructor = this.casterConstructor; if (val && Constructor.discriminators && Constructor.schema.options.discriminatorKey && typeof val[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; } var proto = this.casterConstructor.prototype; var method = proto && (proto.castForQuery || proto.cast); if (!method && Constructor.castForQuery) { method = Constructor.castForQuery; } var caster = this.caster; if (Array.isArray(val)) { 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)) { var o = {}; o[this.path] = v; return cast(this.casterConstructor.schema, o)[this.path]; } return v; }, this); return this.castForQuery(val); } function cast$elemMatch(val) { var keys = Object.keys(val); var numKeys = keys.length; var key; var value; for (var i = 0; i < numKeys; ++i) { key = keys[i]; value = val[key]; if (key.indexOf('$') === 0 && value) { val[key] = this.castForQuery(key, value); } } return cast(this.casterConstructor.schema, val); } var handle = SchemaArray.prototype.$conditionalHandlers = {}; handle.$all = cast$all; handle.$options = String; handle.$elemMatch = cast$elemMatch; handle.$geoIntersects = geospatial.cast$geoIntersects; handle.$or = handle.$and = function(val) { if (!Array.isArray(val)) { throw new TypeError('conditional $or/$and require array'); } var ret = []; for (var i = 0; i < val.length; ++i) { ret.push(cast(this.casterConstructor.schema, val[i])); } 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.$in = handle.$lt = handle.$lte = handle.$ne = handle.$nin = handle.$regex = SchemaArray.prototype.castForQuery; /*! * Module exports. */ module.exports = SchemaArray; },{"../cast":403,"../schematype":452,"../types":466,"../utils":469,"./boolean":436,"./buffer":437,"./date":438,"./mixed":443,"./number":444,"./objectid":445,"./operators/exists":447,"./operators/geospatial":448,"./operators/helpers":449,"./operators/type":450,"./string":451,"lodash.get":338,"util":563}],436:[function(require,module,exports){ /*! * Module dependencies. */ var utils = require('../utils'); var SchemaType = require('../schematype'); var CastError = SchemaType.CastError; const convertToTrue = [true, 'true', 1, '1', 'yes']; const convertToFalse = [false, 'false', 0, '0', 'no']; /** * 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'; /*! * Inherits from SchemaType. */ SchemaBoolean.prototype = Object.create(SchemaType.prototype); SchemaBoolean.prototype.constructor = SchemaBoolean; /** * 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 value === true || value === false; }; /** * Casts to boolean * * @param {Object} value * @param {Object} model - this value is optional * @api private */ SchemaBoolean.prototype.cast = function(value) { if (value == null) { return value; } // strict mode (throws if value is not a boolean, instead of converting) if (convertToTrue.indexOf(value) !== -1) { return true; } if (convertToFalse.indexOf(value) !== -1) { return false; } throw new CastError('boolean', value, this.path); }; 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) { var handler; if (arguments.length === 2) { handler = SchemaBoolean.$conditionalHandlers[$conditional]; if (handler) { return handler.call(this, val); } return this._castForQuery(val); } return this._castForQuery($conditional); }; /*! * Module exports. */ module.exports = SchemaBoolean; },{"../schematype":452,"../utils":469}],437:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ var handleBitwiseOperator = require('./operators/bitwise'); var utils = require('../utils'); var MongooseBuffer = require('../types/buffer'); var SchemaType = require('../schematype'); var Binary = MongooseBuffer.Binary; var CastError = SchemaType.CastError; var 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'; /*! * Inherits from SchemaType. */ SchemaBuffer.prototype = Object.create(SchemaType.prototype); SchemaBuffer.prototype.constructor = SchemaBuffer; /** * 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 !!(value && value.length); }; /** * 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) { var 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); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. var path = doc.$__fullPath(this.path); var owner = doc.ownerDocument ? doc.ownerDocument() : doc; var pop = owner.populated(path, true); ret = new pop.options.model(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; } else 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); } ret._subtype = value.sub_type; return ret; } if (value === null) { return value; } var type = typeof value; if (type === 'string' || type === 'number' || Array.isArray(value)) { 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); }; /** * 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: * * var s = new Schema({ uuid: { type: Buffer, subtype: 4 }); * var M = db.model('M', s); * var 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) { var 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; var 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":335,"../schematype":452,"../types/buffer":462,"../utils":469,"./../document":404,"./operators/bitwise":446}],438:[function(require,module,exports){ /*! * Module requirements. */ var MongooseError = require('../error'); var utils = require('../utils'); var SchemaType = require('../schematype'); var 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'; /*! * Inherits from SchemaType. */ SchemaDate.prototype = Object.create(SchemaType.prototype); SchemaDate.prototype.constructor = SchemaDate; /** * 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 * var 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; }; /** * 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) { return value instanceof Date; }; /** * Sets a minimum date validator. * * ####Example: * * var s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) * var M = db.model('M', s) * var 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 * var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; * var schema = new Schema({ d: { type: Date, min: min }) * var M = mongoose.model('M', schema); * var 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) { var msg = message || MongooseError.messages.Date.min; msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); var _this = this; this.validators.push({ validator: this.minValidator = function(val) { var 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: * * var s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) * var M = db.model('M', s) * var 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 * var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; * var schema = new Schema({ d: { type: Date, max: max }) * var M = mongoose.model('M', schema); * var 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) { var msg = message || MongooseError.messages.Date.max; msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); var _this = this; this.validators.push({ validator: this.maxValidator = function(val) { var 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) { // If null or undefined if (value === null || value === void 0 || value === '') { return null; } if (value instanceof Date) { if (isNaN(value.valueOf())) { throw new CastError('date', value, this.path); } return value; } var date; if (typeof value === 'boolean') { throw new CastError('date', value, this.path); } if (value instanceof Number || typeof value === 'number') { date = new Date(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; } throw new CastError('date', value, this.path); }; /*! * 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) { var handler; if (arguments.length !== 2) { return this._castForQuery($conditional); } 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; },{"../error":419,"../schematype":452,"../utils":469}],439:[function(require,module,exports){ (function (Buffer){ /* eslint no-empty: 1 */ /*! * Module dependencies. */ var SchemaType = require('../schematype'); var CastError = SchemaType.CastError; var Decimal128Type = require('../types/decimal128'); var utils = require('../utils'); var 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'; /*! * Inherits from SchemaType. */ Decimal128.prototype = Object.create(SchemaType.prototype); Decimal128.prototype.constructor = Decimal128; /** * 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; } return value instanceof Decimal128Type; }; /** * 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); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. var path = doc.$__fullPath(this.path); var owner = doc.ownerDocument ? doc.ownerDocument() : doc; var pop = owner.populated(path, true); var 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.model(value); ret.$__.wasPopulated = true; } return ret; } 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); } throw new CastError('Decimal128', value, this.path); }; /*! * 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":335,"../schematype":452,"../types/decimal128":463,"../utils":469,"./../document":404}],440:[function(require,module,exports){ /* eslint no-empty: 1 */ /*! * Module dependencies. */ var ArrayType = require('./array'); var CastError = require('../error/cast'); var Document = require('../document'); var EventEmitter = require('events').EventEmitter; var SchemaType = require('../schematype'); var discriminator = require('../services/model/discriminator'); var util = require('util'); var utils = require('../utils'); var MongooseDocumentArray; var Subdocument; /** * SubdocsArray SchemaType constructor * * @param {String} key * @param {Schema} schema * @param {Object} options * @inherits SchemaArray * @api public */ function DocumentArray(key, schema, options) { var EmbeddedDocument = _createConstructor(schema, options); EmbeddedDocument.prototype.$basePath = key; ArrayType.call(this, key, EmbeddedDocument, options); this.schema = schema; this.$isMongooseDocumentArray = true; var fn = this.defaultValue; if (!('defaultValue' in this) || fn !== void 0) { this.default(function() { var arr = fn.call(this); if (!Array.isArray(arr)) { arr = [arr]; } // Leave it up to `cast()` to convert this to a documentarray return arr; }); } } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ DocumentArray.schemaName = 'DocumentArray'; /*! * Inherits from ArrayType. */ DocumentArray.prototype = Object.create(ArrayType.prototype); DocumentArray.prototype.constructor = DocumentArray; /*! * Ignore */ function _createConstructor(schema, options) { Subdocument || (Subdocument = require('../types/embedded')); // compile an embedded document for this schema function EmbeddedDocument() { Subdocument.apply(this, arguments); } EmbeddedDocument.prototype = Object.create(Subdocument.prototype); EmbeddedDocument.prototype.$__setSchema(schema); EmbeddedDocument.schema = schema; EmbeddedDocument.prototype.constructor = EmbeddedDocument; EmbeddedDocument.$isArraySubdocument = true; // apply methods for (var i in schema.methods) { EmbeddedDocument.prototype[i] = schema.methods[i]; } // apply statics for (i in schema.statics) { EmbeddedDocument[i] = schema.statics[i]; } for (i in EventEmitter.prototype) { EmbeddedDocument[i] = EventEmitter.prototype[i]; } EmbeddedDocument.options = options; return EmbeddedDocument; } /*! * Ignore */ DocumentArray.prototype.discriminator = function(name, schema) { if (typeof name === 'function') { name = utils.getFunctionName(name); } schema = discriminator(this.casterConstructor, name, schema); var EmbeddedDocument = _createConstructor(schema); 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 */ DocumentArray.prototype.doValidate = function(array, fn, scope, options) { // lazy load MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); var _this = this; SchemaType.prototype.doValidate.call(this, array, function(err) { if (err) { return fn(err); } var count = array && array.length; var 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) { error = err; } --count || fn(error); } for (var i = 0, len = count; i < len; ++i) { // sidestep sparse entries var doc = array[i]; if (!doc) { --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)) { doc = array[i] = new _this.casterConstructor(doc, array, undefined, undefined, i); } doc.$__validate(callback); } }, scope); }; /** * Performs local validations first, then validations on each embedded doc. * * ####Note: * * This method ignores the asynchronous validators. * * @return {MongooseError|undefined} * @api private */ DocumentArray.prototype.doValidateSync = function(array, scope) { var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); if (schemaTypeError) { return schemaTypeError; } var count = array && array.length, 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 (var i = 0, len = count; i < len; ++i) { // only first error if (resultError) { break; } // sidestep sparse entries var 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)) { doc = array[i] = new this.casterConstructor(doc, array, undefined, undefined, i); } var subdocValidateError = doc.validateSync(); if (subdocValidateError) { resultError = subdocValidateError; } } return resultError; }; /** * Casts contents * * @param {Object} value * @param {Document} document that triggers the casting * @api private */ DocumentArray.prototype.cast = function(value, doc, init, prev, options) { // lazy load MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); var selected; var subdoc; var i; var _opts = { transform: false, virtuals: false }; if (!Array.isArray(value)) { // 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); } if (!(value && value.isMongooseDocumentArray) && (!options || !options.skipDocumentArrayCast)) { value = new MongooseDocumentArray(value, this.path, doc); if (prev && prev._handlers) { for (var key in prev._handlers) { doc.removeListener(key, prev._handlers[key]); } } } 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); } i = value.length; while (i--) { if (!value[i]) { continue; } var Constructor = this.casterConstructor; if (Constructor.discriminators && typeof value[i][Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]]; } // Check if the document has a different schema (re gh-3701) if ((value[i] instanceof Document) && value[i].schema !== Constructor.schema) { value[i] = value[i].toObject({ transform: false, virtuals: false }); } if (!(value[i] instanceof Subdocument) && value[i]) { if (init) { if (doc) { selected || (selected = scopePaths(this, doc.$__.selected, init)); } else { selected = true; } subdoc = new Constructor(null, value, true, selected, i); value[i] = subdoc.init(value[i]); } else { if (prev && (subdoc = prev.id(value[i]._id))) { 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) { var valueInErrorMessage = util.inspect(value[i]); throw new CastError('embedded', valueInErrorMessage, value._path, error); } } } } } return value; }; /*! * Scopes paths selected in a query to this array. * Necessary for proper default application of subdocument values. * * @param {DocumentArray} 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; } var path = array.path + '.'; var keys = Object.keys(fields); var i = keys.length; var selected = {}; var hasKeys; var key; var sub; while (i--) { key = keys[i]; if (key.indexOf(path) === 0) { sub = key.substring(path.length); if (sub === '$') { continue; } if (sub.indexOf('$.') === 0) { sub = sub.substr(2); } hasKeys || (hasKeys = true); selected[sub] = fields[key]; } } return hasKeys && selected || undefined; } /*! * Module exports. */ module.exports = DocumentArray; },{"../document":404,"../error/cast":417,"../schematype":452,"../services/model/discriminator":457,"../types/documentarray":464,"../types/embedded":465,"../utils":469,"./array":435,"events":316,"util":563}],441:[function(require,module,exports){ 'use strict'; /*! * Module dependencies. */ const $exists = require('./operators/exists'); const EventEmitter = require('events').EventEmitter; const SchemaType = require('../schematype'); const castToNumber = require('./operators/helpers').castToNumber; const discriminator = require('../services/model/discriminator'); const geospatial = require('./operators/geospatial'); const internalToObjectOptions = require('../options').internalToObjectOptions; let Subdocument; module.exports = Embedded; /** * Sub-schema schematype constructor * * @param {Schema} schema * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function Embedded(schema, path, options) { this.caster = _createConstructor(schema); this.caster.prototype.$basePath = path; this.schema = schema; this.$isSingleNested = true; SchemaType.call(this, path, options, 'Embedded'); } /*! * ignore */ Embedded.prototype = Object.create(SchemaType.prototype); /*! * ignore */ function _createConstructor(schema) { // lazy load Subdocument || (Subdocument = require('../types/subdocument')); var _embedded = function SingleNested(value, path, parent) { var _this = this; this.$parent = parent; Subdocument.apply(this, arguments); 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); }); } }; _embedded.prototype = Object.create(Subdocument.prototype); _embedded.prototype.$__setSchema(schema); _embedded.prototype.constructor = _embedded; _embedded.schema = schema; _embedded.$isSingleNested = true; _embedded.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; // apply methods for (var i in schema.methods) { _embedded.prototype[i] = schema.methods[i]; } // apply statics for (i in schema.statics) { _embedded[i] = schema.statics[i]; } for (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 */ Embedded.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { return { $geometry: this.castForQuery(val.$geometry) }; }; /*! * ignore */ Embedded.prototype.$conditionalHandlers.$near = Embedded.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; Embedded.prototype.$conditionalHandlers.$within = Embedded.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; Embedded.prototype.$conditionalHandlers.$geoIntersects = geospatial.cast$geoIntersects; Embedded.prototype.$conditionalHandlers.$minDistance = castToNumber; Embedded.prototype.$conditionalHandlers.$maxDistance = castToNumber; Embedded.prototype.$conditionalHandlers.$exists = $exists; /** * Casts contents * * @param {Object} value * @api private */ Embedded.prototype.cast = function(val, doc, init, priorVal) { if (val && val.$isSingleNested) { return val; } var Constructor = this.caster; var discriminatorKey = Constructor.schema.options.discriminatorKey; if (val != null && Constructor.discriminators && typeof val[discriminatorKey] === 'string' && Constructor.discriminators[val[discriminatorKey]]) { Constructor = Constructor.discriminators[val[discriminatorKey]]; } var subdoc; if (init) { subdoc = new Constructor(void 0, doc ? doc.$__.selected : void 0, doc); subdoc.init(val); } else { if (Object.keys(val).length === 0) { return new Constructor({}, doc ? doc.$__.selected : void 0, doc); } return new Constructor(val, doc ? doc.$__.selected : void 0, 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 */ Embedded.prototype.castForQuery = function($conditional, val) { var 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); } return new this.caster(val); }; /** * Async validation on this single nested doc. * * @api private */ Embedded.prototype.doValidate = function(value, fn, scope) { var Constructor = this.caster; var discriminatorKey = Constructor.schema.options.discriminatorKey; if (value != null && Constructor.discriminators && typeof value[discriminatorKey] === 'string' && Constructor.discriminators[value[discriminatorKey]]) { Constructor = Constructor.discriminators[value[discriminatorKey]]; } SchemaType.prototype.doValidate.call(this, value, function(error) { if (error) { return fn(error); } if (!value) { return fn(null); } if (!(value instanceof Constructor)) { value = new Constructor(value); } value.validate({__noPromise: true}, fn); }, scope); }; /** * Synchronously validate this single nested doc * * @api private */ Embedded.prototype.doValidateSync = function(value, scope) { var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); if (schemaTypeError) { return schemaTypeError; } if (!value) { return; } return value.validateSync(); }; /** * Adds a discriminator to this property * * @param {String} name * @param {Schema} schema fields to add to the schema for instances of this sub-class * @api public */ Embedded.prototype.discriminator = function(name, schema) { discriminator(this.caster, name, schema); this.caster.discriminators[name] = _createConstructor(schema); return this.caster.discriminators[name]; }; },{"../options":431,"../schematype":452,"../services/model/discriminator":457,"../types/subdocument":468,"./operators/exists":447,"./operators/geospatial":448,"./operators/helpers":449,"events":316}],442:[function(require,module,exports){ /*! * Module exports. */ exports.String = require('./string'); exports.Number = require('./number'); exports.Boolean = require('./boolean'); exports.DocumentArray = require('./documentarray'); exports.Embedded = require('./embedded'); 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'); // alias exports.Oid = exports.ObjectId; exports.Object = exports.Mixed; exports.Bool = exports.Boolean; },{"./array":435,"./boolean":436,"./buffer":437,"./date":438,"./decimal128":439,"./documentarray":440,"./embedded":441,"./mixed":443,"./number":444,"./objectid":445,"./string":451}],443:[function(require,module,exports){ /*! * Module dependencies. */ var SchemaType = require('../schematype'); var utils = require('../utils'); /** * Mixed SchemaType constructor. * * @param {String} path * @param {Object} options * @inherits SchemaType * @api public */ function Mixed(path, options) { if (options && options.default) { var def = options.default; if (Array.isArray(def) && def.length === 0) { // make sure empty array defaults are handled options.default = Array; } else if (!options.shared && utils.isObject(def) && Object.keys(def).length === 0) { // prevent odd "shared" objects between documents options.default = function() { return {}; }; } } SchemaType.call(this, path, options, 'Mixed'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ Mixed.schemaName = 'Mixed'; /*! * Inherits from SchemaType. */ Mixed.prototype = Object.create(SchemaType.prototype); Mixed.prototype.constructor = Mixed; /** * 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; },{"../schematype":452,"../utils":469}],444:[function(require,module,exports){ (function (Buffer){ /*! * Module requirements. */ var SchemaType = require('../schematype'); var CastError = SchemaType.CastError; var handleBitwiseOperator = require('./operators/bitwise'); var MongooseError = require('../error'); var utils = require('../utils'); var Document; /** * Number SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function SchemaNumber(key, options) { SchemaType.call(this, key, options, 'Number'); } /** * This schema type's name, to defend against minifiers that mangle * function names. * * @api public */ SchemaNumber.schemaName = 'Number'; /*! * Inherits from SchemaType. */ SchemaNumber.prototype = Object.create(SchemaType.prototype); SchemaNumber.prototype.constructor = SchemaNumber; /** * 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; } return typeof value === 'number' || value instanceof Number; }; /** * Sets a minimum number validator. * * ####Example: * * var s = new Schema({ n: { type: Number, min: 10 }) * var M = db.model('M', s) * var 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 * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; * var schema = new Schema({ n: { type: Number, min: min }) * var M = mongoose.model('Measurement', schema); * var 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) { var 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: * * var s = new Schema({ n: { type: Number, max: 10 }) * var M = db.model('M', s) * var 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 * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; * var schema = new Schema({ n: { type: Number, max: max }) * var M = mongoose.model('Measurement', schema); * var 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) { var 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; }; /** * 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); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. var path = doc.$__fullPath(this.path); var owner = doc.ownerDocument ? doc.ownerDocument() : doc; var pop = owner.populated(path, true); var ret = new pop.options.model(value); ret.$__.wasPopulated = true; return ret; } var val = value && typeof value._id !== 'undefined' ? value._id : // documents value; if (!isNaN(val)) { if (val === null) { return val; } if (val === '') { return null; } if (typeof val === 'string' || typeof val === 'boolean') { val = Number(val); } if (val instanceof Number) { return val; } if (typeof val === 'number') { return val; } if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { return new Number(val); } } throw new CastError('number', value, this.path); }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } function handleArray(val) { var _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) { var handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with Number.'); } 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":335,"../error":419,"../schematype":452,"../utils":469,"./../document":404,"./operators/bitwise":446}],445:[function(require,module,exports){ (function (Buffer){ /* eslint no-empty: 1 */ /*! * Module dependencies. */ var SchemaType = require('../schematype'), CastError = SchemaType.CastError, oid = require('../types/objectid'), utils = require('../utils'), Document; /** * ObjectId SchemaType constructor. * * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function ObjectId(key, options) { var isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); var 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'; /*! * Inherits from SchemaType. */ ObjectId.prototype = Object.create(SchemaType.prototype); ObjectId.prototype.constructor = ObjectId; /** * 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; }; /** * 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; } return value instanceof oid; }; /** * 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); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. var path = doc.$__fullPath(this.path); var owner = doc.ownerDocument ? doc.ownerDocument() : doc; var pop = owner.populated(path, true); var 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.model(value); ret.$__.wasPopulated = true; } return ret; } if (value === null || value === undefined) { return value; } if (value instanceof oid) { return value; } if (value._id) { if (value._id instanceof oid) { return value._id; } if (value._id.toString instanceof Function) { try { return new oid(value._id.toString()); } catch (e) { } } } if (value.toString instanceof Function) { try { return new oid(value.toString()); } catch (err) { throw new CastError('ObjectId', value, this.path); } } throw new CastError('ObjectId', value, this.path); }; /*! * ignore */ function handleSingle(val) { return this.cast(val); } ObjectId.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [val] * @api private */ ObjectId.prototype.castForQuery = function($conditional, val) { var handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional + ' with ObjectId.'); } return handler.call(this, val); } return this._castForQuery($conditional); }; /*! * ignore */ function defaultId() { return new oid(); } function resetId(v) { Document || (Document = require('./../document')); if (this instanceof Document) { if (v === void 0) { var _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":335,"../schematype":452,"../types/objectid":467,"../utils":469,"./../document":404}],446:[function(require,module,exports){ (function (Buffer){ /*! * Module requirements. */ var CastError = require('../../error/cast'); /*! * ignore */ function handleBitwiseOperator(val) { var _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) { var 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":335,"../../error/cast":417}],447:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function(val) { if (typeof val !== 'boolean') { throw new Error('$exists parameter must be a boolean!'); } return val; }; },{}],448:[function(require,module,exports){ /*! * Module requirements. */ var castArraysOfNumbers = require('./helpers').castArraysOfNumbers; var castToNumber = require('./helpers').castToNumber; /*! * ignore */ exports.cast$geoIntersects = cast$geoIntersects; exports.cast$near = cast$near; exports.cast$within = cast$within; function cast$near(val) { var SchemaArray = require('../array'); if (Array.isArray(val)) { castArraysOfNumbers(val, this); return val; } _castMinMaxDistance(this, val); if (val && val.$geometry) { return cast$geometry(val, this); } 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(this, val); return val; } function cast$within(val) { _castMinMaxDistance(this, val); if (val.$box || val.$polygon) { var type = val.$box ? '$box' : '$polygon'; val[type].forEach(function(arr) { if (!Array.isArray(arr)) { var msg = 'Invalid $within $box argument. ' + 'Expected an array, received ' + arr; throw new TypeError(msg); } arr.forEach(function(v, i) { arr[i] = castToNumber.call(this, v); }); }); } else if (val.$center || val.$centerSphere) { type = val.$center ? '$center' : '$centerSphere'; val[type].forEach(function(item, i) { if (Array.isArray(item)) { item.forEach(function(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) { var 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":435,"./helpers":449}],449:[function(require,module,exports){ 'use strict'; /*! * Module requirements. */ var Types = { Number: require('../number') }; /*! * @ignore */ exports.castToNumber = castToNumber; exports.castArraysOfNumbers = castArraysOfNumbers; /*! * @ignore */ function castToNumber(val) { return Types.Number.prototype.cast.call(this, 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":444}],450:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function(val) { if (typeof val !== 'number' && typeof val !== 'string') { throw new Error('$type parameter must be number or string'); } return val; }; },{}],451:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ var SchemaType = require('../schematype'); var CastError = SchemaType.CastError; var MongooseError = require('../error'); var utils = require('../utils'); var 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'; /*! * Inherits from SchemaType. */ SchemaString.prototype = Object.create(SchemaType.prototype); SchemaString.prototype.constructor = SchemaString; /** * Adds an enum validator * * ####Example: * * var states = ['opening', 'open', 'closing', 'closed'] * var s = new Schema({ state: { type: String, enum: states }}) * var M = db.model('M', s) * var 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 * var enum = { * values: ['opening', 'open', 'closing', 'closed'], * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' * } * var s = new Schema({ state: { type: String, enum: enum }) * var M = db.model('M', s) * var 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; } var values; var errorMessage; if (utils.isObject(arguments[0])) { values = arguments[0].values; errorMessage = arguments[0].message; } else { values = arguments; errorMessage = MongooseError.messages.String.enum; } for (var i = 0; i < values.length; i++) { if (undefined !== values[i]) { this.enumValues.push(this.cast(values[i])); } } var 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: * * var s = new Schema({ email: { type: String, lowercase: true }}) * var M = db.model('M', s); * var 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' * * @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: * * var s = new Schema({ caps: { type: String, uppercase: true }}) * var M = db.model('M', s); * var m = new M({ caps: 'an example' }); * console.log(m.caps) // AN EXAMPLE * M.find({ caps: 'an example' }) // Matches documents where caps = '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: * * var s = new Schema({ name: { type: String, trim: true }}) * var M = db.model('M', s) * var string = ' some name ' * console.log(string.length) // 11 * var m = new M({ name: string }) * console.log(m.name.length) // 9 * * @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: * * var schema = new Schema({ postalCode: { type: String, minlength: 5 }) * var Address = db.model('Address', schema) * var 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 * var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; * var schema = new Schema({ postalCode: { type: String, minlength: minlength }) * var Address = mongoose.model('Address', schema); * var 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) { var 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; }; /** * Sets a maximum length validator. * * ####Example: * * var schema = new Schema({ postalCode: { type: String, maxlength: 9 }) * var Address = db.model('Address', schema) * var 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 * var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) * var Address = mongoose.model('Address', schema); * var 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) { var 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; }; /** * Sets a regexp validator. * * Any value that does not pass `regExp`.test(val) will fail validation. * * ####Example: * * var s = new Schema({ name: { type: String, match: /^a/ }}) * var M = db.model('M', s) * var 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 * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; * var s = new Schema({ file: { type: String, match: match }}) * var M = db.model('M', s); * var 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. * * var 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 var msg = message || MongooseError.messages.String.match; var matchValidator = function(v) { if (!regExp) { return false; } var 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; } return (value instanceof String || typeof value === 'string') && value.length; }; /** * 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); } // Handle the case where user directly sets a populated // path to a plain object; cast to the Model used in // the population query. var path = doc.$__fullPath(this.path); var owner = doc.ownerDocument ? doc.ownerDocument() : doc; var pop = owner.populated(path, true); var ret = new pop.options.model(value); ret.$__.wasPopulated = true; return ret; } // If null or undefined if (value === null || value === undefined) { return value; } if (typeof value !== 'undefined') { // 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) { return value.toString(); } } throw new CastError('string', value, this.path); }; /*! * ignore */ function handleSingle(val) { return this.castForQuery(val); } function handleArray(val) { var _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { return _this.castForQuery(m); }); } SchemaString.prototype.$conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { $all: handleArray, $gt: handleSingle, $gte: handleSingle, $lt: handleSingle, $lte: handleSingle, $options: handleSingle, $regex: handleSingle, $not: handleSingle }); /** * Casts contents for queries. * * @param {String} $conditional * @param {any} [val] * @api private */ SchemaString.prototype.castForQuery = function($conditional, val) { var 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":335,"../error":419,"../schematype":452,"../utils":469,"./../document":404}],452:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ var $exists = require('./schema/operators/exists'); var $type = require('./schema/operators/type'); var utils = require('./utils'); var MongooseError = require('./error'); var CastError = MongooseError.CastError; var 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 {Object} [options] * @param {String} [instance] * @api public */ function SchemaType(path, options, instance) { this.path = path; this.instance = instance; this.validators = []; this.setters = []; this.getters = []; this.options = options; this._index = null; this.selected; for (var prop in options) { if (this[prop] && typeof this[prop] === 'function') { // { unique: true, index: true } if (prop === 'index' && this._index) { continue; } var val = options[prop]; // Special case so we don't screw up array defaults, see gh-5780 if (prop === 'default') { this.default(val); continue; } var opts = Array.isArray(val) ? val : [val]; this[prop].apply(this, opts); } } Object.defineProperty(this, '$$context', { enumerable: false, configurable: false, writable: true, value: null }); } /** * Sets a default value for this SchemaType. * * ####Example: * * var schema = new Schema({ n: { type: Number, default: 10 }) * var M = db.model('M', schema) * var 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: * var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) * var M = db.model('M', schema) * var m = new M; * console.log(m.aNumber) // 4.815162342 * * // default unique objects for Mixed types: * var 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: * var schema = new Schema({ mixed: Schema.Types.Mixed }); * schema.path('mixed').default({}); * var M = db.model('M', schema); * var m1 = new M; * m1.mixed.added = 1; * console.log(m1.mixed); // { added: 1 } * var 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; } 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: * * var s = new Schema({ name: { type: String, index: true }) * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) * Schema.path('my.path').index(true); * Schema.path('my.date').index({ expires: 60 }); * Schema.path('my.path').index({ unique: true, sparse: true }); * * ####NOTE: * * _Indexes are created in the background by default. Specify `background: false` to override._ * * [Direction doesn't matter for single key indexes](http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes) * * @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: * * var s = new Schema({ name: { type: String, unique: true }}); * Schema.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: * * var s = new Schema({name : {type: String, text : true }) * Schema.path('name').index({text : true}); * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.text = function(bool) { 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: * * var s = new Schema({ name: { type: String, sparse: true }) * Schema.path('name').index({ sparse: true }); * * @param {Boolean} bool * @return {SchemaType} this * @api public */ SchemaType.prototype.sparse = function(bool) { 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.sparse = bool; 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 * var s = new Schema({ name: { type: String, set: capitalize }}) * * // or by retreiving its SchemaType * var 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 and is set as a value on an actual key. * * 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(); * } * * var UserSchema = new Schema({ * email: { type: String, set: toLower } * }); * * var User = db.model('User', UserSchema); * * var user = new User({email: 'AVENUE@Q.COM'}); * console.log(user.email); // 'avenue@q.com' * * // or * var 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. * * _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; * } * } * * var VirusSchema = new Schema({ * name: { type: String, required: true, set: inspector }, * taxonomy: { type: String, set: inspector } * }) * * var Virus = db.model('Virus', VirusSchema); * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); * * console.log(v.name); // name is required * console.log(v.taxonomy); // Parvovirinae * * @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 * var s = new Schema({ born: { type: Date, get: dob }) * * // or by retreiving its SchemaType * var 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); * } * * var AccountSchema = new Schema({ * creditCardNumber: { type: String, get: obfuscate } * }); * * var 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'; * } * } * * var VirusSchema = new Schema({ * name: { type: String, required: true, get: inspector }, * taxonomy: { type: String, get: inspector } * }) * * var 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` 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 * * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] * new Schema({ name: { type: String, validate: custom }}); * * // adding many validators at a time * * var many = [ * { validator: validator, msg: 'uh oh' } * , { validator: anotherValidator, msg: 'failed' } * ] * new Schema({ name: { type: String, validate: many }}); * * // or utilizing SchemaType methods directly: * * var 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) * * ####Asynchronous validation: * * Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either `true` or `false` to communicate either success or failure respectively. * * schema.path('name').validate({ * isAsync: true, * validator: function (value, respond) { * doStuff(value, function () { * ... * respond(false); // validation failed * }); * }, * message: 'Custom error message!' // Optional * }); * * // Can also return a promise * 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. * * var conn = mongoose.createConnection(..); * conn.on('error', handleError); * * var Product = conn.model('Product', yourSchema); * var dvd = new Product(..); * dvd.save(); // emits error on the `conn` above * * If you desire handling these errors at the Model level, attach an `error` listener to your Model and the event will instead be emitted there. * * // registering an error listener on the Model lets us handle errors more locally * Product.on('error', handleError); * * @param {RegExp|Function|Object} obj validator * @param {String} [errorMsg] optional error message * @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') { var properties; 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) { message = MongooseError.messages.general.default; } if (!type) { type = 'user defined'; } properties = {message: message, type: type, validator: obj}; } this.validators.push(properties); return this; } var i, length, arg; for (i = 0, length = arguments.length; i < length; i++) { arg = arguments[i]; if (!(arg && utils.getFunctionName(arg.constructor) === 'Object')) { var 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; }; /** * Adds a required validator to this SchemaType. The validator gets added * to the front of this SchemaType's validators array using `unshift()`. * * ####Example: * * var s = new Schema({ born: { type: Date, required: true }) * * // or with custom error message * * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) * * // or with a function * * var s = new Schema({ * userId: ObjectId, * username: { * type: String, * required: function() { return this.userId != null; } * } * }) * * // or with a function and a custom message * var 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 * * Schema.path('name').required(true); * * // with custom error messaging * * Schema.path('name').required(true, 'grrr :( '); * * // or make a path conditionally required based on a function * var isOver18 = function() { return this.age >= 18; }; * Schema.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) { var customOptions = {}; 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; return this; } var _this = this; this.isRequired = true; this.requiredValidator = function(v) { // no validation when this path wasn't selected in the query. if (this != null && this.$__ && !this.isSelected(_this.path) && !this.isModified(_this.path)) { return true; } return ((typeof required === 'function') && !required.apply(this)) || _this.checkRequired(v, this); }; this.originalRequiredValue = required; if (typeof required === 'string') { message = required; required = undefined; } var msg = message || MongooseError.messages.general.required; this.validators.unshift(Object.assign({}, customOptions, { validator: this.requiredValidator, message: msg, type: 'required' })); 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) { var 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); } var casted = this.cast(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) { var v = value; var setters = this.setters; var len = setters.length; var caster = this.caster; while (len--) { v = setters[len].call(scope, v, this); } if (Array.isArray(v) && caster && caster.setters) { var newVal = []; for (var i = 0; i < v.length; i++) { newVal.push(caster.applySetters(v[i], scope, init, priorVal)); } v = newVal; } return v; }; /** * Applies setters * * @param {Object} value * @param {Object} scope * @param {Boolean} init * @api private */ SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { var v = this._applySetters(value, scope, init, priorVal, options); if (v == null) { return 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) { var err = false; var path = this.path; var count = this.validators.length; if (!count) { return fn(null); } var validate = function(ok, validatorProperties) { if (err) { return; } if (ok === undefined || ok) { if (--count <= 0) { utils.immediate(function() { fn(null); }); } } else { var ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err.$isValidatorError = true; utils.immediate(function() { fn(err); }); } }; var _this = this; this.validators.forEach(function(v) { if (err) { return; } var validator = v.validator; var ok; var validatorProperties = utils.clone(v); validatorProperties.path = path; validatorProperties.value = value; if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); } else if (typeof validator === 'function') { if (value === undefined && validator !== _this.requiredValidator) { validate(true, validatorProperties); return; } if (validatorProperties.isAsync) { asyncValidate(validator, scope, value, validatorProperties, validate); } else { try { 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; ok = false; validate(ok, validatorProperties); }); } else { validate(ok, validatorProperties); } } } }); }; /*! * Handle async validators */ function asyncValidate(validator, scope, value, props, cb) { var called = false; var returnVal = validator.call(scope, value, function(ok, customMsg) { if (called) { return; } called = true; if (typeof returnVal === 'boolean') { return; } 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; 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) { var err = null, path = this.path, count = this.validators.length; if (!count) { return null; } var validate = function(ok, validatorProperties) { if (err) { return; } if (ok !== undefined && !ok) { var ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; err = new ErrorConstructor(validatorProperties); err.$isValidatorError = true; } }; var validators = this.validators; if (value === void 0) { if (this.validators.length > 0 && this.validators[0].type === 'required') { validators = [this.validators[0]]; } else { return null; } } validators.forEach(function(v) { if (err) { return; } var validator = v.validator; var validatorProperties = utils.clone(v); validatorProperties.path = path; validatorProperties.value = value; var ok; if (validator instanceof RegExp) { validate(validator.test(value), validatorProperties); } else if (typeof validator === 'function') { // if not async validators if (validator.length !== 2 && !validatorProperties.isAsync) { try { ok = validator.call(scope, value); } catch (error) { ok = false; validatorProperties.reason = error; } validate(ok, validatorProperties); } } }); return err; }; /** * 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 var ref = init && self.options && self.options.ref; if (!ref && doc && doc.$__fullPath) { // checks for // - this populated with adhoc model and no ref was set in schema OR // - setting / pushing values after population var path = doc.$__fullPath(self.path); var owner = doc.ownerDocument ? doc.ownerDocument() : doc; ref = owner.populated(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) { var _this = this; if (!Array.isArray(val)) { return [this.castForQuery(val)]; } return val.map(function(m) { return _this.castForQuery(m); }); } /*! * ignore */ SchemaType.prototype.$conditionalHandlers = { $all: handleArray, $eq: handleSingle, $in: handleArray, $ne: handleSingle, $nin: handleArray, $exists: $exists, $type: $type }; /*! * Wraps `castForQuery` to handle context */ SchemaType.prototype.castForQueryWrapper = function(params) { this.$$context = params.context; if ('$conditional' in params) { return this.castForQuery(params.$conditional, params.val); } if (params.$skipQueryCastForUpdate) { return this._castForQuery(params.val); } return this.castForQuery(params.val); }; /** * 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) { var 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); }; /** * Default check for if this path satisfies the `required` validator. * * @param {any} val * @api private */ SchemaType.prototype.checkRequired = function(val) { return val != null; }; /*! * Module exports. */ module.exports = exports = SchemaType; exports.CastError = CastError; exports.ValidatorError = ValidatorError; }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":335,"./error":419,"./schema/operators/exists":447,"./schema/operators/type":450,"./utils":469}],453:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ var ObjectId = require('../types/objectid'); var utils = require('../utils'); exports.flatten = flatten; exports.modifiedPaths = modifiedPaths; /*! * ignore */ function flatten(update, path, options) { var keys; if (update && utils.isMongooseObject(update) && !Buffer.isBuffer(update)) { keys = Object.keys(update.toObject({ transform: false, virtuals: false })); } else { keys = Object.keys(update || {}); } var numKeys = keys.length; var result = {}; path = path ? path + '.' : ''; for (var i = 0; i < numKeys; ++i) { var key = keys[i]; var val = update[key]; result[path + key] = val; if (shouldFlatten(val)) { if (options && options.skipArrays && Array.isArray(val)) { continue; } var flat = flatten(val, path + key, options); for (var k in flat) { result[k] = flat[k]; } if (Array.isArray(val)) { result[path + key] = val; } } } return result; } /*! * ignore */ function modifiedPaths(update, path, result) { var keys = Object.keys(update || {}); var numKeys = keys.length; result = result || {}; path = path ? path + '.' : ''; for (var i = 0; i < numKeys; ++i) { var key = keys[i]; var val = update[key]; result[path + key] = true; if (utils.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); } }).call(this,require("buffer").Buffer) },{"../types/objectid":467,"../utils":469,"buffer":144}],454:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = function cleanModifiedSubpaths(doc, path) { var _modifiedPaths = Object.keys(doc.$__.activePaths.states.modify); var _numModifiedPaths = _modifiedPaths.length; var deleted = 0; for (var j = 0; j < _numModifiedPaths; ++j) { if (_modifiedPaths[j].indexOf(path + '.') === 0) { delete doc.$__.activePaths.states.modify[_modifiedPaths[j]]; ++deleted; } } return deleted; }; },{}],455:[function(require,module,exports){ 'use strict'; var Document; var utils = require('../../utils'); /*! * exports */ exports.compile = compile; exports.defineKey = defineKey; /*! * Compiles schemas. */ function compile(tree, proto, prefix, options) { Document = Document || require('../../document'); var keys = Object.keys(tree); var i = keys.length; var len = keys.length; var limb; var key; for (i = 0; i < len; ++i) { key = keys[i]; limb = tree[key]; defineKey(key, ((utils.getFunctionName(limb.constructor) === 'Object' && Object.keys(limb).length) && (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)) ? limb : null) , 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'); var path = (prefix ? prefix + '.' : '') + prop; prefix = prefix || ''; if (subprops) { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { var _this = this; if (!this.$__.getters) { this.$__.getters = {}; } if (!this.$__.getters[path]) { var nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); // save scope for nested getters/setters if (!prefix) { nested.$__.scope = this; } nested.$__.nestedPath = path; Object.defineProperty(nested, 'schema', { 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)); } }); Object.defineProperty(nested, 'toJSON', { enumerable: false, configurable: true, writable: false, value: function() { return _this.get(path); } }); Object.defineProperty(nested, '$__isNested', { enumerable: false, configurable: true, writable: false, value: true }); compile(subprops, nested, path, options); this.$__.getters[path] = nested; } return this.$__.getters[path]; }, set: function(v) { if (v instanceof Document) { v = v.toObject({ transform: false }); } var doc = this.$__.scope || this; return doc.$set(path, v); } }); } else { Object.defineProperty(prototype, prop, { enumerable: true, configurable: true, get: function() { return this.get.call(this.$__.scope || this, path); }, set: function(v) { return this.$set.call(this.$__.scope || this, path, v); } }); } } // gets descriptors for all properties of `object` // makes all properties non-enumerable to match previous behavior to #2211 function getOwnPropertyDescriptors(object) { var 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'].indexOf(key) === -1; }); return result; } },{"../../document":404,"../../utils":469}],456:[function(require,module,exports){ 'use strict'; /*! * ignore */ module.exports = applyHooks; /*! * 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 (let i = 0; i < schema.childSchemas.length; ++i) { const childModel = schema.childSchemas[i].model; if (childModel.$appliedHooks) { continue; } applyHooks(childModel, schema.childSchemas[i].schema, options); if (childModel.discriminators != null) { let keys = Object.keys(childModel.discriminators); for (let j = 0; j < keys.length; ++j) { applyHooks(childModel.discriminators[keys[j]], childModel.discriminators[keys[j]].schema, options); } } } objToDecorate.$__save = schema.s.hooks. createWrapper('save', objToDecorate.$__save, null, kareemOptions); objToDecorate.$__validate = schema.s.hooks. createWrapper('validate', objToDecorate.$__validate, null, kareemOptions); objToDecorate.$__remove = schema.s.hooks. createWrapper('remove', objToDecorate.$__remove, null, kareemOptions); objToDecorate.$__init = schema.s.hooks. createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); } },{}],457:[function(require,module,exports){ 'use strict'; var defineKey = require('../document/compile').defineKey; var utils = require('../../utils'); var CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { toJSON: true, toObject: true, _id: true, id: true }; /*! * ignore */ module.exports = function discriminator(model, name, schema) { if (!(schema && schema.instanceOfSchema)) { throw new Error('You must pass a valid discriminator Schema'); } if (model.base && model.base.options.applyPluginsToDiscriminators) { model.base._applyPlugins(schema); } if (model.schema.discriminatorMapping && !model.schema.discriminatorMapping.isRoot) { throw new Error('Discriminator "' + name + '" can only be a discriminator of the root model'); } var key = model.schema.options.discriminatorKey; var 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 + '"'); } function merge(schema, baseSchema) { if (baseSchema.paths._id && baseSchema.paths._id.options && !baseSchema.paths._id.options.auto) { var originalSchema = schema; utils.merge(schema, originalSchema); delete schema.paths._id; delete schema.tree._id; } utils.merge(schema, baseSchema, { omit: { discriminators: true } }); var obj = {}; obj[key] = { default: name, select: true, set: function(newName) { if (newName === name) { return name; } throw new Error('Can\'t set discriminator key "' + key + '"'); }, $skipDiscriminatorCheck: true }; obj[key][schema.options.typeKey] = String; schema.add(obj); schema.discriminatorMapping = {key: key, value: name, isRoot: false}; if (baseSchema.options.collection) { schema.options.collection = baseSchema.options.collection; } var toJSON = schema.options.toJSON; var toObject = schema.options.toObject; var _id = schema.options._id; var id = schema.options.id; var keys = Object.keys(schema.options); schema.options.discriminatorKey = baseSchema.options.discriminatorKey; for (var i = 0; i < keys.length; ++i) { var _key = keys[i]; if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { 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(baseSchema.plugins); schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); schema._requiredpaths = undefined; // 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}; model.schema.discriminators = {}; } model.schema.discriminators[name] = schema; if (model.discriminators[name]) { throw new Error('Discriminator with name "' + name + '" already exists'); } return schema; }; },{"../../utils":469,"../document/compile":455}],458:[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; }; },{}],459:[function(require,module,exports){ 'use strict'; const isDefiningProjection = require('./isDefiningProjection'); /*! * ignore */ module.exports = function isExclusive(projection) { let 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":458}],460:[function(require,module,exports){ /*! * Module dependencies. */ var utils = require('./utils'); /*! * StateMachine represents a minimal `interface` for the * constructors it builds via StateMachine.ctor(...). * * @api private */ var 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() { var states = utils.args(arguments); var ctor = function() { StateMachine.apply(this, arguments); this.paths = {}; this.states = {}; this.stateNames = states; var 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) { var 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) { var keys = Object.keys(this.states[state]), i = keys.length, 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() { var _this = this; var 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() { var numArgs = arguments.length, states = utils.args(arguments, 0, numArgs - 1), callback = arguments[numArgs - 1]; if (!states.length) states = this.stateNames; var _this = this; var 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":469}],461:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ const EmbeddedDocument = require('./embedded'); const Document = require('../document'); const ObjectId = require('./objectid'); const cleanModifiedSubpaths = require('../services/document/cleanModifiedSubpaths'); const internalToObjectOptions = require('../options').internalToObjectOptions; const utils = require('../utils'); const isMongooseObject = utils.isMongooseObject; /** * 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) { var arr = [].concat(values); var keysMA = Object.keys(MongooseArray.mixin); var numKeys = keysMA.length; for (var i = 0; i < numKeys; ++i) { arr[keysMA[i]] = MongooseArray.mixin[keysMA[i]]; } arr._path = path; arr.isMongooseArray = true; arr.validators = []; arr._atomics = {}; arr._schema = 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._parent = doc; arr._schema = doc.schema.path(path); } return arr; } MongooseArray.mixin = { /*! * ignore */ toBSON: function() { return this.toObject(internalToObjectOptions); }, /** * Stores a queue of atomic operations to perform * * @property _atomics * @api private */ _atomics: undefined, /** * Parent owner document * * @property _parent * @api private * @receiver MongooseArray */ _parent: undefined, /** * Casts a member based on this arrays schema. * * @param {any} value * @return value the casted value * @method _cast * @api private * @receiver MongooseArray */ _cast: function(value) { var populated = false; var Model; if (this._parent) { populated = this._parent.populated(this._path, true); } if (populated && value !== null && value !== undefined) { // cast to the populated Models schema Model = populated.options.model || populated.options.Model; // 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 var isDisc = value.schema && value.schema.discriminatorMapping && value.schema.discriminatorMapping.key !== undefined; if (!isDisc) { value = new Model(value); } return this._schema.caster.applySetters(value, this._parent, true); } return this._schema.caster.applySetters(value, this._parent, false); }, /** * 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 * @receiver MongooseArray */ _markModified: function(elem, embeddedPath) { var parent = this._parent, dirtyPath; if (parent) { dirtyPath = this._path; 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; } } 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 * @receiver MongooseArray */ _registerAtomic: function(op, val) { if (op === '$set') { // $set takes precedence over all other ops. // mark entire array modified. this._atomics = {$set: val}; return this; } var atomics = this._atomics; // reset pop/shift after save if (op === '$pop' && !('$pop' in atomics)) { var _this = this; this._parent.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._atomics.$set || Object.keys(atomics).length && !(op in atomics)) { // a different op was previously registered. // save the entire thing. this._atomics = {$set: this}; return this; } var selector; if (op === '$pullAll' || op === '$addToSet') { atomics[op] || (atomics[op] = []); atomics[op] = atomics[op].concat(val); } else if (op === '$pullDocs') { var 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: [] }; atomics.$push.$each = atomics.$push.$each.concat(val); } else { atomics[op] = val; } return this; }, /** * 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 * @api private */ $__getAtomics: function() { var ret = []; var keys = Object.keys(this._atomics); var i = keys.length; const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); if (i === 0) { ret[0] = ['$set', this.toObject(opts)]; return ret; } while (i--) { var op = keys[i]; var val = this._atomics[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 (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.valueOf) { val = val.valueOf(); } if (op === '$addToSet') { val = {$each: val}; } ret.push([op, val]); } return ret; }, /** * Returns the number of pending atomic operations to send to the db for this array. * * @api private * @return {Number} * @method hasAtomics * @receiver MongooseArray */ hasAtomics: function hasAtomics() { if (!(this._atomics && this._atomics.constructor.name === 'Object')) { return 0; } return Object.keys(this._atomics).length; }, /** * Internal helper for .map() * * @api private * @return {Number} * @method _mapCast * @receiver MongooseArray */ _mapCast: function(val, index) { return this._cast(val, this.length + index); }, /** * 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 * @receiver MongooseArray */ push: function() { _checkManualPopulation(this, arguments); var values = [].map.call(arguments, this._mapCast, this); values = this._schema.applySetters(values, this._parent, undefined, undefined, { skipDocumentArrayCast: true }); var ret = [].push.apply(this, values); this._registerAtomic('$push', values); this._markModified(); return ret; }, /** * 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 * @receiver MongooseArray */ nonAtomicPush: function() { var values = [].map.call(arguments, this._mapCast, this); var ret = [].push.apply(this, values); this._registerAtomic('$set', this); this._markModified(); return ret; }, /** * 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]; * * var 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 * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop * @method $pop * @receiver MongooseArray */ $pop: function() { this._registerAtomic('$pop', 1); this._markModified(); // only allow popping once if (this._popped) { return; } this._popped = true; return [].pop.call(this); }, /** * 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 * @receiver MongooseArray */ pop: function() { var ret = [].pop.call(this); this._registerAtomic('$set', this); this._markModified(); return ret; }, /** * Atomically shifts the array 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]; * * var 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 * @method $shift * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop */ $shift: function $shift() { this._registerAtomic('$pop', -1); this._markModified(); // only allow shifting once if (this._shifted) { return; } this._shifted = true; return [].shift.call(this); }, /** * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. * * ####Example: * * doc.array = [2,3]; * var 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 * @receiver MongooseArray */ shift: function() { var ret = [].shift.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 * @receiver MongooseArray */ pull: function() { var values = [].map.call(arguments, this._cast, this), cur = this._parent.get(this._path), i = cur.length, mem; while (i--) { mem = cur[i]; if (mem instanceof Document) { var 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._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._parent, this._path) > 0) { this._registerAtomic('$set', this); } return this; }, /** * 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 * @receiver MongooseArray */ splice: function splice() { var ret; var vals; var i; _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); if (arguments.length) { vals = []; for (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); this._markModified(); } return ret; }, /** * 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 overwritting any changes that happen between when you retrieved the object and when you save it._ * * @api public * @method unshift * @receiver MongooseArray */ unshift: function() { _checkManualPopulation(this, arguments); var values = [].map.call(arguments, this._cast, this); values = this._schema.applySetters(values, this._parent); [].unshift.apply(this, values); this._registerAtomic('$set', this); this._markModified(); return this.length; }, /** * 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 * @receiver MongooseArray */ sort: function() { var ret = [].sort.apply(this, arguments); this._registerAtomic('$set', this); this._markModified(); return ret; }, /** * Adds values to the array if not already present. * * ####Example: * * console.log(doc.array) // [2,3,4] * var 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 * @receiver MongooseArray * @api public * @method addToSet */ addToSet: function addToSet() { _checkManualPopulation(this, arguments); var values = [].map.call(arguments, this._mapCast, this); values = this._schema.applySetters(values, this._parent); var added = []; var type = ''; if (values[0] instanceof EmbeddedDocument) { type = 'doc'; } else if (values[0] instanceof Date) { type = 'date'; } values.forEach(function(v) { var found; switch (type) { case 'doc': found = this.some(function(doc) { return doc.equals(v); }); break; case 'date': var val = +v; 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; }, /** * Sets the casted `val` at index `i` and marks the array modified. * * ####Example: * * // given documents based on the following * var Doc = mongoose.model('Doc', new Schema({ array: [Number] })); * * var 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 * @receiver MongooseArray */ set: function set(i, val) { var value = this._cast(val, i); this[i] = value; this._markModified(i); return this; }, /** * Returns a native js Array. * * @param {Object} options * @return {Array} * @api public * @method toObject * @receiver MongooseArray */ toObject: function(options) { if (options && options.depopulate) { options = utils.clone(options); options._isNested = true; return this.map(function(doc) { return doc instanceof Document ? doc.toObject(options) : doc; }); } return this.slice(); }, /** * Helper for console.log * * @api public * @method inspect * @receiver MongooseArray */ inspect: function() { return JSON.stringify(this); }, /** * Return the index of `obj` or `-1` if not found. * * @param {Object} obj the item to look for * @return {Number} * @api public * @method indexOf * @receiver MongooseArray */ indexOf: function indexOf(obj) { if (obj instanceof ObjectId) { obj = obj.toString(); } for (var i = 0, len = this.length; i < len; ++i) { if (obj == this[i]) { return i; } } return -1; } }; /** * Alias of [pull](#types_array_MongooseArray-pull) * * @see MongooseArray#pull #types_array_MongooseArray-pull * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull * @api public * @memberOf MongooseArray * @method remove */ MongooseArray.mixin.remove = MongooseArray.mixin.pull; /*! * ignore */ function _isAllSubdocs(docs, ref) { if (!ref) { return false; } for (var i = 0; i < docs.length; ++i) { var arg = docs[i]; if (arg == null) { return false; } var model = arg.constructor; if (!(arg instanceof Document) || (model.modelName !== ref && model.baseModelName !== ref)) { return false; } } return true; } /*! * ignore */ function _checkManualPopulation(arr, docs) { var ref = arr._schema.caster.options && arr._schema.caster.options.ref; if (arr.length === 0 && docs.length > 0) { if (_isAllSubdocs(docs, ref)) { arr._parent.populated(arr._path, [], { model: docs[0].constructor }); } } } /*! * Module exports. */ module.exports = exports = MongooseArray; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":335,"../document":404,"../options":431,"../services/document/cleanModifiedSubpaths":454,"../utils":469,"./embedded":465,"./objectid":467}],462:[function(require,module,exports){ (function (Buffer){ /*! * Module dependencies. */ var Binary = require('../drivers').Binary, utils = require('../utils'); /** * 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) { var length = arguments.length; var val; if (length === 0 || arguments[0] === null || arguments[0] === undefined) { val = 0; } else { val = value; } var encoding; var path; var doc; if (Array.isArray(encode)) { // internal casting path = encode[0]; doc = encode[1]; } else { encoding = encode; } var buf = new Buffer(val, encoding, offset); utils.decorate(buf, MongooseBuffer.mixin); buf.isMongooseBuffer = true; // make sure these internal props don't show up in Object.keys() Object.defineProperties(buf, { validators: { value: [], enumerable: false }, _path: { value: path, enumerable: false }, _parent: { value: doc, enumerable: false } }); if (doc && typeof path === 'string') { Object.defineProperty(buf, '_schema', { value: doc.schema.path(path) }); } buf._subtype = 0; return buf; } /*! * Inherit from Buffer. */ // MongooseBuffer.prototype = new Buffer(0); MongooseBuffer.mixin = { /** * Parent owner document * * @api private * @property _parent * @receiver MongooseBuffer */ _parent: undefined, /** * 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() { var parent = this._parent; if (parent) { parent.markModified(this._path); } return this; }, /** * Writes the buffer. * * @api public * @method write * @receiver MongooseBuffer */ write: function() { var 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) { var 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() { var ret = Buffer.prototype[method].apply(this, arguments); this._markModified(); return ret; }; }); /** * Converts this buffer to its Binary type representation. * * ####SubTypes: * * var 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) { var subtype = typeof options === 'number' ? options : (this._subtype || 0); return new Binary(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 (var 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: * * var 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; }).call(this,require("buffer").Buffer) },{"../drivers":411,"../utils":469,"buffer":144}],463:[function(require,module,exports){ /** * ObjectId type constructor * * ####Example * * var id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ module.exports = require('../drivers').Decimal128; },{"../drivers":411}],464:[function(require,module,exports){ (function (Buffer){ 'use strict'; /*! * Module dependencies. */ const MongooseArray = require('./array'); const ObjectId = require('./objectid'); const ObjectIdSchema = require('../schema/objectid'); const internalToObjectOptions = require('../options').internalToObjectOptions; const utils = require('../utils'); const Document = require('../document'); /** * 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) { var arr = [].concat(values); arr._path = path; var props = { isMongooseArray: true, isMongooseDocumentArray: true, validators: [], _atomics: {}, _schema: void 0, _handlers: void 0 }; // Values always have to be passed to the constructor to initialize, since // otherwise MongooseArray#push will mark the array as modified to the parent. var keysMA = Object.keys(MongooseArray.mixin); var numKeys = keysMA.length; for (var j = 0; j < numKeys; ++j) { arr[keysMA[j]] = MongooseArray.mixin[keysMA[j]]; } var keysMDA = Object.keys(MongooseDocumentArray.mixin); numKeys = keysMDA.length; for (var i = 0; i < numKeys; ++i) { arr[keysMDA[i]] = MongooseDocumentArray.mixin[keysMDA[i]]; } var keysP = Object.keys(props); numKeys = keysP.length; for (var k = 0; k < numKeys; ++k) { arr[keysP[k]] = props[keysP[k]]; } // 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._parent = doc; arr._schema = doc.schema.path(path); arr._handlers = { isNew: arr.notify('isNew'), save: arr.notify('save') }; doc.on('save', arr._handlers.save); doc.on('isNew', arr._handlers.isNew); } return arr; } /*! * Inherits from MongooseArray */ // MongooseDocumentArray.mixin = Object.create( MongooseArray.mixin ); MongooseDocumentArray.mixin = { /*! * ignore */ toBSON: function() { return this.toObject(internalToObjectOptions); }, /** * Overrides MongooseArray#cast * * @method _cast * @api private * @receiver MongooseDocumentArray */ _cast: function(value, index) { var Constructor = this._schema.casterConstructor; if (value instanceof Constructor || // Hack re: #5001, see #5005 (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) { if (!(value.__parent && value.__parentArray)) { // value may have been created using array.create() value.__parent = this._parent; value.__parentArray = this; } value.__index = 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.options.discriminatorKey && typeof value[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]; } return new Constructor(value, this, undefined, undefined, index); }, /** * Searches array items for the first document with a matching _id. * * ####Example: * * var 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: function(id) { var casted, sid, _id; try { var casted_ = ObjectIdSchema.prototype.cast.call({}, id); if (casted_) { casted = String(casted_); } } catch (e) { casted = null; } for (var i = 0, l = this.length; i < l; i++) { if (!this[i]) { continue; } _id = this[i].get('_id'); if (_id === null || typeof _id === 'undefined') { continue; } else if (_id instanceof Document) { sid || (sid = String(id)); if (sid == _id._id) { return this[i]; } } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) { if (utils.deepEqual(id, _id)) { return this[i]; } } else if (casted == _id) { return this[i]; } } 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: function(options) { return this.map(function(doc) { return doc && doc.toObject(options) || null; }); }, /** * Helper for console.log * * @method inspect * @api public * @receiver MongooseDocumentArray */ inspect: function() { return Array.prototype.slice.call(this); }, /** * 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: function(obj) { var Constructor = this._schema.casterConstructor; if (obj && Constructor.discriminators && Constructor.schema.options.discriminatorKey && typeof obj[Constructor.schema.options.discriminatorKey] === 'string' && Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; } return new Constructor(obj); }, /** * Creates a fn that notifies all child docs of `event`. * * @param {String} event * @return {Function} * @method notify * @api private * @receiver MongooseDocumentArray */ notify: function notify(event) { var _this = this; return function notify(val) { var i = _this.length; while (i--) { if (!_this[i]) { 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; } _this[i].emit(event, val); } }; } }; /*! * Module exports. */ module.exports = MongooseDocumentArray; }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) },{"../../../is-buffer/index.js":335,"../document":404,"../options":431,"../schema/objectid":445,"../utils":469,"./array":461,"./objectid":467}],465:[function(require,module,exports){ /* eslint no-func-assign: 1 */ /*! * Module dependencies. */ const Document = require('../document_provider')(); const EventEmitter = require('events').EventEmitter; const internalToObjectOptions = require('../options').internalToObjectOptions; const utils = require('../utils'); /** * 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) { if (parentArr) { this.__parentArray = parentArr; this.__parent = parentArr._parent; } else { this.__parentArray = undefined; this.__parent = undefined; } this.__index = index; Document.call(this, obj, fields, skipId); var _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 (var i in EventEmitter.prototype) { EmbeddedDocument[i] = EventEmitter.prototype[i]; } EmbeddedDocument.prototype.toBSON = function() { return this.toObject(internalToObjectOptions); }; /** * Marks the embedded doc modified. * * ####Example: * * var 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; } if (this.isNew) { // 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(fn) { return utils.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 utils.immediate(() => fn(null, this)); }; /*! * Registers remove event listeners for triggering * on subdocuments. * * @param {EmbeddedDocument} sub * @api private */ function registerRemoveListener(sub) { var 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; } var _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 }); }; /** * 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, first) { if (!this.__parent) { Document.prototype.invalidate.call(this, path, err, val); if (err.$isValidatorError) { return true; } throw err; } var index = this.__index; if (typeof index !== 'undefined') { var parentPath = this.__parentArray._path; var fullPath = [parentPath, index, path].join('.'); this.__parent.invalidate(fullPath, err, val); } if (first) { this.$__.validationError = this.ownerDocument().$__.validationError; } return true; }; /** * 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.__parent) { return; } var index = this.__index; if (typeof index !== 'undefined') { var parentPath = this.__parentArray._path; var fullPath = [parentPath, index, path].join('.'); this.__parent.$markValid(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) { var index = this.__index; if (typeof index !== 'undefined' && this.__parent) { return !this.__parent.$__.validationError || !this.__parent.$__.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; } var parent = this.__parent; if (!parent) { return this; } while (parent.__parent || parent.$parent) { parent = parent.__parent || 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 */ EmbeddedDocument.prototype.$__fullPath = function(path) { if (!this.$__.fullPath) { var parent = this; // eslint-disable-line consistent-this if (!parent.__parent) { return path; } var paths = []; while (parent.__parent || parent.$parent) { if (parent.__parent) { paths.unshift(parent.__parentArray._path); } else { paths.unshift(parent.$basePath); } parent = parent.__parent || 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.__parent; }; /** * Returns this sub-documents parent array. * * @api public */ EmbeddedDocument.prototype.parentArray = function() { return this.__parentArray; }; /*! * Module exports. */ module.exports = EmbeddedDocument; },{"../document_provider":405,"../options":431,"../utils":469,"events":316}],466:[function(require,module,exports){ /*! * Module exports. */ 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.Subdocument = require('./subdocument'); },{"./array":461,"./buffer":462,"./decimal128":463,"./documentarray":464,"./embedded":465,"./objectid":467,"./subdocument":468}],467:[function(require,module,exports){ /** * ObjectId type constructor * * ####Example * * var id = new mongoose.Types.ObjectId; * * @constructor ObjectId */ var ObjectId = require('../drivers').ObjectId; module.exports = ObjectId; },{"../drivers":411}],468:[function(require,module,exports){ 'use strict'; var Document = require('../document'); var internalToObjectOptions = require('../options').internalToObjectOptions; var utils = require('../utils'); module.exports = Subdocument; /** * Subdocument constructor. * * @inherits Document * @api private */ function Subdocument(value, fields, parent, skipId, options) { this.$isSingleNested = true; Document.call(this, value, fields, skipId, options); } 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(fn) { return utils.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 utils.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.$markValid = function(path) { Document.prototype.$markValid.call(this, path); if (this.$parent && this.$basePath) { this.$parent.$markValid([this.$basePath, path].join('.')); } }; 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; } }; /** * Returns the top level document of this sub-document. * * @return {Document} */ Subdocument.prototype.ownerDocument = function() { if (this.$__.ownerDocument) { return this.$__.ownerDocument; } var parent = this.$parent; if (!parent) { return this; } while (parent.$parent || parent.__parent) { parent = parent.$parent || parent.__parent; } this.$__.ownerDocument = parent; return this.$__.ownerDocument; }; /** * Returns this sub-documents parent document. * * @api public */ Subdocument.prototype.parent = function() { return this.$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 {EmbeddedDocument} sub * @api private */ function registerRemoveListener(sub) { var 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":404,"../options":431,"../utils":469}],469:[function(require,module,exports){ (function (process,Buffer){ 'use strict'; /*! * Module dependencies. */ const Decimal = require('./types/decimal128'); const ObjectId = require('./types/objectid'); const PromiseProvider = require('./promise_provider'); const cloneRegExp = require('regexp-clone'); const sliced = require('sliced'); const mpath = require('mpath'); const ms = require('ms'); let MongooseBuffer; let MongooseArray; let Document; /*! * 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 (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } if ((a instanceof ObjectId && b instanceof ObjectId) || (a instanceof Decimal && b instanceof Decimal)) { 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 (typeof a !== 'object' && typeof b !== 'object') { return a == b; } if (a === null || b === null || a === undefined || b === undefined) { return false; } if (a.prototype !== b.prototype) { return false; } // 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 (isMongooseObject(a)) { a = a.toObject(); } if (isMongooseObject(b)) { b = b.toObject(); } try { var ka = Object.keys(a), kb = Object.keys(b), key, i; } catch (e) { // happens when one is a string literal and the other isn't return false; } // 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])) { return false; } } return true; }; /*! * 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 * @return {Object} the cloned object * @api private */ exports.clone = function clone(obj, options) { if (obj === undefined || obj === null) { return obj; } if (Array.isArray(obj)) { return cloneArray(obj, options); } if (isMongooseObject(obj)) { if (options && options.json && typeof obj.toJSON === 'function') { return obj.toJSON(options); } return obj.toObject(options); } if (obj.constructor) { switch (exports.getFunctionName(obj.constructor)) { case 'Object': return cloneObject(obj, options); 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 (obj instanceof Decimal) { if (options && options.flattenDecimals) { return obj.toJSON(); } return Decimal.fromString(obj.toString()); } if (!obj.constructor && exports.isObject(obj)) { // object created with Object.create(null) return cloneObject(obj, options); } if (obj.valueOf) { return obj.valueOf(); } }; var clone = exports.clone; /*! * ignore */ exports.promiseOrCallback = function promiseOrCallback(callback, fn) { if (typeof callback === 'function') { try { return fn(callback); } catch (error) { return process.nextTick(() => { throw error; }); } } const Promise = PromiseProvider.get(); return new Promise((resolve, reject) => { fn(function(error, res) { if (error != null) { return reject(error); } if (arguments.length > 2) { return resolve(Array.prototype.slice.call(arguments, 1)); } resolve(res); }); }); }; /*! * ignore */ function cloneObject(obj, options) { const minimize = options && options.minimize; const ret = {}; let hasKeys; let val; let k; for (k in obj) { val = clone(obj[k], options); if (!minimize || (typeof val !== 'undefined')) { hasKeys || (hasKeys = true); ret[k] = val; } } return minimize ? hasKeys && ret : ret; } function cloneArray(arr, options) { var ret = []; for (var i = 0, l = arr.length; i < l; i++) { ret.push(clone(arr[i], options)); } 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) { var keys = Object.keys(defaults), i = keys.length, 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) { options = options || {}; const keys = Object.keys(from); let i = 0; const len = keys.length; let key; while (i < len) { key = keys[i++]; if (options.omit && options.omit[key]) { continue; } if (to[key] == null) { to[key] = from[key]; } else if (exports.isObject(from[key])) { if (!exports.isObject(to[key])) { to[key] = {}; } merge(to[key], from[key], options); } 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')); var ret; if (obj == null) { return obj; } if (obj instanceof Document) { return obj.toObject(); } if (Array.isArray(obj)) { ret = []; for (var i = 0, len = obj.length; i < len; ++i) { ret.push(toObject(obj[i])); } return ret; } if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') || (!obj.constructor && exports.isObject(obj))) { ret = {}; for (var k in obj) { ret[k] = toObject(obj[k]); } return ret; } return obj; }; /*! * Determines if `arg` is an object. * * @param {Object|Array|String|Function|RegExp|any} arg * @api private * @return {Boolean} */ exports.isObject = function(arg) { if (Buffer.isBuffer(arg)) { return true; } return Object.prototype.toString.call(arg) === '[object Object]'; }; /*! * 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 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 */ exports.isMongooseObject = function(v) { Document || (Document = require('./document')); MongooseArray || (MongooseArray = require('./types').Array); MongooseBuffer || (MongooseBuffer = require('./types').Buffer); return v instanceof Document || (v && v.isMongooseArray) || (v && v.isMongooseBuffer); }; var isMongooseObject = exports.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; } var when; if (typeof object.expires !== 'string') { when = object.expires; } else { when = Math.round(ms(object.expires) / 1000); } object.expireAfterSeconds = when; delete object.expires; }; /*! * Populate options constructor */ function PopulateOptions(path, select, match, options, model, subPopulate) { this.path = path; this.match = match; this.select = select; this.options = options; this.model = model; if (typeof subPopulate === 'object') { this.populate = subPopulate; } this._docs = {}; } // make it compatible with utils.clone PopulateOptions.prototype.constructor = Object; // expose exports.PopulateOptions = PopulateOptions; /*! * populate helper */ exports.populate = function populate(path, select, model, match, options, subPopulate) { // 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). // might have passed an object specifying all arguments if (arguments.length === 1) { if (path instanceof PopulateOptions) { return [path]; } if (Array.isArray(path)) { return path.map(function(o) { return exports.populate(o)[0]; }); } if (exports.isObject(path)) { match = path.match; options = path.options; select = path.select; model = path.model; subPopulate = path.populate; path = path.path; } } else if (typeof model !== 'string' && typeof model !== 'function') { options = match; match = model; model = undefined; } if (typeof path !== 'string') { throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); } if (typeof subPopulate === 'object') { subPopulate = exports.populate(subPopulate); } var ret = []; var paths = path.split(' '); options = exports.clone(options); for (var i = 0; i < paths.length; ++i) { ret.push(new PopulateOptions(paths[i], select, match, options, model, subPopulate)); } 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) { mpath.set(path, val, obj, '_doc', map); }; /*! * Returns an array of values from object `o`. * * @param {Object} o * @return {Array} * @private */ exports.object = {}; exports.object.vals = function vals(o) { var keys = Object.keys(o), i = keys.length, 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 */ var 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 falsey 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; }; /*! * 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) { var primitives = {}; var ids = {}; var ret = []; var length = arr.length; for (var i = 0; i < length; ++i) { if (typeof arr[i] === 'number' || typeof arr[i] === 'string') { if (primitives[arr[i]]) { continue; } ret.push(arr[i]); primitives[arr[i]] = true; } else if (arr[i] instanceof ObjectId) { if (ids[arr[i].toString()]) { continue; } ret.push(arr[i]); ids[arr[i].toString()] = true; } else { ret.push(arr[i]); } } 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 (var i = 0, len = a.length; i < len; ++i) { if (a[i] !== b[i]) { return false; } } return true; }; exports.getFunctionName = function(fn) { if (fn.name) { return fn.name; } return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; }; exports.decorate = function(destination, source) { for (var key in source) { 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 }); } var keys = Object.keys(fromObj); var len = keys.length; var i = 0; var key; while (i < len) { key = keys[i++]; if (typeof to[key] === 'undefined') { to[key] = exports.clone(fromObj[key], { transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } else { var val = fromObj[key]; if (val != null && val.valueOf && !(val instanceof Date)) { val = val.valueOf(); } if (exports.isObject(val)) { var obj = val; if (isMongooseObject(val) && !val.isMongooseBuffer) { obj = obj.toObject({ transform: false, virtuals: false, depopulate: true, getters: false, flattenDecimals: false }); } if (val.isMongooseBuffer) { obj = new Buffer(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 (var i = 0; i < arr.length; ++i) { fn(arr[i]); } }; /*! * 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 */ exports.immediate = function immediate(cb) { return process.nextTick(cb); }; /*! * ignore */ exports.noop = function() {}; }).call(this,require('_process'),require("buffer").Buffer) },{"./document":404,"./promise_provider":433,"./types":466,"./types/decimal128":463,"./types/objectid":467,"_process":507,"buffer":144,"mpath":471,"ms":482,"regexp-clone":533,"sliced":547}],470:[function(require,module,exports){ /** * VirtualType constructor * * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. * * ####Example: * * var fullname = schema.virtual('fullname'); * fullname instanceof mongoose.VirtualType // true * * @parma {Object} options * @api public */ function VirtualType(options, name) { this.path = name; this.getters = []; this.setters = []; this.options = options || {}; } /** * Defines a getter. * * ####Example: * * var virtual = schema.virtual('fullname'); * virtual.get(function () { * return this.name.first + ' ' + this.name.last; * }); * * @param {Function} fn * @return {VirtualType} this * @api public */ VirtualType.prototype.get = function(fn) { this.getters.push(fn); return this; }; /** * Defines a setter. * * ####Example: * * var virtual = schema.virtual('fullname'); * virtual.set(function (v) { * var parts = v.split(' '); * this.name.first = parts[0]; * this.name.last = parts[1]; * }); * * @param {Function} fn * @return {VirtualType} this * @api public */ VirtualType.prototype.set = function(fn) { this.setters.push(fn); return this; }; /** * Applies getters to `value` using optional `scope`. * * @param {Object} value * @param {Object} scope * @return {any} the value after applying all getters * @api public */ VirtualType.prototype.applyGetters = function(value, scope) { var v = value; for (var l = this.getters.length - 1; l >= 0; l--) { v = this.getters[l].call(scope, v, this); } return v; }; /** * Applies setters to `value` using optional `scope`. * * @param {Object} value * @param {Object} scope * @return {any} the value after applying all setters * @api public */ VirtualType.prototype.applySetters = function(value, scope) { var v = value; for (var l = this.setters.length - 1; l >= 0; l--) { v = this.setters[l].call(scope, v, this); } return v; }; /*! * exports */ module.exports = VirtualType; },{}],471:[function(require,module,exports){ module.exports = exports = require('./lib'); },{"./lib":472}],472:[function(require,module,exports){ /** * 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 ? path.split('.') : 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); return obj.map(function (item) { return item ? exports.get(paths, item, special || lookup, map) : map(undefined); }); } if (lookup) { obj = lookup(obj, part); } else { obj = special && obj[special] ? obj[special][part] : obj[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' ? path.split('.') : 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' ? path.split('.') : 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; } if (i === len - 1) { delete cur[parts[i]]; return true; } cur = 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 ? path.split('.') : path if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } if (null == o) 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. var copy = _copying || /\$/.test(path) , 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 { obj = special && obj[special] ? obj[special][part] : obj[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)) { for (var item, j = 0; j < obj.length && j < val.length; ++j) { item = obj[j]; if (item) { if (lookup) { lookup(item, part, map(val[j])); } else { if (item[special]) item = item[special]; item[part] = map(val[j]); } } } } else { for (var j = 0; j < obj.length; ++j) { 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 { obj[part] = map(val); } } } /*! * Returns the value passed to it. */ function K (v) { return v; } },{}],473:[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'); } } },{}],474:[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":476,"./collection":473,"./node":475}],475:[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); } /** * 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":479,"./collection":473}],476:[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":507,"buffer":144}],477:[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'); /** * 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 = {}; this.setOptions(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; } /** * 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; if (('string' == type || utils.isArgumentsObject(arg)) && 'number' == typeof arg.length || Array.isArray(arg)) { if ('string' == type) arg = arg.split(/\s+/); for (var 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 (var 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 len; this._validate('sort'); var type = typeof arg; // .sort([['field', 1], ['test', -1]]) if (Array.isArray(arg)) { len = arg.length; for (var 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 (var i = 0; i < len; ++i) { var 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 (var i = 0; i < keys.length; ++i) { var 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 */ 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 })`"); } if (value && value.$meta) { var s = opts.sort || (opts.sort = {}); s[field] = { $meta : value.$meta }; return; } var val = String(value || 1).toLowerCase(); if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) { if (utils.isArray(value)) value = '['+value+']'; throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }'); } // store `sort` in a sane format var s = opts.sort || (opts.sort = {}); var valueStr = value.toString() .replace("asc", "1") .replace("ascending", "1") .replace("desc", "-1") .replace("descending", "-1"); s[field] = parseInt(valueStr, 10); } 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 valueStr = value.toString() .replace("asc", "1") .replace("ascending", "1") .replace("desc", "-1") .replace("descending", "-1"); opts.sort.push([field, value]); } 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 valueStr = value.toString() .replace("asc", "1") .replace("ascending", "1") .replace("desc", "-1") .replace("descending", "-1"); opts.sort.set(key, valueStr); }); } /** * 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) * * @method maxTime * @memberOf Query * @param {Number} val * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS * @api public */ Query.prototype.maxTime = function (v) { this._validate('maxTime'); this.options.maxTimeMS = v; 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); } /** * 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 }])) * * ####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 = 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 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; } /** * 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 self = this , conds = this._conditions , options = this._optionsForExec() 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 , options = this._optionsForExec() 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 self = this , conds = this._conditions , options = this._optionsForExec() 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') break; } 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; var 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 * * @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 = 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 opts = this._optionsForExec() , self = this , fields , sort , doc if ('remove' == type) { opts.remove = true; } else { if (!('new' in opts)) opts.new = true; if (!('upsert' in opts)) opts.upsert = false; doc = this._updateForExec() if (!doc) { if (opts.upsert) { // still need to do the upsert to empty doc doc = { $set: {} }; } else { return this.findOne(callback); } } } var fields = this._fieldsForExec(); if (fields) { opts.fields = fields; } var conds = this._conditions; debug('findAndModify', this._collection.collectionName, conds, doc, opts); callback = this._wrapCallback('findAndModify', callback, { conditions: conds , doc: doc , options: opts }); this._collection .findAndModify(conds, doc, opts, 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 self = this; if ('function' == typeof callback) { this[this.op](callback); } else { return new Query.Promise(function(success, error) { self[self.op](function(err, val) { if (err) error(err); else success(val); self = 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 self = this; return function(cb) { self.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 self = this; var promise = new Query.Promise(function(success, error) { self.exec(function(err, val) { if (err) error(err); else success(val); self = 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() 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 = {} , hasKeys , val 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":474,"./collection/collection":473,"./env":476,"./permissions":478,"./utils":479,"assert":88,"bluebird":90,"debug":288,"sliced":480,"util":563}],478:[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; },{}],479:[function(require,module,exports){ (function (process,Buffer){ 'use strict'; /*! * Module dependencies. */ var RegExpClone = require('regexp-clone') /** * 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 ('ReadPreference' === obj._type && obj.isValid && obj.toObject) { return 'function' == typeof obj.clone ? obj.clone() : 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 */ var cloneObject = exports.cloneObject = function cloneObject (obj, options) { var minimize = options && options.minimize; var ret = {}; var hasKeys; var keys; var val; var k; var i; for (k in obj) { val = clone(obj[k], options); if (!minimize || ('undefined' !== typeof val)) { hasKeys || (hasKeys = true); ret[k] = val; } } return minimize ? hasKeys && ret : ret; }; var cloneArray = 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 */ var tick = 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 */ var merge = exports.merge = function merge (to, from) { var keys = Object.keys(from) , i = keys.length , key while (i--) { key = keys[i]; 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 */ var mergeClone = 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; } /** * Object.prototype.toString.call helper */ var _toString = Object.prototype.toString; var 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 */ var isArray = 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 = new Buffer(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("buffer").Buffer) },{"_process":507,"buffer":144,"regexp-clone":533}],480:[function(require,module,exports){ module.exports = exports = require('./lib/sliced'); },{"./lib/sliced":481}],481:[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; } },{}],482:[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'; } },{}],483:[function(require,module,exports){ exports.endianness = function () { return 'LE' }; exports.hostname = function () { if (typeof location !== 'undefined') { return location.hostname } else return ''; }; exports.loadavg = function () { return [] }; exports.uptime = function () { return 0 }; exports.freemem = function () { return Number.MAX_VALUE; }; exports.totalmem = function () { return Number.MAX_VALUE; }; exports.cpus = function () { return [] }; exports.type = function () { return 'Browser' }; exports.release = function () { if (typeof navigator !== 'undefined') { return navigator.appVersion; } return ''; }; exports.networkInterfaces = exports.getNetworkInterfaces = function () { return {} }; exports.arch = function () { return 'javascript' }; exports.platform = function () { return 'browser' }; exports.tmpdir = exports.tmpDir = function () { return '/tmp'; }; exports.EOL = '\n'; exports.homedir = function () { return '/' }; },{}],484:[function(require,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); function _has(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (_has(source, p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs + len), dest_offs); return; } // Fallback to ordinary array for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i = 0, l = chunks.length; i < l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],485:[function(require,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It isn't worth it to make additional optimizations as in original. // Small size is preferable. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],486:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],487:[function(require,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],488:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); var trees = require('./trees'); var adler32 = require('./adler32'); var crc32 = require('./crc32'); var msg = require('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only(s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; // zmemcpy(buf, strm->next_in, len); utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH - 1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH - 1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length - 1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH - 1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); //s->pending_buf = (uchf *) overlay; s.pending_buf = new utils.Buf8(s.pending_buf_size); // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); s.d_buf = 1 * s.lit_bufsize; //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Initializes the compression dictionary from the given byte * sequence without producing any compressed output. */ function deflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var s; var str, n; var wrap; var avail; var next; var input; var tmpDict; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } s = strm.state; wrap = s.wrap; if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { return Z_STREAM_ERROR; } /* when using zlib wrappers, compute Adler-32 for provided dictionary */ if (wrap === 1) { /* adler32(strm->adler, dictionary, dictLength); */ strm.adler = adler32(strm.adler, dictionary, dictLength, 0); } s.wrap = 0; /* avoid computing Adler-32 in read_buf */ /* if dictionary would fill window, just replace the history */ if (dictLength >= s.w_size) { if (wrap === 0) { /* already empty otherwise */ /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); s.strstart = 0; s.block_start = 0; s.insert = 0; } /* use the tail */ // dictionary = dictionary.slice(dictLength - s.w_size); tmpDict = new utils.Buf8(s.w_size); utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); dictionary = tmpDict; dictLength = s.w_size; } /* insert dictionary into window and hash */ avail = strm.avail_in; next = strm.next_in; input = strm.input; strm.avail_in = dictLength; strm.next_in = 0; strm.input = dictionary; fill_window(s); while (s.lookahead >= MIN_MATCH) { str = s.strstart; n = s.lookahead - (MIN_MATCH - 1); do { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; } while (--n); s.strstart = str; s.lookahead = MIN_MATCH - 1; fill_window(s); } s.strstart += s.lookahead; s.block_start = s.strstart; s.insert = s.lookahead; s.lookahead = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; strm.next_in = next; strm.input = input; strm.avail_in = avail; s.wrap = wrap; return Z_OK; } exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":484,"./adler32":485,"./crc32":487,"./messages":492,"./trees":493}],489:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],490:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); var adler32 = require('./adler32'); var crc32 = require('./crc32'); var inflate_fast = require('./inffast'); var inflate_table = require('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function zswap32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window, src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window, src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more convenient processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' instead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } function inflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var state; var dictid; var ret; /* check state */ if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } state = strm.state; if (state.wrap !== 0 && state.mode !== DICT) { return Z_STREAM_ERROR; } /* check for correct dictionary identifier */ if (state.mode === DICT) { dictid = 1; /* adler32(0, null, 0)*/ /* dictid = adler32(dictid, dictionary, dictLength); */ dictid = adler32(dictid, dictionary, dictLength, 0); if (dictid !== state.check) { return Z_DATA_ERROR; } } /* copy dictionary to window using updatewindow(), which will amend the existing dictionary if appropriate */ ret = updatewindow(strm, dictionary, dictLength, dictLength); if (ret) { state.mode = MEM; return Z_MEM_ERROR; } state.havedict = 1; // Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":484,"./adler32":485,"./crc32":487,"./inffast":489,"./inftrees":491}],491:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* process all codes and make table entries */ for (;;) { /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":484}],492:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. module.exports = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ 1: 'stream end', /* Z_STREAM_END 1 */ 0: '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],493:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } var static_l_desc; var static_d_desc; var static_bl_desc; function TreeDesc(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; tree[m * 2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1]/*.Len*/ = 5; static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n * 2; var _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6 * 2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":484}],494:[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}],495:[function(require,module,exports){ module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.2": "aes-128-cbc", "2.16.840.1.101.3.4.1.3": "aes-128-ofb", "2.16.840.1.101.3.4.1.4": "aes-128-cfb", "2.16.840.1.101.3.4.1.21": "aes-192-ecb", "2.16.840.1.101.3.4.1.22": "aes-192-cbc", "2.16.840.1.101.3.4.1.23": "aes-192-ofb", "2.16.840.1.101.3.4.1.24": "aes-192-cfb", "2.16.840.1.101.3.4.1.41": "aes-256-ecb", "2.16.840.1.101.3.4.1.42": "aes-256-cbc", "2.16.840.1.101.3.4.1.43": "aes-256-ofb", "2.16.840.1.101.3.4.1.44": "aes-256-cfb" } },{}],496:[function(require,module,exports){ // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js // Fedor, you are amazing. 'use strict' var asn1 = require('asn1.js') exports.certificate = require('./certificate') var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { this.seq().obj( this.key('version').int(), this.key('modulus').int(), this.key('publicExponent').int(), this.key('privateExponent').int(), this.key('prime1').int(), this.key('prime2').int(), this.key('exponent1').int(), this.key('exponent2').int(), this.key('coefficient').int() ) }) exports.RSAPrivateKey = RSAPrivateKey var RSAPublicKey = asn1.define('RSAPublicKey', function () { this.seq().obj( this.key('modulus').int(), this.key('publicExponent').int() ) }) exports.RSAPublicKey = RSAPublicKey var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { this.seq().obj( this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr() ) }) exports.PublicKey = PublicKey var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { this.seq().obj( this.key('algorithm').objid(), this.key('none').null_().optional(), this.key('curve').objid().optional(), this.key('params').seq().obj( this.key('p').int(), this.key('q').int(), this.key('g').int() ).optional() ) }) var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { this.seq().obj( this.key('version').int(), this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPrivateKey').octstr() ) }) exports.PrivateKey = PrivateKeyInfo var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { this.seq().obj( this.key('algorithm').seq().obj( this.key('id').objid(), this.key('decrypt').seq().obj( this.key('kde').seq().obj( this.key('id').objid(), this.key('kdeparams').seq().obj( this.key('salt').octstr(), this.key('iters').int() ) ), this.key('cipher').seq().obj( this.key('algo').objid(), this.key('iv').octstr() ) ) ), this.key('subjectPrivateKey').octstr() ) }) exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { this.seq().obj( this.key('version').int(), this.key('p').int(), this.key('q').int(), this.key('g').int(), this.key('pub_key').int(), this.key('priv_key').int() ) }) exports.DSAPrivateKey = DSAPrivateKey exports.DSAparam = asn1.define('DSAparam', function () { this.int() }) var ECPrivateKey = asn1.define('ECPrivateKey', function () { this.seq().obj( this.key('version').int(), this.key('privateKey').octstr(), this.key('parameters').optional().explicit(0).use(ECParameters), this.key('publicKey').optional().explicit(1).bitstr() ) }) exports.ECPrivateKey = ECPrivateKey var ECParameters = asn1.define('ECParameters', function () { this.choice({ namedCurve: this.objid() }) }) exports.signature = asn1.define('signature', function () { this.seq().obj( this.key('r').int(), this.key('s').int() ) }) },{"./certificate":497,"asn1.js":74}],497:[function(require,module,exports){ // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js // thanks to @Rantanen 'use strict' var asn = require('asn1.js') var Time = asn.define('Time', function () { this.choice({ utcTime: this.utctime(), generalTime: this.gentime() }) }) var AttributeTypeValue = asn.define('AttributeTypeValue', function () { this.seq().obj( this.key('type').objid(), this.key('value').any() ) }) var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { this.seq().obj( this.key('algorithm').objid(), this.key('parameters').optional() ) }) var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { this.seq().obj( this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr() ) }) var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { this.setof(AttributeTypeValue) }) var RDNSequence = asn.define('RDNSequence', function () { this.seqof(RelativeDistinguishedName) }) var Name = asn.define('Name', function () { this.choice({ rdnSequence: this.use(RDNSequence) }) }) var Validity = asn.define('Validity', function () { this.seq().obj( this.key('notBefore').use(Time), this.key('notAfter').use(Time) ) }) var Extension = asn.define('Extension', function () { this.seq().obj( this.key('extnID').objid(), this.key('critical').bool().def(false), this.key('extnValue').octstr() ) }) var TBSCertificate = asn.define('TBSCertificate', function () { this.seq().obj( this.key('version').explicit(0).int(), this.key('serialNumber').int(), this.key('signature').use(AlgorithmIdentifier), this.key('issuer').use(Name), this.key('validity').use(Validity), this.key('subject').use(Name), this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), this.key('issuerUniqueID').implicit(1).bitstr().optional(), this.key('subjectUniqueID').implicit(2).bitstr().optional(), this.key('extensions').explicit(3).seqof(Extension).optional() ) }) var X509Certificate = asn.define('X509Certificate', function () { this.seq().obj( this.key('tbsCertificate').use(TBSCertificate), this.key('signatureAlgorithm').use(AlgorithmIdentifier), this.key('signatureValue').bitstr() ) }) module.exports = X509Certificate },{"asn1.js":74}],498:[function(require,module,exports){ (function (Buffer){ // adapted from https://github.com/apatil/pemstrip var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m var evp = require('evp_bytestokey') var ciphers = require('browserify-aes') module.exports = function (okey, password) { var key = okey.toString() var match = key.match(findProc) var decrypted if (!match) { var match2 = key.match(fullRegex) decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64') } else { var suite = 'aes' + match[1] var iv = new Buffer(match[2], 'hex') var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64') var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key var out = [] var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) out.push(cipher.update(cipherText)) out.push(cipher.final()) decrypted = Buffer.concat(out) } var tag = key.match(startRegex)[1] return { tag: tag, data: decrypted } } }).call(this,require("buffer").Buffer) },{"browserify-aes":96,"buffer":144,"evp_bytestokey":317}],499:[function(require,module,exports){ (function (Buffer){ var asn1 = require('./asn1') var aesid = require('./aesid.json') var fixProc = require('./fixProc') var ciphers = require('browserify-aes') var compat = require('pbkdf2') module.exports = parseKeys function parseKeys (buffer) { var password if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { password = buffer.passphrase buffer = buffer.key } if (typeof buffer === 'string') { buffer = new Buffer(buffer) } var stripped = fixProc(buffer, password) var type = stripped.tag var data = stripped.data var subtype, ndata switch (type) { case 'CERTIFICATE': ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo // falls through case 'PUBLIC KEY': if (!ndata) { ndata = asn1.PublicKey.decode(data, 'der') } subtype = ndata.algorithm.algorithm.join('.') switch (subtype) { case '1.2.840.113549.1.1.1': return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') case '1.2.840.10045.2.1': ndata.subjectPrivateKey = ndata.subjectPublicKey return { type: 'ec', data: ndata } case '1.2.840.10040.4.1': ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') return { type: 'dsa', data: ndata.algorithm.params } default: throw new Error('unknown key id ' + subtype) } throw new Error('unknown key type ' + type) case 'ENCRYPTED PRIVATE KEY': data = asn1.EncryptedPrivateKey.decode(data, 'der') data = decrypt(data, password) // falls through case 'PRIVATE KEY': ndata = asn1.PrivateKey.decode(data, 'der') subtype = ndata.algorithm.algorithm.join('.') switch (subtype) { case '1.2.840.113549.1.1.1': return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') case '1.2.840.10045.2.1': return { curve: ndata.algorithm.curve, privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey } case '1.2.840.10040.4.1': ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') return { type: 'dsa', params: ndata.algorithm.params } default: throw new Error('unknown key id ' + subtype) } throw new Error('unknown key type ' + type) case 'RSA PUBLIC KEY': return asn1.RSAPublicKey.decode(data, 'der') case 'RSA PRIVATE KEY': return asn1.RSAPrivateKey.decode(data, 'der') case 'DSA PRIVATE KEY': return { type: 'dsa', params: asn1.DSAPrivateKey.decode(data, 'der') } case 'EC PRIVATE KEY': data = asn1.ECPrivateKey.decode(data, 'der') return { curve: data.parameters.value, privateKey: data.privateKey } default: throw new Error('unknown key type ' + type) } } parseKeys.signature = asn1.signature function decrypt (data, password) { var salt = data.algorithm.decrypt.kde.kdeparams.salt var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] var iv = data.algorithm.decrypt.cipher.iv var cipherText = data.subjectPrivateKey var keylen = parseInt(algo.split('-')[1], 10) / 8 var key = compat.pbkdf2Sync(password, salt, iters, keylen) var cipher = ciphers.createDecipheriv(algo, key, iv) var out = [] out.push(cipher.update(cipherText)) out.push(cipher.final()) return Buffer.concat(out) } }).call(this,require("buffer").Buffer) },{"./aesid.json":495,"./asn1":496,"./fixProc":498,"browserify-aes":96,"buffer":144,"pbkdf2":501}],500:[function(require,module,exports){ (function (process){ // 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. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; }).call(this,require('_process')) },{"_process":507}],501:[function(require,module,exports){ exports.pbkdf2 = require('./lib/async') exports.pbkdf2Sync = require('./lib/sync') },{"./lib/async":502,"./lib/sync":505}],502:[function(require,module,exports){ (function (process,global){ var checkParameters = require('./precondition') var defaultEncoding = require('./default-encoding') var sync = require('./sync') var Buffer = require('safe-buffer').Buffer var ZERO_BUF var subtle = global.crypto && global.crypto.subtle var toBrowser = { 'sha': 'SHA-1', 'sha-1': 'SHA-1', 'sha1': 'SHA-1', 'sha256': 'SHA-256', 'sha-256': 'SHA-256', 'sha384': 'SHA-384', 'sha-384': 'SHA-384', 'sha-512': 'SHA-512', 'sha512': 'SHA-512' } var checks = [] function checkNative (algo) { if (global.process && !global.process.browser) { return Promise.resolve(false) } if (!subtle || !subtle.importKey || !subtle.deriveBits) { return Promise.resolve(false) } if (checks[algo] !== undefined) { return checks[algo] } ZERO_BUF = ZERO_BUF || Buffer.alloc(8) var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) .then(function () { return true }).catch(function () { return false }) checks[algo] = prom return prom } function browserPbkdf2 (password, salt, iterations, length, algo) { return subtle.importKey( 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits'] ).then(function (key) { return subtle.deriveBits({ name: 'PBKDF2', salt: salt, iterations: iterations, hash: { name: algo } }, key, length << 3) }).then(function (res) { return Buffer.from(res) }) } function resolvePromise (promise, callback) { promise.then(function (out) { process.nextTick(function () { callback(null, out) }) }, function (e) { process.nextTick(function () { callback(e) }) }) } module.exports = function (password, salt, iterations, keylen, digest, callback) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) checkParameters(iterations, keylen) if (typeof digest === 'function') { callback = digest digest = undefined } if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') digest = digest || 'sha1' var algo = toBrowser[digest.toLowerCase()] if (!algo || typeof global.Promise !== 'function') { return process.nextTick(function () { var out try { out = sync(password, salt, iterations, keylen, digest) } catch (e) { return callback(e) } callback(null, out) }) } resolvePromise(checkNative(algo).then(function (resp) { if (resp) { return browserPbkdf2(password, salt, iterations, keylen, algo) } else { return sync(password, salt, iterations, keylen, digest) } }), callback) } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./default-encoding":503,"./precondition":504,"./sync":505,"_process":507,"safe-buffer":537}],503:[function(require,module,exports){ (function (process){ var defaultEncoding /* istanbul ignore next */ if (process.browser) { defaultEncoding = 'utf-8' } else { var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' } module.exports = defaultEncoding }).call(this,require('_process')) },{"_process":507}],504:[function(require,module,exports){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs module.exports = function (iterations, keylen) { if (typeof iterations !== 'number') { throw new TypeError('Iterations not a number') } if (iterations < 0) { throw new TypeError('Bad iterations') } if (typeof keylen !== 'number') { throw new TypeError('Key length not a number') } if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ throw new TypeError('Bad key length') } } },{}],505:[function(require,module,exports){ var md5 = require('create-hash/md5') var rmd160 = require('ripemd160') var sha = require('sha.js') var checkParameters = require('./precondition') var defaultEncoding = require('./default-encoding') var Buffer = require('safe-buffer').Buffer var ZEROS = Buffer.alloc(128) var sizes = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, rmd160: 20, ripemd160: 20 } function Hmac (alg, key, saltLen) { var hash = getDigest(alg) var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 if (key.length > blocksize) { key = hash(key) } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) ipad.copy(ipad1, 0, 0, blocksize) this.ipad1 = ipad1 this.ipad2 = ipad this.opad = opad this.alg = alg this.blocksize = blocksize this.hash = hash this.size = sizes[alg] } Hmac.prototype.run = function (data, ipad) { data.copy(ipad, this.blocksize) var h = this.hash(ipad) h.copy(this.opad, this.blocksize) return this.hash(this.opad) } function getDigest (alg) { function shaFunc (data) { return sha(alg).update(data).digest() } if (alg === 'rmd160' || alg === 'ripemd160') return rmd160 if (alg === 'md5') return md5 return shaFunc } function pbkdf2 (password, salt, iterations, keylen, digest) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) checkParameters(iterations, keylen) digest = digest || 'sha1' var hmac = new Hmac(digest, password, salt.length) var DK = Buffer.allocUnsafe(keylen) var block1 = Buffer.allocUnsafe(salt.length + 4) salt.copy(block1, 0, 0, salt.length) var destPos = 0 var hLen = sizes[digest] var l = Math.ceil(keylen / hLen) for (var i = 1; i <= l; i++) { block1.writeUInt32BE(i, salt.length) var T = hmac.run(block1, hmac.ipad1) var U = T for (var j = 1; j < iterations; j++) { U = hmac.run(U, hmac.ipad2) for (var k = 0; k < hLen; k++) T[k] ^= U[k] } T.copy(DK, destPos) destPos += hLen } return DK } module.exports = pbkdf2 },{"./default-encoding":503,"./precondition":504,"create-hash/md5":284,"ripemd160":536,"safe-buffer":537,"sha.js":540}],506:[function(require,module,exports){ (function (process){ 'use strict'; if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; } else { module.exports = process } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this,require('_process')) },{"_process":507}],507:[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; }; },{}],508:[function(require,module,exports){ exports.publicEncrypt = require('./publicEncrypt'); exports.privateDecrypt = require('./privateDecrypt'); exports.privateEncrypt = function privateEncrypt(key, buf) { return exports.publicEncrypt(key, buf, true); }; exports.publicDecrypt = function publicDecrypt(key, buf) { return exports.privateDecrypt(key, buf, true); }; },{"./privateDecrypt":510,"./publicEncrypt":511}],509:[function(require,module,exports){ (function (Buffer){ var createHash = require('create-hash'); module.exports = function (seed, len) { var t = new Buffer(''); var i = 0, c; while (t.length < len) { c = i2ops(i++); t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]); } return t.slice(0, len); }; function i2ops(c) { var out = new Buffer(4); out.writeUInt32BE(c,0); return out; } }).call(this,require("buffer").Buffer) },{"buffer":144,"create-hash":282}],510:[function(require,module,exports){ (function (Buffer){ var parseKeys = require('parse-asn1'); var mgf = require('./mgf'); var xor = require('./xor'); var bn = require('bn.js'); var crt = require('browserify-rsa'); var createHash = require('create-hash'); var withPublic = require('./withPublic'); module.exports = function privateDecrypt(private_key, enc, reverse) { var padding; if (private_key.padding) { padding = private_key.padding; } else if (reverse) { padding = 1; } else { padding = 4; } var key = parseKeys(private_key); var k = key.modulus.byteLength(); if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) { throw new Error('decryption error'); } var msg; if (reverse) { msg = withPublic(new bn(enc), key); } else { msg = crt(enc, key); } var zBuffer = new Buffer(k - msg.length); zBuffer.fill(0); msg = Buffer.concat([zBuffer, msg], k); if (padding === 4) { return oaep(key, msg); } else if (padding === 1) { return pkcs1(key, msg, reverse); } else if (padding === 3) { return msg; } else { throw new Error('unknown padding'); } }; function oaep(key, msg){ var n = key.modulus; var k = key.modulus.byteLength(); var mLen = msg.length; var iHash = createHash('sha1').update(new Buffer('')).digest(); var hLen = iHash.length; var hLen2 = 2 * hLen; if (msg[0] !== 0) { throw new Error('decryption error'); } var maskedSeed = msg.slice(1, hLen + 1); var maskedDb = msg.slice(hLen + 1); var seed = xor(maskedSeed, mgf(maskedDb, hLen)); var db = xor(maskedDb, mgf(seed, k - hLen - 1)); if (compare(iHash, db.slice(0, hLen))) { throw new Error('decryption error'); } var i = hLen; while (db[i] === 0) { i++; } if (db[i++] !== 1) { throw new Error('decryption error'); } return db.slice(i); } function pkcs1(key, msg, reverse){ var p1 = msg.slice(0, 2); var i = 2; var status = 0; while (msg[i++] !== 0) { if (i >= msg.length) { status++; break; } } var ps = msg.slice(2, i - 1); var p2 = msg.slice(i - 1, i); if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){ status++; } if (ps.length < 8) { status++; } if (status) { throw new Error('decryption error'); } return msg.slice(i); } function compare(a, b){ a = new Buffer(a); b = new Buffer(b); var dif = 0; var len = a.length; if (a.length !== b.length) { dif++; len = Math.min(a.length, b.length); } var i = -1; while (++i < len) { dif += (a[i] ^ b[i]); } return dif; } }).call(this,require("buffer").Buffer) },{"./mgf":509,"./withPublic":512,"./xor":513,"bn.js":91,"browserify-rsa":114,"buffer":144,"create-hash":282,"parse-asn1":499}],511:[function(require,module,exports){ (function (Buffer){ var parseKeys = require('parse-asn1'); var randomBytes = require('randombytes'); var createHash = require('create-hash'); var mgf = require('./mgf'); var xor = require('./xor'); var bn = require('bn.js'); var withPublic = require('./withPublic'); var crt = require('browserify-rsa'); var constants = { RSA_PKCS1_OAEP_PADDING: 4, RSA_PKCS1_PADDIN: 1, RSA_NO_PADDING: 3 }; module.exports = function publicEncrypt(public_key, msg, reverse) { var padding; if (public_key.padding) { padding = public_key.padding; } else if (reverse) { padding = 1; } else { padding = 4; } var key = parseKeys(public_key); var paddedMsg; if (padding === 4) { paddedMsg = oaep(key, msg); } else if (padding === 1) { paddedMsg = pkcs1(key, msg, reverse); } else if (padding === 3) { paddedMsg = new bn(msg); if (paddedMsg.cmp(key.modulus) >= 0) { throw new Error('data too long for modulus'); } } else { throw new Error('unknown padding'); } if (reverse) { return crt(paddedMsg, key); } else { return withPublic(paddedMsg, key); } }; function oaep(key, msg){ var k = key.modulus.byteLength(); var mLen = msg.length; var iHash = createHash('sha1').update(new Buffer('')).digest(); var hLen = iHash.length; var hLen2 = 2 * hLen; if (mLen > k - hLen2 - 2) { throw new Error('message too long'); } var ps = new Buffer(k - mLen - hLen2 - 2); ps.fill(0); var dblen = k - hLen - 1; var seed = randomBytes(hLen); var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen)); var maskedSeed = xor(seed, mgf(maskedDb, hLen)); return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k)); } function pkcs1(key, msg, reverse){ var mLen = msg.length; var k = key.modulus.byteLength(); if (mLen > k - 11) { throw new Error('message too long'); } var ps; if (reverse) { ps = new Buffer(k - mLen - 3); ps.fill(0xff); } else { ps = nonZero(k - mLen - 3); } return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k)); } function nonZero(len, crypto) { var out = new Buffer(len); var i = 0; var cache = randomBytes(len*2); var cur = 0; var num; while (i < len) { if (cur === cache.length) { cache = randomBytes(len*2); cur = 0; } num = cache[cur++]; if (num) { out[i++] = num; } } return out; } }).call(this,require("buffer").Buffer) },{"./mgf":509,"./withPublic":512,"./xor":513,"bn.js":91,"browserify-rsa":114,"buffer":144,"create-hash":282,"parse-asn1":499,"randombytes":518}],512:[function(require,module,exports){ (function (Buffer){ var bn = require('bn.js'); function withPublic(paddedMsg, key) { return new Buffer(paddedMsg .toRed(bn.mont(key.modulus)) .redPow(new bn(key.publicExponent)) .fromRed() .toArray()); } module.exports = withPublic; }).call(this,require("buffer").Buffer) },{"bn.js":91,"buffer":144}],513:[function(require,module,exports){ module.exports = function xor(a, b) { var len = a.length; var i = -1; while (++i < len) { a[i] ^= b[i]; } return a }; },{}],514:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],515:[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. 'use strict'; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],516:[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. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],517:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); },{"./decode":515,"./encode":516}],518:[function(require,module,exports){ (function (process,global){ 'use strict' function oldBrowser () { throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') } var Buffer = require('safe-buffer').Buffer var crypto = global.crypto || global.msCrypto if (crypto && crypto.getRandomValues) { module.exports = randomBytes } else { module.exports = oldBrowser } function randomBytes (size, cb) { // phantomjs needs to throw if (size > 65536) throw new Error('requested too many random bytes') // in case browserify isn't using the Uint8Array version var rawBytes = new global.Uint8Array(size) // This will not work in older browsers. // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues if (size > 0) { // getRandomValues fails on IE if size == 0 crypto.getRandomValues(rawBytes) } // XXX: phantomjs doesn't like a buffer being passed here var bytes = Buffer.from(rawBytes.buffer) if (typeof cb === 'function') { return process.nextTick(function () { cb(null, bytes) }) } return bytes } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":507,"safe-buffer":537}],519:[function(require,module,exports){ (function (process,global){ 'use strict' function oldBrowser () { throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') } var safeBuffer = require('safe-buffer') var randombytes = require('randombytes') var Buffer = safeBuffer.Buffer var kBufferMaxLength = safeBuffer.kMaxLength var crypto = global.crypto || global.msCrypto var kMaxUint32 = Math.pow(2, 32) - 1 function assertOffset (offset, length) { if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare throw new TypeError('offset must be a number') } if (offset > kMaxUint32 || offset < 0) { throw new TypeError('offset must be a uint32') } if (offset > kBufferMaxLength || offset > length) { throw new RangeError('offset out of range') } } function assertSize (size, offset, length) { if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare throw new TypeError('size must be a number') } if (size > kMaxUint32 || size < 0) { throw new TypeError('size must be a uint32') } if (size + offset > length || size > kBufferMaxLength) { throw new RangeError('buffer too small') } } if ((crypto && crypto.getRandomValues) || !process.browser) { exports.randomFill = randomFill exports.randomFillSync = randomFillSync } else { exports.randomFill = oldBrowser exports.randomFillSync = oldBrowser } function randomFill (buf, offset, size, cb) { if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array') } if (typeof offset === 'function') { cb = offset offset = 0 size = buf.length } else if (typeof size === 'function') { cb = size size = buf.length - offset } else if (typeof cb !== 'function') { throw new TypeError('"cb" argument must be a function') } assertOffset(offset, buf.length) assertSize(size, offset, buf.length) return actualFill(buf, offset, size, cb) } function actualFill (buf, offset, size, cb) { if (process.browser) { var ourBuf = buf.buffer var uint = new Uint8Array(ourBuf, offset, size) crypto.getRandomValues(uint) if (cb) { process.nextTick(function () { cb(null, buf) }) return } return buf } if (cb) { randombytes(size, function (err, bytes) { if (err) { return cb(err) } bytes.copy(buf, offset) cb(null, buf) }) return } var bytes = randombytes(size) bytes.copy(buf, offset) return buf } function randomFillSync (buf, offset, size) { if (typeof offset === 'undefined') { offset = 0 } if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array') } assertOffset(offset, buf.length) if (size === undefined) size = buf.length - offset assertSize(size, offset, buf.length) return actualFill(buf, offset, size) } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":507,"randombytes":518,"safe-buffer":537}],520:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); },{"./lib/_stream_duplex.js":521}],521:[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. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /**/ var processNextTick = require('process-nextick-args').nextTick; /**/ /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /**/ module.exports = Duplex; /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. processNextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); processNextTick(cb, err); }; function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } },{"./_stream_readable":523,"./_stream_writable":525,"core-util-is":146,"inherits":334,"process-nextick-args":506}],522:[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. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":524,"core-util-is":146,"inherits":334}],523:[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. 'use strict'; /**/ var processNextTick = require('process-nextick-args').nextTick; /**/ module.exports = Readable; /**/ var isArray = require('isarray'); /**/ /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = require('events').EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = require('./internal/streams/stream'); /**/ /**/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ /**/ var debugUtil = require('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /**/ var BufferList = require('./internal/streams/BufferList'); var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; processNextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, unpipeInfo); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { processNextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; processNextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; processNextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":521,"./internal/streams/BufferList":526,"./internal/streams/destroy":527,"./internal/streams/stream":528,"_process":507,"core-util-is":146,"events":316,"inherits":334,"isarray":336,"process-nextick-args":506,"safe-buffer":537,"string_decoder/":549,"util":93}],524:[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. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":521,"core-util-is":146,"inherits":334}],525:[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. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; /**/ var processNextTick = require('process-nextick-args').nextTick; /**/ module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; /**/ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ /**/ var internalUtil = { deprecate: require('util-deprecate') }; /**/ /**/ var Stream = require('./internal/streams/stream'); /**/ /**/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var destroyImpl = require('./internal/streams/destroy'); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); processNextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); processNextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack processNextTick(cb, er); // this can emit finish, and it will always happen // after error processNextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /**/ asyncWrite(afterWrite, stream, state, finished, cb); /**/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; processNextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) processNextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = corkReq; } else { state.corkedRequestsFree = corkReq; } } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":521,"./internal/streams/destroy":527,"./internal/streams/stream":528,"_process":507,"core-util-is":146,"inherits":334,"process-nextick-args":506,"safe-buffer":537,"util-deprecate":560}],526:[function(require,module,exports){ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = require('safe-buffer').Buffer; var util = require('util'); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } },{"safe-buffer":537,"util":93}],527:[function(require,module,exports){ 'use strict'; /**/ var processNextTick = require('process-nextick-args').nextTick; /**/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { processNextTick(emitErrorNT, this, err); } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { processNextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":506}],528:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":316}],529:[function(require,module,exports){ module.exports = require('./readable').PassThrough },{"./readable":530}],530:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":521,"./lib/_stream_passthrough.js":522,"./lib/_stream_readable.js":523,"./lib/_stream_transform.js":524,"./lib/_stream_writable.js":525}],531:[function(require,module,exports){ module.exports = require('./readable').Transform },{"./readable":530}],532:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); },{"./lib/_stream_writable.js":525}],533:[function(require,module,exports){ var 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'); } var flags = []; if (regexp.global) flags.push('g'); if (regexp.multiline) flags.push('m'); if (regexp.ignoreCase) flags.push('i'); return new RegExp(regexp.source, flags.join('')); } },{}],534:[function(require,module,exports){ (function (process){ var path = require('path'), fs = require('fs'), f = require('util').format, resolveFrom = require('resolve-from'), semver = require('semver'); var exists = fs.existsSync || path.existsSync; // Find the location of a package.json file near or above the given location var find_package_json = function(location) { var found = false; while(!found) { if (exists(location + '/package.json')) { found = location; } else if (location !== '/') { location = path.dirname(location); } else { return false; } } return location; } // Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies var find_package_json_with_name = function(name) { // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies var currentModule = module; var found = false; while (currentModule) { // Check currentModule has a package.json location = currentModule.filename; var location = find_package_json(location) if (!location) { currentModule = currentModule.parent; continue; } // Read the package.json file var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); // Is the name defined by interal file references var parts = name.split(/\//); // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { currentModule = currentModule.parent; continue; } found = true; break; } // Check whether name has been found in currentModule's peerOptionalDependencies if (!found) { throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); } return { object: object, parts: parts } } var require_optional = function(name, options) { options = options || {}; options.strict = typeof options.strict == 'boolean' ? options.strict : true; var res = find_package_json_with_name(name) var object = res.object; var parts = res.parts; // Unpack the expected version var expectedVersions = object.peerOptionalDependencies[parts[0]]; // The resolved package var moduleEntry = undefined; // Module file var moduleEntryFile = name; try { // Validate if it's possible to read the module moduleEntry = require(moduleEntryFile); } catch(err) { // Attempt to resolve in top level package try { // Get the module entry file moduleEntryFile = resolveFrom(process.cwd(), name); if(moduleEntryFile == null) return undefined; // Attempt to resolve the module moduleEntry = require(moduleEntryFile); } catch(err) { if(err.code === 'MODULE_NOT_FOUND') return undefined; } } // Resolve the location of the module's package.json file var location = find_package_json(require.resolve(moduleEntryFile)); if(!location) { throw new Error('package.json can not be located'); } // Read the module file var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); // Get the version var version = dependentOnModule.version; // Validate if the found module satisfies the version id if(semver.satisfies(version, expectedVersions) == false && options.strict) { var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); error.code = 'OPTIONAL_MODULE_NOT_FOUND'; throw error; } // Satifies the module requirement return moduleEntry; } require_optional.exists = function(name) { try { var m = require_optional(name); if(m === undefined) return false; return true; } catch(err) { return false; } } module.exports = require_optional; }).call(this,require('_process')) },{"_process":507,"fs":123,"path":500,"resolve-from":535,"semver":538,"util":563}],535:[function(require,module,exports){ 'use strict'; var path = require('path'); var Module = require('module'); module.exports = function (fromDir, moduleId) { if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); } fromDir = path.resolve(fromDir); var fromFile = path.join(fromDir, 'noop.js'); try { return Module._resolveFilename(moduleId, { id: fromFile, filename: fromFile, paths: Module._nodeModulePaths(fromDir) }); } catch (err) { return null; } }; },{"module":123,"path":500}],536:[function(require,module,exports){ (function (Buffer){ 'use strict' var inherits = require('inherits') var HashBase = require('hash-base') function RIPEMD160 () { HashBase.call(this, 64) // state this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 this._e = 0xc3d2e1f0 } inherits(RIPEMD160, HashBase) RIPEMD160.prototype._update = function () { var m = new Array(16) for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4) var al = this._a var bl = this._b var cl = this._c var dl = this._d var el = this._e // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 // K = 0x00000000 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10) el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10) dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10) cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10) bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10) al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10) el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10) dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10) cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10) bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10) al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10) el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10) dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10) cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10) bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10) al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10) // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 // K = 0x5a827999 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10) dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10) cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10) bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10) al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10) el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10) dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10) cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10) bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10) al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10) el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10) dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10) cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10) bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10) al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10) el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10) // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12 // K = 0x6ed9eba1 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10) cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10) bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10) al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10) el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10) dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10) cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10) bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10) al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10) el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10) dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10) cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10) bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10) al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10) el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10) dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10) // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 // K = 0x8f1bbcdc // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10) bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10) al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10) el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10) dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10) cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10) bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10) al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10) el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10) dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10) cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10) bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10) al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10) el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10) dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10) cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10) // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 // K = 0xa953fd4e // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10) al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10) el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10) dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10) cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10) bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10) al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10) el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10) dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10) cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10) bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10) al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10) el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10) dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10) cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10) bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10) var ar = this._a var br = this._b var cr = this._c var dr = this._d var er = this._e // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12 // K' = 0x50a28be6 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10) er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10) dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10) cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10) br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10) ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10) er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10) dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10) cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10) br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10) ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10) er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10) dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10) cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10) br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10) ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10) // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2 // K' = 0x5c4dd124 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10) dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10) cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10) br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10) ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10) er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10) dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10) cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10) br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10) ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10) er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10) dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10) cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10) br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10) ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10) er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10) // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13 // K' = 0x6d703ef3 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10) cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10) br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10) ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10) er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10) dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10) cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10) br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10) ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10) er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10) dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10) cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10) br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10) ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10) er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10) dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10) // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 // K' = 0x7a6d76e9 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10) br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10) ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10) er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10) dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10) cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10) br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10) ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10) er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10) dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10) cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10) br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10) ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10) er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10) dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10) cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10) // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 // K' = 0x00000000 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10) ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10) er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10) dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10) cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10) br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10) ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10) er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10) dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10) cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10) br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10) ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10) er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10) dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10) cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10) br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10) // change state var t = (this._b + cl + dr) | 0 this._b = (this._c + dl + er) | 0 this._c = (this._d + el + ar) | 0 this._d = (this._e + al + br) | 0 this._e = (this._a + bl + cr) | 0 this._a = t } RIPEMD160.prototype._digest = function () { // create padding and handle blocks this._block[this._blockOffset++] = 0x80 if (this._blockOffset > 56) { this._block.fill(0, this._blockOffset, 64) this._update() this._blockOffset = 0 } this._block.fill(0, this._blockOffset, 56) this._block.writeUInt32LE(this._length[0], 56) this._block.writeUInt32LE(this._length[1], 60) this._update() // produce result var buffer = new Buffer(20) buffer.writeInt32LE(this._a, 0) buffer.writeInt32LE(this._b, 4) buffer.writeInt32LE(this._c, 8) buffer.writeInt32LE(this._d, 12) buffer.writeInt32LE(this._e, 16) return buffer } function rotl (x, n) { return (x << n) | (x >>> (32 - n)) } function fn1 (a, b, c, d, e, m, k, s) { return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 } function fn2 (a, b, c, d, e, m, k, s) { return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } function fn3 (a, b, c, d, e, m, k, s) { return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 } function fn4 (a, b, c, d, e, m, k, s) { return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } function fn5 (a, b, c, d, e, m, k, s) { return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } module.exports = RIPEMD160 }).call(this,require("buffer").Buffer) },{"buffer":144,"hash-base":318,"inherits":334}],537:[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":144}],538:[function(require,module,exports){ (function (process){ exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version. /* nomin */ var debug; /* nomin */ if (typeof process === 'object' && /* nomin */ process.env && /* nomin */ process.env.NODE_DEBUG && /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) /* nomin */ debug = function() { /* nomin */ var args = Array.prototype.slice.call(arguments, 0); /* nomin */ args.unshift('SEMVER'); /* nomin */ console.log.apply(console, args); /* nomin */ }; /* nomin */ else /* nomin */ debug = function() {}; // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0'; var MAX_LENGTH = 256; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re var re = exports.re = []; var src = exports.src = []; var R = 0; // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. var NUMERICIDENTIFIER = R++; src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; var NUMERICIDENTIFIERLOOSE = R++; src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. var NONNUMERICIDENTIFIER = R++; src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version // Three dot-separated numeric identifiers. var MAINVERSION = R++; src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')'; var MAINVERSIONLOOSE = R++; src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. var PRERELEASEIDENTIFIER = R++; src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')'; var PRERELEASEIDENTIFIERLOOSE = R++; src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. var PRERELEASE = R++; src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; var PRERELEASELOOSE = R++; src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. var BUILDIDENTIFIER = R++; src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. var BUILD = R++; src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. var FULL = R++; var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?'; src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?'; var LOOSE = R++; src[LOOSE] = '^' + LOOSEPLAIN + '$'; var GTLT = R++; src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. var XRANGEIDENTIFIERLOOSE = R++; src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; var XRANGEIDENTIFIER = R++; src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; var XRANGEPLAIN = R++; src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?'; var XRANGEPLAINLOOSE = R++; src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?'; var XRANGE = R++; src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; var XRANGELOOSE = R++; src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion. // Extract anything that could conceivably be a part of a valid semver var COERCE = R++; src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges. // Meaning is "reasonably at or greater than" var LONETILDE = R++; src[LONETILDE] = '(?:~>?)'; var TILDETRIM = R++; src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); var tildeTrimReplace = '$1~'; var TILDE = R++; src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; var TILDELOOSE = R++; src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges. // Meaning is "at least and backwards compatible with" var LONECARET = R++; src[LONECARET] = '(?:\\^)'; var CARETTRIM = R++; src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); var caretTrimReplace = '$1^'; var CARET = R++; src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; var CARETLOOSE = R++; src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version" var COMPARATORLOOSE = R++; src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; var COMPARATOR = R++; src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` var COMPARATORTRIM = R++; src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. var HYPHENRANGE = R++; src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$'; var HYPHENRANGELOOSE = R++; src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all. var STAR = R++; src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]); if (!re[i]) re[i] = new RegExp(src[i]); } exports.parse = parse; function parse(version, loose) { if (version instanceof SemVer) return version; if (typeof version !== 'string') return null; if (version.length > MAX_LENGTH) return null; var r = loose ? re[LOOSE] : re[FULL]; if (!r.test(version)) return null; try { return new SemVer(version, loose); } catch (er) { return null; } } exports.valid = valid; function valid(version, loose) { var v = parse(version, loose); return v ? v.version : null; } exports.clean = clean; function clean(version, loose) { var s = parse(version.trim().replace(/^[=v]+/, ''), loose); return s ? s.version : null; } exports.SemVer = SemVer; function SemVer(version, loose) { if (version instanceof SemVer) { if (version.loose === loose) return version; else version = version.version; } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version); } if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') if (!(this instanceof SemVer)) return new SemVer(version, loose); debug('SemVer', version, loose); this.loose = loose; var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); if (!m) throw new TypeError('Invalid Version: ' + version); this.raw = version; // these are actually numbers this.major = +m[1]; this.minor = +m[2]; this.patch = +m[3]; if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version') if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version') if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version') // numberify any prerelease numeric ids if (!m[4]) this.prerelease = []; else this.prerelease = m[4].split('.').map(function(id) { if (/^[0-9]+$/.test(id)) { var num = +id; if (num >= 0 && num < MAX_SAFE_INTEGER) return num; } return id; }); this.build = m[5] ? m[5].split('.') : []; this.format(); } SemVer.prototype.format = function() { this.version = this.major + '.' + this.minor + '.' + this.patch; if (this.prerelease.length) this.version += '-' + this.prerelease.join('.'); return this.version; }; SemVer.prototype.toString = function() { return this.version; }; SemVer.prototype.compare = function(other) { debug('SemVer.compare', this.version, this.loose, other); if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); return this.compareMain(other) || this.comparePre(other); }; SemVer.prototype.compareMain = function(other) { if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); }; SemVer.prototype.comparePre = function(other) { if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) return -1; else if (!this.prerelease.length && other.prerelease.length) return 1; else if (!this.prerelease.length && !other.prerelease.length) return 0; var i = 0; do { var a = this.prerelease[i]; var b = other.prerelease[i]; debug('prerelease compare', i, a, b); if (a === undefined && b === undefined) return 0; else if (b === undefined) return 1; else if (a === undefined) return -1; else if (a === b) continue; else return compareIdentifiers(a, b); } while (++i); }; // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function(release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0; this.patch = 0; this.minor = 0; this.major++; this.inc('pre', identifier); break; case 'preminor': this.prerelease.length = 0; this.patch = 0; this.minor++; this.inc('pre', identifier); break; case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0; this.inc('patch', identifier); this.inc('pre', identifier); break; // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) this.inc('patch', identifier); this.inc('pre', identifier); break; case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++; this.minor = 0; this.patch = 0; this.prerelease = []; break; case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) this.minor++; this.patch = 0; this.prerelease = []; break; case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) this.patch++; this.prerelease = []; break; // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) this.prerelease = [0]; else { var i = this.prerelease.length; while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++; i = -2; } } if (i === -1) // didn't increment anything this.prerelease.push(0); } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0]; } else this.prerelease = [identifier, 0]; } break; default: throw new Error('invalid increment argument: ' + release); } this.format(); this.raw = this.version; return this; }; exports.inc = inc; function inc(version, release, loose, identifier) { if (typeof(loose) === 'string') { identifier = loose; loose = undefined; } try { return new SemVer(version, loose).inc(release, identifier).version; } catch (er) { return null; } } exports.diff = diff; function diff(version1, version2) { if (eq(version1, version2)) { return null; } else { var v1 = parse(version1); var v2 = parse(version2); if (v1.prerelease.length || v2.prerelease.length) { for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return 'pre'+key; } } } return 'prerelease'; } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return key; } } } } } exports.compareIdentifiers = compareIdentifiers; var numeric = /^[0-9]+$/; function compareIdentifiers(a, b) { var anum = numeric.test(a); var bnum = numeric.test(b); if (anum && bnum) { a = +a; b = +b; } return (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : a > b ? 1 : 0; } exports.rcompareIdentifiers = rcompareIdentifiers; function rcompareIdentifiers(a, b) { return compareIdentifiers(b, a); } exports.major = major; function major(a, loose) { return new SemVer(a, loose).major; } exports.minor = minor; function minor(a, loose) { return new SemVer(a, loose).minor; } exports.patch = patch; function patch(a, loose) { return new SemVer(a, loose).patch; } exports.compare = compare; function compare(a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)); } exports.compareLoose = compareLoose; function compareLoose(a, b) { return compare(a, b, true); } exports.rcompare = rcompare; function rcompare(a, b, loose) { return compare(b, a, loose); } exports.sort = sort; function sort(list, loose) { return list.sort(function(a, b) { return exports.compare(a, b, loose); }); } exports.rsort = rsort; function rsort(list, loose) { return list.sort(function(a, b) { return exports.rcompare(a, b, loose); }); } exports.gt = gt; function gt(a, b, loose) { return compare(a, b, loose) > 0; } exports.lt = lt; function lt(a, b, loose) { return compare(a, b, loose) < 0; } exports.eq = eq; function eq(a, b, loose) { return compare(a, b, loose) === 0; } exports.neq = neq; function neq(a, b, loose) { return compare(a, b, loose) !== 0; } exports.gte = gte; function gte(a, b, loose) { return compare(a, b, loose) >= 0; } exports.lte = lte; function lte(a, b, loose) { return compare(a, b, loose) <= 0; } exports.cmp = cmp; function cmp(a, op, b, loose) { var ret; switch (op) { case '===': if (typeof a === 'object') a = a.version; if (typeof b === 'object') b = b.version; ret = a === b; break; case '!==': if (typeof a === 'object') a = a.version; if (typeof b === 'object') b = b.version; ret = a !== b; break; case '': case '=': case '==': ret = eq(a, b, loose); break; case '!=': ret = neq(a, b, loose); break; case '>': ret = gt(a, b, loose); break; case '>=': ret = gte(a, b, loose); break; case '<': ret = lt(a, b, loose); break; case '<=': ret = lte(a, b, loose); break; default: throw new TypeError('Invalid operator: ' + op); } return ret; } exports.Comparator = Comparator; function Comparator(comp, loose) { if (comp instanceof Comparator) { if (comp.loose === loose) return comp; else comp = comp.value; } if (!(this instanceof Comparator)) return new Comparator(comp, loose); debug('comparator', comp, loose); this.loose = loose; this.parse(comp); if (this.semver === ANY) this.value = ''; else this.value = this.operator + this.semver.version; debug('comp', this); } var ANY = {}; Comparator.prototype.parse = function(comp) { var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; var m = comp.match(r); if (!m) throw new TypeError('Invalid comparator: ' + comp); this.operator = m[1]; if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything. if (!m[2]) this.semver = ANY; else this.semver = new SemVer(m[2], this.loose); }; Comparator.prototype.toString = function() { return this.value; }; Comparator.prototype.test = function(version) { debug('Comparator.test', version, this.loose); if (this.semver === ANY) return true; if (typeof version === 'string') version = new SemVer(version, this.loose); return cmp(version, this.operator, this.semver, this.loose); }; Comparator.prototype.intersects = function(comp, loose) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required'); } var rangeTmp; if (this.operator === '') { rangeTmp = new Range(comp.value, loose); return satisfies(this.value, rangeTmp, loose); } else if (comp.operator === '') { rangeTmp = new Range(this.value, loose); return satisfies(comp.semver, rangeTmp, loose); } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); var sameSemVer = this.semver.version === comp.semver.version; var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, loose) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')); var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, loose) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')); return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; }; exports.Range = Range; function Range(range, loose) { if (range instanceof Range) { if (range.loose === loose) { return range; } else { return new Range(range.raw, loose); } } if (range instanceof Comparator) { return new Range(range.value, loose); } if (!(this instanceof Range)) return new Range(range, loose); this.loose = loose; // First, split based on boolean or || this.raw = range; this.set = range.split(/\s*\|\|\s*/).map(function(range) { return this.parseRange(range.trim()); }, this).filter(function(c) { // throw out any that are not relevant for whatever reason return c.length; }); if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range); } this.format(); } Range.prototype.format = function() { this.range = this.set.map(function(comps) { return comps.join(' ').trim(); }).join('||').trim(); return this.range; }; Range.prototype.toString = function() { return this.range; }; Range.prototype.parseRange = function(range) { var loose = this.loose; range = range.trim(); debug('range', range, loose); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; range = range.replace(hr, hyphenReplace); debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3` range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; var set = range.split(' ').map(function(comp) { return parseComparator(comp, loose); }).join(' ').split(/\s+/); if (this.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function(comp) { return !!comp.match(compRe); }); } set = set.map(function(comp) { return new Comparator(comp, loose); }); return set; }; Range.prototype.intersects = function(range, loose) { if (!(range instanceof Range)) { throw new TypeError('a Range is required'); } return this.set.some(function(thisComparators) { return thisComparators.every(function(thisComparator) { return range.set.some(function(rangeComparators) { return rangeComparators.every(function(rangeComparator) { return thisComparator.intersects(rangeComparator, loose); }); }); }); }); }; // Mostly just for testing and legacy API reasons exports.toComparators = toComparators; function toComparators(range, loose) { return new Range(range, loose).set.map(function(comp) { return comp.map(function(c) { return c.value; }).join(' ').trim().split(' '); }); } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator(comp, loose) { debug('comp', comp); comp = replaceCarets(comp, loose); debug('caret', comp); comp = replaceTildes(comp, loose); debug('tildes', comp); comp = replaceXRanges(comp, loose); debug('xrange', comp); comp = replaceStars(comp, loose); debug('stars', comp); return comp; } function isX(id) { return !id || id.toLowerCase() === 'x' || id === '*'; } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes(comp, loose) { return comp.trim().split(/\s+/).map(function(comp) { return replaceTilde(comp, loose); }).join(' '); } function replaceTilde(comp, loose) { var r = loose ? re[TILDELOOSE] : re[TILDE]; return comp.replace(r, function(_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr); var ret; if (isX(M)) ret = ''; else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; else if (isX(p)) // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; else if (pr) { debug('replaceTilde pr', pr); if (pr.charAt(0) !== '-') pr = '-' + pr; ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0'; } else // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; debug('tilde return', ret); return ret; }); } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets(comp, loose) { return comp.trim().split(/\s+/).map(function(comp) { return replaceCaret(comp, loose); }).join(' '); } function replaceCaret(comp, loose) { debug('caret', comp, loose); var r = loose ? re[CARETLOOSE] : re[CARET]; return comp.replace(r, function(_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr); var ret; if (isX(M)) ret = ''; else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; else if (isX(p)) { if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; } else if (pr) { debug('replaceCaret pr', pr); if (pr.charAt(0) !== '-') pr = '-' + pr; if (M === '0') { if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1); else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0'; } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0'; } else { debug('no pr'); if (M === '0') { if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1); else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; } else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0'; } debug('caret return', ret); return ret; }); } function replaceXRanges(comp, loose) { debug('replaceXRanges', comp, loose); return comp.split(/\s+/).map(function(comp) { return replaceXRange(comp, loose); }).join(' '); } function replaceXRange(comp, loose) { comp = comp.trim(); var r = loose ? re[XRANGELOOSE] : re[XRANGE]; return comp.replace(r, function(ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr); var xM = isX(M); var xm = xM || isX(m); var xp = xm || isX(p); var anyX = xp; if (gtlt === '=' && anyX) gtlt = ''; if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0'; } else { // nothing is forbidden ret = '*'; } } else if (gtlt && anyX) { // replace X with 0 if (xm) m = 0; if (xp) p = 0; if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>='; if (xm) { M = +M + 1; m = 0; p = 0; } else if (xp) { m = +m + 1; p = 0; } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<'; if (xm) M = +M + 1; else m = +m + 1; } ret = gtlt + M + '.' + m + '.' + p; } else if (xm) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; } else if (xp) { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; } debug('xRange return', ret); return ret; }); } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars(comp, loose) { debug('replaceStars', comp, loose); // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[STAR], ''); } // This function is passed to string.replace(re[HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) from = ''; else if (isX(fm)) from = '>=' + fM + '.0.0'; else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0'; else from = '>=' + from; if (isX(tM)) to = ''; else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0'; else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0'; else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; else to = '<=' + to; return (from + ' ' + to).trim(); } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function(version) { if (!version) return false; if (typeof version === 'string') version = new SemVer(version, this.loose); for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version)) return true; } return false; }; function testSet(set, version) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) return false; } if (version.prerelease.length) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (var i = 0; i < set.length; i++) { debug(set[i].semver); if (set[i].semver === ANY) continue; if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver; if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true; } } // Version has a -pre, but it's not one of the ones we like. return false; } return true; } exports.satisfies = satisfies; function satisfies(version, range, loose) { try { range = new Range(range, loose); } catch (er) { return false; } return range.test(version); } exports.maxSatisfying = maxSatisfying; function maxSatisfying(versions, range, loose) { var max = null; var maxSV = null; try { var rangeObj = new Range(range, loose); } catch (er) { return null; } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, loose) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v; maxSV = new SemVer(max, loose); } } }) return max; } exports.minSatisfying = minSatisfying; function minSatisfying(versions, range, loose) { var min = null; var minSV = null; try { var rangeObj = new Range(range, loose); } catch (er) { return null; } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, loose) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v; minSV = new SemVer(min, loose); } } }) return min; } exports.validRange = validRange; function validRange(range, loose) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, loose).range || '*'; } catch (er) { return null; } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr; function ltr(version, range, loose) { return outside(version, range, '<', loose); } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr; function gtr(version, range, loose) { return outside(version, range, '>', loose); } exports.outside = outside; function outside(version, range, hilo, loose) { version = new SemVer(version, loose); range = new Range(range, loose); var gtfn, ltefn, ltfn, comp, ecomp; switch (hilo) { case '>': gtfn = gt; ltefn = lte; ltfn = lt; comp = '>'; ecomp = '>='; break; case '<': gtfn = lt; ltefn = gte; ltfn = gt; comp = '<'; ecomp = '<='; break; default: throw new TypeError('Must provide a hilo val of "<" or ">"'); } // If it satisifes the range it is not outside if (satisfies(version, range, loose)) { return false; } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i]; var high = null; var low = null; comparators.forEach(function(comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator; low = low || comparator; if (gtfn(comparator.semver, high.semver, loose)) { high = comparator; } else if (ltfn(comparator.semver, low.semver, loose)) { low = comparator; } }); // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false; } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false; } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false; } } return true; } exports.prerelease = prerelease; function prerelease(version, loose) { var parsed = parse(version, loose); return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; } exports.intersects = intersects; function intersects(r1, r2, loose) { r1 = new Range(r1, loose) r2 = new Range(r2, loose) return r1.intersects(r2) } exports.coerce = coerce; function coerce(version) { if (version instanceof SemVer) return version; if (typeof version !== 'string') return null; var match = version.match(re[COERCE]); if (match == null) return null; return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); } }).call(this,require('_process')) },{"_process":507}],539:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer // prototype class for hash functions function Hash (blockSize, finalSize) { this._block = Buffer.alloc(blockSize) this._finalSize = finalSize this._blockSize = blockSize this._len = 0 } Hash.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8' data = Buffer.from(data, enc) } var block = this._block var blockSize = this._blockSize var length = data.length var accum = this._len for (var offset = 0; offset < length;) { var assigned = accum % blockSize var remainder = Math.min(length - offset, blockSize - assigned) for (var i = 0; i < remainder; i++) { block[assigned + i] = data[offset + i] } accum += remainder offset += remainder if ((accum % blockSize) === 0) { this._update(block) } } this._len += length return this } Hash.prototype.digest = function (enc) { var rem = this._len % this._blockSize this._block[rem] = 0x80 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize this._block.fill(0, rem + 1) if (rem >= this._finalSize) { this._update(this._block) this._block.fill(0) } var bits = this._len * 8 // uint32 if (bits <= 0xffffffff) { this._block.writeUInt32BE(bits, this._blockSize - 4) // uint64 } else { var lowBits = (bits & 0xffffffff) >>> 0 var highBits = (bits - lowBits) / 0x100000000 this._block.writeUInt32BE(highBits, this._blockSize - 8) this._block.writeUInt32BE(lowBits, this._blockSize - 4) } this._update(this._block) var hash = this._hash() return enc ? hash.toString(enc) : hash } Hash.prototype._update = function () { throw new Error('_update must be implemented by subclass') } module.exports = Hash },{"safe-buffer":537}],540:[function(require,module,exports){ var exports = module.exports = function SHA (algorithm) { algorithm = algorithm.toLowerCase() var Algorithm = exports[algorithm] if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') return new Algorithm() } exports.sha = require('./sha') exports.sha1 = require('./sha1') exports.sha224 = require('./sha224') exports.sha256 = require('./sha256') exports.sha384 = require('./sha384') exports.sha512 = require('./sha512') },{"./sha":541,"./sha1":542,"./sha224":543,"./sha256":544,"./sha384":545,"./sha512":546}],541:[function(require,module,exports){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined * in FIPS PUB 180-1 * This source code is derived from sha1.js of the same repository. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left * operation was added. */ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 ] var W = new Array(80) function Sha () { this.init() this._w = W Hash.call(this, 64, 56) } inherits(Sha, Hash) Sha.prototype.init = function () { this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 this._e = 0xc3d2e1f0 return this } function rotl5 (num) { return (num << 5) | (num >>> 27) } function rotl30 (num) { return (num << 30) | (num >>> 2) } function ft (s, b, c, d) { if (s === 0) return (b & c) | ((~b) & d) if (s === 2) return (b & c) | (b & d) | (c & d) return b ^ c ^ d } Sha.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] for (var j = 0; j < 80; ++j) { var s = ~~(j / 20) var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 e = d d = c c = rotl30(b) b = a a = t } this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 } Sha.prototype._hash = function () { var H = Buffer.allocUnsafe(20) H.writeInt32BE(this._a | 0, 0) H.writeInt32BE(this._b | 0, 4) H.writeInt32BE(this._c | 0, 8) H.writeInt32BE(this._d | 0, 12) H.writeInt32BE(this._e | 0, 16) return H } module.exports = Sha },{"./hash":539,"inherits":334,"safe-buffer":537}],542:[function(require,module,exports){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 ] var W = new Array(80) function Sha1 () { this.init() this._w = W Hash.call(this, 64, 56) } inherits(Sha1, Hash) Sha1.prototype.init = function () { this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 this._e = 0xc3d2e1f0 return this } function rotl1 (num) { return (num << 1) | (num >>> 31) } function rotl5 (num) { return (num << 5) | (num >>> 27) } function rotl30 (num) { return (num << 30) | (num >>> 2) } function ft (s, b, c, d) { if (s === 0) return (b & c) | ((~b) & d) if (s === 2) return (b & c) | (b & d) | (c & d) return b ^ c ^ d } Sha1.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) for (var j = 0; j < 80; ++j) { var s = ~~(j / 20) var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 e = d d = c c = rotl30(b) b = a a = t } this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 } Sha1.prototype._hash = function () { var H = Buffer.allocUnsafe(20) H.writeInt32BE(this._a | 0, 0) H.writeInt32BE(this._b | 0, 4) H.writeInt32BE(this._c | 0, 8) H.writeInt32BE(this._d | 0, 12) H.writeInt32BE(this._e | 0, 16) return H } module.exports = Sha1 },{"./hash":539,"inherits":334,"safe-buffer":537}],543:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = require('inherits') var Sha256 = require('./sha256') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var W = new Array(64) function Sha224 () { this.init() this._w = W // new Array(64) Hash.call(this, 64, 56) } inherits(Sha224, Sha256) Sha224.prototype.init = function () { this._a = 0xc1059ed8 this._b = 0x367cd507 this._c = 0x3070dd17 this._d = 0xf70e5939 this._e = 0xffc00b31 this._f = 0x68581511 this._g = 0x64f98fa7 this._h = 0xbefa4fa4 return this } Sha224.prototype._hash = function () { var H = Buffer.allocUnsafe(28) H.writeInt32BE(this._a, 0) H.writeInt32BE(this._b, 4) H.writeInt32BE(this._c, 8) H.writeInt32BE(this._d, 12) H.writeInt32BE(this._e, 16) H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) return H } module.exports = Sha224 },{"./hash":539,"./sha256":544,"inherits":334,"safe-buffer":537}],544:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var K = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 ] var W = new Array(64) function Sha256 () { this.init() this._w = W // new Array(64) Hash.call(this, 64, 56) } inherits(Sha256, Hash) Sha256.prototype.init = function () { this._a = 0x6a09e667 this._b = 0xbb67ae85 this._c = 0x3c6ef372 this._d = 0xa54ff53a this._e = 0x510e527f this._f = 0x9b05688c this._g = 0x1f83d9ab this._h = 0x5be0cd19 return this } function ch (x, y, z) { return z ^ (x & (y ^ z)) } function maj (x, y, z) { return (x & y) | (z & (x | y)) } function sigma0 (x) { return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) } function sigma1 (x) { return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) } function gamma0 (x) { return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) } function gamma1 (x) { return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) } Sha256.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 var f = this._f | 0 var g = this._g | 0 var h = this._h | 0 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 for (var j = 0; j < 64; ++j) { var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 var T2 = (sigma0(a) + maj(a, b, c)) | 0 h = g g = f f = e e = (d + T1) | 0 d = c c = b b = a a = (T1 + T2) | 0 } this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 this._f = (f + this._f) | 0 this._g = (g + this._g) | 0 this._h = (h + this._h) | 0 } Sha256.prototype._hash = function () { var H = Buffer.allocUnsafe(32) H.writeInt32BE(this._a, 0) H.writeInt32BE(this._b, 4) H.writeInt32BE(this._c, 8) H.writeInt32BE(this._d, 12) H.writeInt32BE(this._e, 16) H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) H.writeInt32BE(this._h, 28) return H } module.exports = Sha256 },{"./hash":539,"inherits":334,"safe-buffer":537}],545:[function(require,module,exports){ var inherits = require('inherits') var SHA512 = require('./sha512') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var W = new Array(160) function Sha384 () { this.init() this._w = W Hash.call(this, 128, 112) } inherits(Sha384, SHA512) Sha384.prototype.init = function () { this._ah = 0xcbbb9d5d this._bh = 0x629a292a this._ch = 0x9159015a this._dh = 0x152fecd8 this._eh = 0x67332667 this._fh = 0x8eb44a87 this._gh = 0xdb0c2e0d this._hh = 0x47b5481d this._al = 0xc1059ed8 this._bl = 0x367cd507 this._cl = 0x3070dd17 this._dl = 0xf70e5939 this._el = 0xffc00b31 this._fl = 0x68581511 this._gl = 0x64f98fa7 this._hl = 0xbefa4fa4 return this } Sha384.prototype._hash = function () { var H = Buffer.allocUnsafe(48) function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset) H.writeInt32BE(l, offset + 4) } writeInt64BE(this._ah, this._al, 0) writeInt64BE(this._bh, this._bl, 8) writeInt64BE(this._ch, this._cl, 16) writeInt64BE(this._dh, this._dl, 24) writeInt64BE(this._eh, this._el, 32) writeInt64BE(this._fh, this._fl, 40) return H } module.exports = Sha384 },{"./hash":539,"./sha512":546,"inherits":334,"safe-buffer":537}],546:[function(require,module,exports){ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ] var W = new Array(160) function Sha512 () { this.init() this._w = W Hash.call(this, 128, 112) } inherits(Sha512, Hash) Sha512.prototype.init = function () { this._ah = 0x6a09e667 this._bh = 0xbb67ae85 this._ch = 0x3c6ef372 this._dh = 0xa54ff53a this._eh = 0x510e527f this._fh = 0x9b05688c this._gh = 0x1f83d9ab this._hh = 0x5be0cd19 this._al = 0xf3bcc908 this._bl = 0x84caa73b this._cl = 0xfe94f82b this._dl = 0x5f1d36f1 this._el = 0xade682d1 this._fl = 0x2b3e6c1f this._gl = 0xfb41bd6b this._hl = 0x137e2179 return this } function Ch (x, y, z) { return z ^ (x & (y ^ z)) } function maj (x, y, z) { return (x & y) | (z & (x | y)) } function sigma0 (x, xl) { return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) } function sigma1 (x, xl) { return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) } function Gamma0 (x, xl) { return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) } function Gamma0l (x, xl) { return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) } function Gamma1 (x, xl) { return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) } function Gamma1l (x, xl) { return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) } function getCarry (a, b) { return (a >>> 0) < (b >>> 0) ? 1 : 0 } Sha512.prototype._update = function (M) { var W = this._w var ah = this._ah | 0 var bh = this._bh | 0 var ch = this._ch | 0 var dh = this._dh | 0 var eh = this._eh | 0 var fh = this._fh | 0 var gh = this._gh | 0 var hh = this._hh | 0 var al = this._al | 0 var bl = this._bl | 0 var cl = this._cl | 0 var dl = this._dl | 0 var el = this._el | 0 var fl = this._fl | 0 var gl = this._gl | 0 var hl = this._hl | 0 for (var i = 0; i < 32; i += 2) { W[i] = M.readInt32BE(i * 4) W[i + 1] = M.readInt32BE(i * 4 + 4) } for (; i < 160; i += 2) { var xh = W[i - 15 * 2] var xl = W[i - 15 * 2 + 1] var gamma0 = Gamma0(xh, xl) var gamma0l = Gamma0l(xl, xh) xh = W[i - 2 * 2] xl = W[i - 2 * 2 + 1] var gamma1 = Gamma1(xh, xl) var gamma1l = Gamma1l(xl, xh) // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7h = W[i - 7 * 2] var Wi7l = W[i - 7 * 2 + 1] var Wi16h = W[i - 16 * 2] var Wi16l = W[i - 16 * 2 + 1] var Wil = (gamma0l + Wi7l) | 0 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 Wil = (Wil + gamma1l) | 0 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 Wil = (Wil + Wi16l) | 0 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 W[i] = Wih W[i + 1] = Wil } for (var j = 0; j < 160; j += 2) { Wih = W[j] Wil = W[j + 1] var majh = maj(ah, bh, ch) var majl = maj(al, bl, cl) var sigma0h = sigma0(ah, al) var sigma0l = sigma0(al, ah) var sigma1h = sigma1(eh, el) var sigma1l = sigma1(el, eh) // t1 = h + sigma1 + ch + K[j] + W[j] var Kih = K[j] var Kil = K[j + 1] var chh = Ch(eh, fh, gh) var chl = Ch(el, fl, gl) var t1l = (hl + sigma1l) | 0 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 t1l = (t1l + chl) | 0 t1h = (t1h + chh + getCarry(t1l, chl)) | 0 t1l = (t1l + Kil) | 0 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 t1l = (t1l + Wil) | 0 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 // t2 = sigma0 + maj var t2l = (sigma0l + majl) | 0 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 hh = gh hl = gl gh = fh gl = fl fh = eh fl = el el = (dl + t1l) | 0 eh = (dh + t1h + getCarry(el, dl)) | 0 dh = ch dl = cl ch = bh cl = bl bh = ah bl = al al = (t1l + t2l) | 0 ah = (t1h + t2h + getCarry(al, t1l)) | 0 } this._al = (this._al + al) | 0 this._bl = (this._bl + bl) | 0 this._cl = (this._cl + cl) | 0 this._dl = (this._dl + dl) | 0 this._el = (this._el + el) | 0 this._fl = (this._fl + fl) | 0 this._gl = (this._gl + gl) | 0 this._hl = (this._hl + hl) | 0 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 } Sha512.prototype._hash = function () { var H = Buffer.allocUnsafe(64) function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset) H.writeInt32BE(l, offset + 4) } writeInt64BE(this._ah, this._al, 0) writeInt64BE(this._bh, this._bl, 8) writeInt64BE(this._ch, this._cl, 16) writeInt64BE(this._dh, this._dl, 24) writeInt64BE(this._eh, this._el, 32) writeInt64BE(this._fh, this._fl, 40) writeInt64BE(this._gh, this._gl, 48) writeInt64BE(this._hh, this._hl, 56) return H } module.exports = Sha512 },{"./hash":539,"inherits":334,"safe-buffer":537}],547:[function(require,module,exports){ arguments[4][481][0].apply(exports,arguments) },{"dup":481}],548:[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. module.exports = Stream; var EE = require('events').EventEmitter; var inherits = require('inherits'); inherits(Stream, EE); Stream.Readable = require('readable-stream/readable.js'); Stream.Writable = require('readable-stream/writable.js'); Stream.Duplex = require('readable-stream/duplex.js'); Stream.Transform = require('readable-stream/transform.js'); Stream.PassThrough = require('readable-stream/passthrough.js'); // Backwards-compat with node 0.4.x Stream.Stream = Stream; // old-style streams. Note that the pipe method (the only relevant // part of this class) is overridden in the Readable class. function Stream() { EE.call(this); } Stream.prototype.pipe = function(dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; if (typeof dest.destroy === 'function') dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (EE.listenerCount(this, 'error') === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; },{"events":316,"inherits":334,"readable-stream/duplex.js":520,"readable-stream/passthrough.js":529,"readable-stream/readable.js":530,"readable-stream/transform.js":531,"readable-stream/writable.js":532}],549:[function(require,module,exports){ 'use strict'; var Buffer = require('safe-buffer').Buffer; var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return -1; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'.repeat(p); } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'.repeat(p + 1); } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'.repeat(p + 2); } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character for each buffered byte of a (partial) // character needs to be added to the output. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":537}],550:[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" } } },{}],551:[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} },{}],552:[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 } ] } } },{}],553:[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 } },{}],554:[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":556,"./metrics.json":551,"./prefixMetadata.json":552,"./prefixes.json":553,"./unitMetadata.json":555}],555:[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" ] } } },{}],556:[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; }; } } },{}],557:[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":550,"./generated/ucum-parser.js":554,"./generated/unitMetadata.json":555,"./lib/helpers.js":556}],558:[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. 'use strict'; var punycode = require('punycode'); var util = require('./util'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; },{"./util":559,"punycode":514,"querystring":517}],559:[function(require,module,exports){ 'use strict'; module.exports = { isString: function(arg) { return typeof(arg) === 'string'; }, isObject: function(arg) { return typeof(arg) === 'object' && arg !== null; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; } }; },{}],560:[function(require,module,exports){ (function (global){ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],561:[function(require,module,exports){ arguments[4][334][0].apply(exports,arguments) },{"dup":334}],562:[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'; } },{}],563:[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":562,"_process":507,"inherits":561}],564:[function(require,module,exports){ var indexOf = require('indexof'); var Object_keys = function (obj) { if (Object.keys) return Object.keys(obj) else { var res = []; for (var key in obj) res.push(key) return res; } }; var forEach = function (xs, fn) { if (xs.forEach) return xs.forEach(fn) else for (var i = 0; i < xs.length; i++) { fn(xs[i], i, xs); } }; var defineProp = (function() { try { Object.defineProperty({}, '_', {}); return function(obj, name, value) { Object.defineProperty(obj, name, { writable: true, enumerable: false, configurable: true, value: value }) }; } catch(e) { return function(obj, name, value) { obj[name] = value; }; } }()); var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', 'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', 'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; function Context() {} Context.prototype = {}; var Script = exports.Script = function NodeScript (code) { if (!(this instanceof Script)) return new Script(code); this.code = code; }; Script.prototype.runInContext = function (context) { if (!(context instanceof Context)) { throw new TypeError("needs a 'context' argument."); } var iframe = document.createElement('iframe'); if (!iframe.style) iframe.style = {}; iframe.style.display = 'none'; document.body.appendChild(iframe); var win = iframe.contentWindow; var wEval = win.eval, wExecScript = win.execScript; if (!wEval && wExecScript) { // win.eval() magically appears when this is called in IE: wExecScript.call(win, 'null'); wEval = win.eval; } forEach(Object_keys(context), function (key) { win[key] = context[key]; }); forEach(globals, function (key) { if (context[key]) { win[key] = context[key]; } }); var winKeys = Object_keys(win); var res = wEval.call(win, this.code); forEach(Object_keys(win), function (key) { // Avoid copying circular objects like `top` and `window` by only // updating existing context properties or new properties in the `win` // that was only introduced after the eval. if (key in context || indexOf(winKeys, key) === -1) { context[key] = win[key]; } }); forEach(globals, function (key) { if (!(key in context)) { defineProp(context, key, win[key]); } }); document.body.removeChild(iframe); return res; }; Script.prototype.runInThisContext = function () { return eval(this.code); // maybe... }; Script.prototype.runInNewContext = function (context) { var ctx = Script.createContext(context); var res = this.runInContext(ctx); forEach(Object_keys(ctx), function (key) { context[key] = ctx[key]; }); return res; }; forEach(Object_keys(Script.prototype), function (name) { exports[name] = Script[name] = function (code) { var s = Script(code); return s[name].apply(s, [].slice.call(arguments, 1)); }; }); exports.createScript = function (code) { return exports.Script(code); }; exports.createContext = Script.createContext = function (context) { var copy = new Context(); if(typeof context === 'object') { forEach(Object_keys(context), function (key) { copy[key] = context[key]; }); } return copy; }; },{"indexof":333}]},{},[73]);