Repository: aws-samples/aws-lambda-zombie-workshop Branch: master Commit: 7da7ba18c3e7 Files: 60 Total size: 4.0 MB Directory structure: gitextract_f0w1g8j0/ ├── CHANGELOG.md ├── ChatServiceLambdaFunctions/ │ ├── ZombieGetMessages.js │ └── ZombiePostMessage.js ├── CloudFormation/ │ ├── CreateZombieWorkshop.json │ └── CustomResources/ │ ├── APIGatewayCreateScript/ │ │ └── src/ │ │ ├── ApiGatewayCreate.js │ │ ├── ApiGatewayDelete.js │ │ ├── LambdaHandler.js │ │ ├── ZombieWebsiteConfigUpdate.js │ │ └── cloudformationsender.js │ ├── IamUsers/ │ │ ├── IamLambdaHandler.js │ │ ├── cloudformationsender.js │ │ ├── create.js │ │ └── delete.js │ ├── S3GetFilesFunction/ │ │ └── S3GetFilesFunction.js │ ├── cognito/ │ │ └── cognito.js │ └── cognitoTriggerBuild/ │ └── index.js ├── ElasticSearchLambda/ │ └── ZombieWorkshopSearchIndexing.js ├── LICENSE ├── NOTICE ├── README.md ├── S3WebApp/ │ └── S3/ │ ├── app.js │ ├── assets/ │ │ ├── css/ │ │ │ └── zombie.css │ │ └── js/ │ │ ├── aws-cognito-sdk.js │ │ ├── constants.js │ │ ├── jsbn.js │ │ ├── jsbn2.js │ │ └── sjcl.js │ ├── factories/ │ │ └── utils.js │ ├── index.html │ ├── lib/ │ │ ├── CryptoJS/ │ │ │ ├── components/ │ │ │ │ ├── enc-base64.js │ │ │ │ └── hmac.js │ │ │ └── rollups/ │ │ │ ├── hmac-sha256.js │ │ │ └── sha256.js │ │ ├── apiGatewayCore/ │ │ │ ├── apiGatewayClient.js │ │ │ ├── sigV4Client.js │ │ │ ├── simpleHttpClient.js │ │ │ └── utils.js │ │ ├── axios/ │ │ │ └── dist/ │ │ │ └── axios.standalone.js │ │ └── url-template/ │ │ └── url-template.js │ └── modules/ │ ├── chat/ │ │ ├── chat.html │ │ ├── chat.js │ │ ├── chatMessages.html │ │ ├── chatMessages.js │ │ ├── chatPanel.html │ │ ├── chatPanel.js │ │ ├── talkersPanel.html │ │ └── talkersPanel.js │ ├── confirm/ │ │ ├── confirm.html │ │ └── confirm.js │ ├── index.html │ ├── signin/ │ │ ├── signin.html │ │ └── signin.js │ └── signup/ │ ├── signup.html │ └── signup.js ├── Slack/ │ └── SlackService.js ├── Twilio/ │ └── TwilioProcessing.js ├── cognitoLambdaTrigger/ │ └── index.js └── zombieSensor/ ├── lambda/ │ └── exampleSNSFunction.js └── zombieIntelEdisonCode/ ├── main.js └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: CHANGELOG.md ================================================ ========= CHANGELOG ========= 3.0.0 ===== * Introduces Cognito User Pools for authentication along with newer looking UI. * Adds API Gateway IAM Authorization * Provides support for workshop to run in all regions that are currently supporting Lambda and API Gateway services. 2.0.0 ===== * Introduces multi-region stack support for workshop to run in any of the 5 existing regions that have API Gateway and Lambda. * Solves hardcoded attribute dependencies, allowing for multiple stacks to run simultaneously in the same AWS account. Resources are created with stack name prepended to the resource names. * Removes caching from API Gateway stage to reduce costs for long running stacks. 1.0.0 ========== * All commits prior to release 2.0.0 are considered a part of v1.0.0 release. * Initial release on Github. * Provides baseline zombie survivor chat application via CloudFormation stack, Lambda functions, DynamoDB tables, and API Gateway resources. ================================================ FILE: ChatServiceLambdaFunctions/ZombieGetMessages.js ================================================ console.log('Loading function'); var aws = require('aws-sdk'); var ddb; var theContext; function dynamoCallback(err, response) { if (err) { console.log('error' + err, err.stack); // an error occurred theContext.fail(err); } else { console.log('result: ' + JSON.stringify(response)) // successful response theContext.succeed(response); } } function init(context) { if(!ddb) { var stackName = context.functionName.split('-z0mb1es-')[0]; var stackRegion = context.functionName.split('-GetMessagesFromDynamoDB-')[1]; ddb = new aws.DynamoDB({ region: stackRegion, params: { TableName: stackName + "-messages" } }); } } exports.handler = function(event, context) { init(context); theContext = context; var params = { "KeyConditions": { "channel": { "AttributeValueList": [{ "S": "default" }], "ComparisonOperator": "EQ" } }, "Limit": 20, "ScanIndexForward":false } console.log("Querying DynamoDB"); var response = ddb.query(params, dynamoCallback); } ================================================ FILE: ChatServiceLambdaFunctions/ZombiePostMessage.js ================================================ // Processes incoming messages for Zombie chat service var aws = require('aws-sdk'); var ddb; var querystring = require('querystring'); var theContext; var message; var from; var numMedia; var mediaURL; var timestamp; var channel = 'default'; exports.handler = function(event, context) { init(context); theContext = context; if(event.message == null || event.message == 'null' || event.name == null || event.name == 'null') { return context.fail("Message and Name cannot be null"); } else { message = event.message; from = event.name; } if (event.timestamp == null || event.timestamp == 'null') { event.timestamp = "" + new Date().getTime(); timestamp = event.timestamp; } /** * For Debubugging input params to the lambda function console.log('Message: ' + message); console.log('Sender: ' + from); console.log('Channel: ' + channel); */ var DDBparams = { "Item": { "channel":{"S":channel}, "message":{"S":message}, "timestamp":{"N":timestamp}, "name":{"S":from} } }; dynamoPut(DDBparams); }; function init(context) { if(!ddb) { console.log("Initializing DynamoDB client."); var stackName = context.functionName.split('-z0mb1es-')[0]; var stackRegion = context.functionName.split('-WriteMessagesToDynamoDB-')[1]; ddb = new aws.DynamoDB({ region: stackRegion, params: { TableName: stackName + "-messages" } }); } } function dynamoPut(params){ console.log("Putting item into DynamoDB"); ddb.putItem(params, dynamoCallback); } function dynamoCallback(err, response) { if (err) { console.log('error' + err, err.stack); // an error occurred return theContext.fail("There was an error."); } else { console.log('Success: ' + '{Sender: ' + from + ', ' + 'Message: ' + message + '}'); return theContext.succeed(); } } ================================================ FILE: CloudFormation/CreateZombieWorkshop.json ================================================ { "AWSTemplateFormatVersion": "2010-09-09", "Description": "AWS CloudFormation template to launch resources for a serverless group chat. This was designed for the AWS Zombie Apocalypse Workshop: Building Serverless Microservices", "Parameters": { "NumberOfTeammates": { "Description": "How many teammates do you have? Input that here, one for each of your teammates. Don't include yourself", "Type": "Number", "MinValue": "0", "MaxValue": "10", "Default": "0" } }, "Mappings": { "AllowedRegions": { "us-west-2": { "S3Endpoint": "https://s3-us-west-2", "S3ContentsBucket": "aws-zombie-workshop-us-west-2", "CognitoRegion": "us-west-2" }, "us-east-1": { "S3Endpoint": "https://s3", "S3ContentsBucket": "aws-zombie-workshop-us-east-1", "CognitoRegion": "us-east-1" }, "us-east-2": { "S3Endpoint": "https://s3-us-east-2", "S3ContentsBucket": "aws-zombie-workshop-us-east-2", "CognitoRegion": "us-east-2" }, "eu-west-1": { "S3Endpoint": "https://s3-eu-west-1", "S3ContentsBucket": "aws-zombie-workshop-eu-west-1", "CognitoRegion": "eu-west-1" }, "eu-central-1": { "S3Endpoint": "https://s3-eu-central-1", "S3ContentsBucket": "aws-zombie-workshop-eu-central-1", "CognitoRegion": "eu-central-1" }, "ap-northeast-1": { "S3Endpoint": "https://s3-ap-northeast-1", "S3ContentsBucket": "aws-zombie-workshop-ap-northeast-1", "CognitoRegion": "ap-northeast-1" }, "ap-northeast-2": { "S3Endpoint": "https://s3-ap-northeast-2", "S3ContentsBucket": "aws-zombie-workshop-ap-northeast-2", "CognitoRegion": "ap-northeast-2" }, "ap-southeast-1": { "S3Endpoint": "https://s3-ap-southeast-1", "S3ContentsBucket": "aws-zombie-workshop-ap-southeast-1", "CognitoRegion": "us-east-1" }, "ap-southeast-2": { "S3Endpoint": "https://s3-ap-southeast-2", "S3ContentsBucket": "aws-zombie-workshop-ap-southeast-2", "CognitoRegion": "us-east-1" } } }, "Conditions": { "CreateIamResources": { "Fn::Not": [{ "Fn::Equals": [ {"Ref": "NumberOfTeammates"}, "0" ] }] } }, "Resources": { "ZombieLabLambdaRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com", "apigateway.amazonaws.com"], "Federated": "cognito-identity.amazonaws.com"}, "Action": ["sts:AssumeRole", "sts:AssumeRoleWithWebIdentity"] }] }, "Path": "/", "Policies": [{ "PolicyName": "root", "PolicyDocument": { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": ["cloudformation:*"], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["lambda:*"], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["execute-api:*"], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["dynamodb:*"], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["kinesis:*"], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["es:*"], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["s3:*"], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["apigateway:*"], "Resource": ["*", "arn:aws:apigateway:*::/*"] }, { "Effect": "Allow", "Action": [ "mobileanalytics:PutEvents", "cognito-sync:*", "cognito-identity:*", "cognito-idp:*" ], "Resource": ["*"] }, { "Effect": "Allow", "Action": ["iam:*"], "Resource": ["*"] }] } }] } }, "IamUserPolicy": { "Type": "AWS::IAM::Policy", "Condition": "CreateIamResources", "Properties": { "PolicyName": "ZombieLabUserPolicy", "PolicyDocument": { "Statement": [ { "Effect": "Allow", "Action": ["*"], "Resource": ["*"] }, { "Effect": "Deny", "Action": ["aws-portal:*"], "Resource": ["*"] } ] }, "Groups": [{ "Fn::GetAtt": ["CreateIAMUsers", "IamGroup"]}] }, "DependsOn": ["ZombieLabLambdaRole","CreateIAMUsers"] }, "APIinvokePolicy": { "Type": "AWS::IAM::Policy", "Properties": { "Roles": [{ "Ref" : "ZombieLabLambdaRole" }], "PolicyName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "apiinvokepolicy"]]}, "PolicyDocument": { "Statement": [ { "Effect": "Allow", "Action": ["execute-api:invoke"], "Resource": [ { "Fn::Join" : ["", ["arn:aws:execute-api:", { "Ref" : "AWS::Region" }, ":", { "Ref" : "AWS::AccountId" }, ":", { "Fn::GetAtt": ["CreateAPIGateway", "RestApiID"]}, "/ZombieWorkshopStage/zombie/POST/message" ]]}, { "Fn::Join" : ["", ["arn:aws:execute-api:", { "Ref" : "AWS::Region" }, ":", { "Ref" : "AWS::AccountId" }, ":", { "Fn::GetAtt": ["CreateAPIGateway", "RestApiID"]}, "/ZombieWorkshopStage/zombie/GET/message" ]]}, { "Fn::Join" : ["", ["arn:aws:execute-api:", { "Ref" : "AWS::Region" }, ":", { "Ref" : "AWS::AccountId" }, ":", { "Fn::GetAtt": ["CreateAPIGateway", "RestApiID"]}, "/ZombieWorkshopStage/zombie/POST/talkers" ]]}, { "Fn::Join" : ["", ["arn:aws:execute-api:", { "Ref" : "AWS::Region" }, ":", { "Ref" : "AWS::AccountId" }, ":", { "Fn::GetAtt": ["CreateAPIGateway", "RestApiID"]}, "/ZombieWorkshopStage/zombie/GET/talkers" ]]} ] } ] } }, "DependsOn": ["ZombieLabLambdaRole", "CreateAPIGateway"] }, "S3BucketPolicy": { "Type": "AWS::S3::BucketPolicy", "Properties": { "Bucket": {"Ref" : "S3BucketForWebsiteContent"}, "PolicyDocument": { "Statement":[{ "Action":["s3:GetObject"], "Effect":"Allow", "Resource": { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "S3BucketForWebsiteContent" } , "/*" ]]}, "Principal": "*" }] } } }, "MessagesDynamoDBTable": { "Type": "AWS::DynamoDB::Table", "Properties": { "TableName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "messages"]]}, "AttributeDefinitions": [ { "AttributeName": "channel", "AttributeType": "S" }, { "AttributeName": "timestamp", "AttributeType": "N" } ], "KeySchema": [ {"AttributeName": "channel", "KeyType": "HASH"}, {"AttributeName": "timestamp", "KeyType": "RANGE"} ], "ProvisionedThroughput": { "ReadCapacityUnits": 10, "WriteCapacityUnits": 10 } } }, "TalkersDynamoDBTable": { "Type": "AWS::DynamoDB::Table", "Properties": { "TableName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "talkers"]]}, "AttributeDefinitions": [ { "AttributeName": "channel", "AttributeType": "S" }, { "AttributeName": "talktime", "AttributeType": "N" } ], "KeySchema": [ {"AttributeName": "channel", "KeyType": "HASH"}, {"AttributeName": "talktime", "KeyType": "RANGE"} ], "ProvisionedThroughput": { "ReadCapacityUnits": 10, "WriteCapacityUnits": 10 } } }, "UsersDynamoDBTable": { "Type": "AWS::DynamoDB::Table", "Properties": { "TableName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "users"]]}, "AttributeDefinitions": [ { "AttributeName": "userid", "AttributeType": "S" }, { "AttributeName": "phone", "AttributeType": "S" }, { "AttributeName": "slackuser", "AttributeType": "S" }, { "AttributeName": "slackteamdomain", "AttributeType": "S" } ], "KeySchema": [ { "AttributeName": "userid", "KeyType": "HASH" } ], "ProvisionedThroughput": { "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 }, "GlobalSecondaryIndexes": [ { "IndexName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "phoneindex"]]}, "KeySchema": [ { "AttributeName": "phone", "KeyType": "HASH" } ], "Projection": { "NonKeyAttributes": ["confirmed", "camp"], "ProjectionType": "INCLUDE" }, "ProvisionedThroughput": { "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 } }, { "IndexName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "slackindex"]]}, "KeySchema": [ { "AttributeName": "slackuser", "KeyType": "HASH" }, { "AttributeName": "slackteamdomain", "KeyType": "RANGE" } ], "Projection": { "NonKeyAttributes": ["confirmed", "camp"], "ProjectionType": "INCLUDE" }, "ProvisionedThroughput": { "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 } } ] } }, "S3BucketForWebsiteContent": { "Type": "AWS::S3::Bucket", "Properties": { "AccessControl": "PublicRead", "WebsiteConfiguration": { "IndexDocument": "index.html", "ErrorDocument": "error.html" } }, "DependsOn" : "ZombieLabLambdaRole" }, "PutWebsiteFilesInS3": { "Type": "Custom::PutWebsiteFilesInS3", "Properties": { "ServiceToken": { "Fn::GetAtt" : ["S3GetFilesFunction", "Arn"] }, "StackName": { "Ref": "AWS::StackName" }, "BucketName": { "Fn::FindInMap" : [ "AllowedRegions", { "Ref" : "AWS::Region" }, "S3ContentsBucket"]}, "WebsiteBucketCreatedEarlier": { "Ref" : "S3BucketForWebsiteContent" }, "S3Region": { "Ref" : "AWS::Region" } }, "DependsOn": [ "ZombieLabLambdaRole", "S3BucketForWebsiteContent" ] }, "S3GetFilesFunction": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "S3GetFilesFunction.handler", "Role": { "Fn::GetAtt": ["ZombieLabLambdaRole", "Arn"] }, "Code": { "S3Bucket": { "Fn::FindInMap" : [ "AllowedRegions", { "Ref" : "AWS::Region" }, "S3ContentsBucket"]}, "S3Key": "S3GetFilesFunction.zip" }, "Runtime": "nodejs4.3", "Timeout": "120" }, "DependsOn": [ "ZombieLabLambdaRole", "S3BucketForWebsiteContent" ] }, "CognitoTriggerBuild": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "index.handler", "Role": { "Fn::GetAtt": ["ZombieLabLambdaRole", "Arn"] }, "Code": { "S3Bucket": { "Ref" : "S3BucketForWebsiteContent" }, "S3Key": "cognitoTriggerBuild.zip" }, "Runtime": "nodejs4.3", "Timeout": "120" }, "DependsOn": [ "ZombieLabLambdaRole", "S3BucketForWebsiteContent", "PutWebsiteFilesInS3" ] }, "CreateCognitoTrigger": { "Type": "Custom::CreateCognitoTrigger", "Properties": { "ServiceToken": { "Fn::GetAtt": ["CognitoTriggerBuild", "Arn"] }, "region": { "Ref": "AWS::Region" }, "CognitoRegion": { "Fn::FindInMap" : [ "AllowedRegions", { "Ref" : "AWS::Region" }, "CognitoRegion"]}, "LambdaFunctionBucket": { "Fn::FindInMap" : [ "AllowedRegions", { "Ref" : "AWS::Region" }, "S3ContentsBucket"]}, "StackName": { "Ref": "AWS::StackName" }, "IamRole": { "Fn::GetAtt": ["ZombieLabLambdaRole", "Arn"] } }, "DependsOn": [ "S3BucketForWebsiteContent", "ZombieLabLambdaRole", "PutWebsiteFilesInS3", "WriteMessagesToDynamoDB", "GetMessagesFromDynamoDB", "MessagesDynamoDBTable" ] }, "CreateAPIGateway": { "Type": "Custom::CreateAPIGateway", "Properties": { "ServiceToken": { "Fn::GetAtt": ["APIGatewayFunction", "Arn"] }, "postmessagelambdaapiuri": { "Fn::Join": [ "", [ "arn:aws:apigateway:", { "Ref": "AWS::Region" }, ":lambda:path/2015-03-31/functions/", { "Fn::GetAtt": ["WriteMessagesToDynamoDB", "Arn"] }, "/invocations" ] ] }, "getmessagelambdaapiuri": { "Fn::Join": [ "", [ "arn:aws:apigateway:", { "Ref": "AWS::Region" }, ":lambda:path/2015-03-31/functions/", { "Fn::GetAtt": ["GetMessagesFromDynamoDB", "Arn"] }, "/invocations" ] ] }, "region": { "Ref": "AWS::Region" }, "iamrole": { "Fn::GetAtt": ["ZombieLabLambdaRole", "Arn"] }, "s3bucket": { "Ref": "S3BucketForWebsiteContent" }, "s3key": "S3/assets/js/constants.js", "apiname": { "Fn::Join": [ "", [ { "Ref": "AWS::StackName" }, "- Zombie Workshop API Gateway" ] ] } }, "DependsOn": [ "S3BucketForWebsiteContent", "ZombieLabLambdaRole", "PutWebsiteFilesInS3", "WriteMessagesToDynamoDB", "GetMessagesFromDynamoDB", "MessagesDynamoDBTable" ] }, "APIGatewayFunction": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "LambdaHandler.handleGatewayEvent", "Role": { "Fn::GetAtt" : ["ZombieLabLambdaRole", "Arn"] }, "Code": { "S3Bucket": { "Ref": "S3BucketForWebsiteContent" }, "S3Key": "WK305_Gateway.zip" }, "Runtime": "nodejs4.3", "Timeout": "300", "MemorySize": "1536" }, "DependsOn": [ "MessagesDynamoDBTable", "ZombieLabLambdaRole", "S3BucketForWebsiteContent", "PutWebsiteFilesInS3" ] }, "CognitoPoolsFunction": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "cognito.handler", "Role": { "Fn::GetAtt" : ["ZombieLabLambdaRole", "Arn"] }, "Code": { "S3Bucket": { "Ref": "S3BucketForWebsiteContent" }, "S3Key": "cognito.zip" }, "Runtime": "nodejs4.3", "Timeout": "300", "MemorySize": "1536" }, "DependsOn": [ "ZombieLabLambdaRole", "S3BucketForWebsiteContent", "PutWebsiteFilesInS3", "CreateAPIGateway" ] }, "CreateCognitoPools": { "Type": "Custom::CognitoPoolsFunction", "Properties": { "ServiceToken": { "Fn::GetAtt": ["CognitoPoolsFunction", "Arn"] }, "region": { "Ref": "AWS::Region" }, "CognitoRegion": { "Fn::FindInMap" : [ "AllowedRegions", { "Ref" : "AWS::Region" }, "CognitoRegion"]}, "cognitoRoleARN": { "Fn::GetAtt": ["ZombieLabLambdaRole", "Arn"] }, "bucket": { "Ref": "S3BucketForWebsiteContent" }, "constantsFile": "S3/assets/js/constants.js", "StackName": { "Ref": "AWS::StackName" } }, "DependsOn": [ "S3BucketForWebsiteContent", "ZombieLabLambdaRole", "PutWebsiteFilesInS3", "WriteMessagesToDynamoDB", "GetMessagesFromDynamoDB", "MessagesDynamoDBTable" ] }, "WriteMessagesToDynamoDB": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "ZombiePostMessage.handler", "Role": { "Fn::GetAtt" : ["ZombieLabLambdaRole", "Arn"] }, "FunctionName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "z0mb1es", "WriteMessagesToDynamoDB", {"Ref": "AWS::Region"}]]}, "Code": { "S3Bucket": { "Ref" : "S3BucketForWebsiteContent" }, "S3Key": "ZombiePostMessage.zip" }, "Runtime": "nodejs4.3", "Timeout": "60" }, "DependsOn": [ "MessagesDynamoDBTable", "S3BucketForWebsiteContent", "PutWebsiteFilesInS3" ] }, "GetMessagesFromDynamoDB": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "ZombieGetMessages.handler", "Role": { "Fn::GetAtt" : ["ZombieLabLambdaRole", "Arn"] }, "FunctionName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "z0mb1es", "GetMessagesFromDynamoDB", {"Ref": "AWS::Region"}]]}, "Code": { "S3Bucket": { "Ref" : "S3BucketForWebsiteContent" }, "S3Key": "ZombieGetMessages.zip" }, "Runtime": "nodejs4.3", "Timeout": "60" }, "DependsOn" : [ "MessagesDynamoDBTable", "S3BucketForWebsiteContent", "PutWebsiteFilesInS3" ] }, "WriteTalkersToDynamoDB": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "index.handler", "Role": { "Fn::GetAtt" : ["ZombieLabLambdaRole", "Arn"] }, "FunctionName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "z0mb1es", "WriteTalkersToDynamoDB", {"Ref": "AWS::Region"}]]}, "Code": { "ZipFile": { "Fn::Join": ["", [ "console.log('Loading function');\n", "\n", "var AWS = require('aws-sdk');\n", "\n", "var docClient = new AWS.DynamoDB.DocumentClient({\n", " region: '", {"Ref": "AWS::Region"}, "',\n", "});\n", "\n", "exports.handler = function(event, context) {\n", " console.log('Received event:', JSON.stringify(event, null, 2));\n", "\n", " if (event.name == null) {\n", " context.fail(new Error('name cannot be null: ' + JSON.stringify(event, null, 2)));\n", " }\n", "\n", " var params = {\n", " TableName: '", {"Ref": "AWS::StackName"}, "-talkers',\n", " Item: {\n", " channel: 'default',\n", " talktime: Date.now(),\n", " name: event.name\n", " }\n", " };\n", "\n", " docClient.put(params, function(err, data) {\n", " if (err) {\n", " console.log('DDB Err:' + err);\n", " context.fail(new Error('DynamoDB Error: ' + err));\n", " } else {\n", " console.log(data);\n", " context.done(null, {Status: 'Success'});\n", " }\n", "\n", " });\n", "\n", "};\n" ]]} }, "Runtime": "nodejs4.3", "Timeout": "10" }, "DependsOn" : ["TalkersDynamoDBTable","ZombieLabLambdaRole"] }, "GetTalkersFromDynamoDB": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "index.handler", "Role": { "Fn::GetAtt" : ["ZombieLabLambdaRole", "Arn"] }, "FunctionName": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "z0mb1es", "GetTalkersFromDynamoDB", {"Ref": "AWS::Region"}]]}, "Code": { "ZipFile": { "Fn::Join": ["", [ "console.log('Loading function');\n", "\n", "var AWS = require('aws-sdk');\n", "\n", "var docClient = new AWS.DynamoDB.DocumentClient({\n", " region: '", {"Ref": "AWS::Region"}, "',\n", "});\n", "\n", "exports.handler = function(event, context) {\n", " console.log('Received event:', JSON.stringify(event, null, 2));\n", "\n", " var params = {\n", " TableName: '", {"Ref": "AWS::StackName"}, "-talkers',\n", " KeyConditionExpression: 'channel = :hkey and talktime > :rkey',\n", " ExpressionAttributeValues: {\n", " ':hkey': 'default',\n", " ':rkey': (Date.now() - 2000)\n", " },\n", " ConsistentRead: true\n", " };\n", "\n", " docClient.query(params, function(err, data) {\n", " if (err) {\n", " console.log('DDB Err:' + err);\n", " context.fail(new Error('DynamoDB Error: ' + err));\n", " } else {\n", " console.log((Date.now() - 2000));\n", " console.log(data);\n", " Talkers = [];\n", " Pushed = {};\n", " data.Items.forEach(function(talker, index, array) {\n", " if (Pushed.hasOwnProperty(talker.name) == false) {\n", " Talkers.push(talker.name);\n", " Pushed[talker.name] = true;\n", " }\n", "\n", " });\n", " context.done(null, {\n", " Talkers: Talkers\n", " });\n", " }\n", "\n", " });\n", "};\n" ]]} }, "Runtime": "nodejs4.3", "Timeout": "10" }, "DependsOn" : ["TalkersDynamoDBTable", "ZombieLabLambdaRole"] }, "CreateIAMUsers": { "Type": "Custom::CreateIAMUsers", "Condition": "CreateIamResources", "Properties": { "ServiceToken": { "Fn::GetAtt": ["IamUsersFunction", "Arn"] }, "StackName": { "Ref": "AWS::StackName" }, "region": { "Ref": "AWS::Region" }, "IamUsers": { "Ref": "NumberOfTeammates"} }, "DependsOn": [ "ZombieLabLambdaRole" ] }, "IamUsersFunction": { "Type": "AWS::Lambda::Function", "Condition": "CreateIamResources", "Properties": { "Handler": "IamLambdaHandler.handleIAM", "Role": { "Fn::GetAtt": ["ZombieLabLambdaRole", "Arn"] }, "Code": { "S3Bucket": { "Ref" : "S3BucketForWebsiteContent" }, "S3Key": "IamUsers.zip" }, "Runtime": "nodejs4.3", "Timeout": "60" }, "DependsOn": [ "ZombieLabLambdaRole", "S3BucketForWebsiteContent", "PutWebsiteFilesInS3", "S3GetFilesFunction" ] } }, "Outputs": { "MyStackRegion": { "Value": { "Ref": "AWS::Region" }, "Description": "The region where the stack was created." }, "MyChatRoomURL": { "Value": { "Fn::Join": [ "", [ { "Fn::FindInMap" : [ "AllowedRegions", { "Ref" : "AWS::Region" }, "S3Endpoint"]}, ".amazonaws.com/", { "Ref": "S3BucketForWebsiteContent" }, "/S3/index.html" ] ] }, "Description": "The URL to access your newly created chat." }, "DynamoDBMessagesTableName": { "Value": { "Ref": "MessagesDynamoDBTable" }, "Description": "Table name of the newly created Messages DynamoDB table that will contain chat messages." }, "DynamoDBTalkersTableName": { "Value": { "Ref": "TalkersDynamoDBTable" }, "Description": "Table name of the newly created Talkers DynamoDB table that will contain metadata about survivors who are typing." }, "DynamoDBUsersTableName": { "Value": { "Ref": "UsersDynamoDBTable" }, "Description": "Table name of the newly created Users DynamoDB table that will contain records about registered users for the app." }, "DynamoDBUsersSlackIndex": { "Value": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "slackindex"]]}, "Description": "Name of the Slack index associated with the newly created Users DynamoDB table." }, "DynamoDBUsersPhoneIndex": { "Value": { "Fn::Join": ["-", [{"Ref": "AWS::StackName"}, "phoneindex"]]}, "Description": "Name of the Phone index associated with the newly created Users DynamoDB table." }, "Bucket": { "Value": { "Ref": "S3BucketForWebsiteContent" }, "Description": "The S3 bucket which contains the chat web app contents." }, "DynamoDBWriteMessagesLambdaFunction": { "Value": { "Ref": "WriteMessagesToDynamoDB" }, "Description": "This Lambda function is used for writing chat messages to the Messages table." }, "DynamoDBGetMessagesLambdaFunction": { "Value": { "Ref": "GetMessagesFromDynamoDB" }, "Description": "This Lambda function is used for getting chat messages from the Messages table." }, "WriteTalkersToDynamoDBLambdaFunction": { "Value": { "Ref": "WriteTalkersToDynamoDB" }, "Description": "This Lambda function is used for writing talkers to the Talkers table." }, "GetTalkersFromDynamoDBLambdaFunction": { "Value": { "Ref": "GetTalkersFromDynamoDB" }, "Description": "This Lambda function is used for getting talkers from the Talkers table." }, "DynamoDBWriteMessagesARN": { "Value": { "Fn::GetAtt": ["WriteMessagesToDynamoDB", "Arn"] }, "Description": "The ARN for the Write Messages Lambda function" }, "DynamoDBGetMessageARN": { "Value": { "Fn::GetAtt": ["GetMessagesFromDynamoDB", "Arn"] }, "Description": "The ARN for the Get Messages Lambda function" }, "ApiID": { "Value": { "Fn::GetAtt": ["CreateAPIGateway", "RestApiID"]}, "Description": "The unique ID for your API Gateway API." }, "IamUsersPassword": { "Value": { "Fn::GetAtt": ["CreateIAMUsers", "IamPassword"]}, "Description": "The password for your IAM users", "Condition": "CreateIamResources" }, "LoginURL": { "Value": { "Fn::Join": [ "", ["https://", {"Ref": "AWS::AccountId"}, ".signin.aws.amazon.com/console"] ]}, "Description": "The URL to login to the AWS Management console for the IAM users.", "Condition": "CreateIamResources" }, "IamUsersCreated": { "Value": { "Fn::GetAtt": ["CreateIAMUsers", "Users"]}, "Description": "The IAM users created to be used for group work", "Condition": "CreateIamResources" }, "IamGroupCreated": { "Value": { "Fn::GetAtt": ["CreateIAMUsers", "IamGroup"]}, "Description": "The IAM group created for the users", "Condition": "CreateIamResources" }, "IamUsersLambdaFunction": { "Value": { "Ref": "IamUsersFunction" }, "Description": "This Lambda function is used for creating additional IAM users in th environment.", "Condition": "CreateIamResources" }, "IamUsersFunctionARN": { "Value": { "Fn::GetAtt": ["IamUsersFunction", "Arn"] }, "Description": "The ARN for the Lambda function that creates additional IAM users.", "Condition": "CreateIamResources" }, "BucketCopiedContentsFrom": { "Value": { "Fn::FindInMap" : [ "AllowedRegions", { "Ref" : "AWS::Region" }, "S3ContentsBucket"]}, "Description": "This is the local region AWS bucket where your files were copied from." } } } ================================================ FILE: CloudFormation/CustomResources/APIGatewayCreateScript/src/ApiGatewayCreate.js ================================================ console.log('Starting create API Gateway script'); var AWS = require('aws-sdk'); var async = require('async'); var apigateway; var restAPIId = ''; var currentResourceId = ''; var zombieResourceId = ''; var talkerResourceId = ''; var twilioResourceId = ''; var getmessagearn; var postmessagearn; var iamRole; var apigatewayuuid; var apiName; // Variables for the callback... var theEvent; var theContext; var theDoneCallback; module.exports = { createGateway:function(event, context, doneCallback) { console.log('creating gateway, parameters passed in: '); console.log(event); theEvent = event; theContext = context; region = event.ResourceProperties.region; getmessagearn = event.ResourceProperties.getmessagelambdaapiuri; postmessagearn = event.ResourceProperties.postmessagelambdaapiuri; iamRole = event.ResourceProperties.iamrole; apigatewayuuid = event.StackId; apiName = event.ResourceProperties.apiname; AWS.config.update({region: region}); apigateway = new AWS.APIGateway(); theDoneCallback = doneCallback; createGatewayImplementation(); } } function createGatewayImplementation() { // Asyncrhonous Steps that need to be done in order... async.waterfall([ createRestAPI, getRootResourse, createZombieResource, createMessagesResource, createMethods, createMethodResponses, createTalkerResource, createTalkerMethods, createTalkerIntegrations, createTwilioResource, createTwilioMethods, createTwilioMethodResponses, createTwilioIntegrations, createTwilioIntegrationResponses, createIntegrations, createIntegrationResponses, createDeployment ], done); } function createRestAPI(callback) { console.log('Creating REST API'); var params = { name: apiName, description: apigatewayuuid }; apigateway.createRestApi(params, function(err, data) { if (!err) { restAPIId = data.id; return callback(null) } else { callback(err); } }); } function getRootResourse(callback){ console.log('Getting Root Resource'); var params = { restApiId: restAPIId }; apigateway.getResources(params, function(err, data) { if(!err) { currentResourceId = data.items[0].id; // successful response return callback(null); } else { callback(err); } }); } function createZombieResource(callback) { console.log('Creating Zombie Resource'); var params = { parentId: currentResourceId, /* required */ pathPart: 'zombie', /* required */ restApiId: restAPIId /* required */ }; apigateway.createResource(params, function(err, data) { if(!err) { currentResourceId = data.id; zombieResourceId = data.id; return callback(null); } else{ callback(err); } }); } function createMessagesResource(callback) { console.log('Creating Message Resource'); var params = { parentId: currentResourceId, pathPart: 'message', restApiId: restAPIId }; apigateway.createResource(params, function(err, data) { if(!err) { currentResourceId = data.id; return callback(null); } else { callback(err); } }); } function createMethods(callback) { console.log('Creating GET Method'); //this method is going to chain the callbacks for the 3 methods to create... //we don't need to save the IDs from these calls. var params = { authorizationType: 'AWS_IAM', /* required */ httpMethod: 'GET', /* required */ resourceId: currentResourceId, /* required */ restApiId: restAPIId, /* required */ apiKeyRequired: false }; apigateway.putMethod(params, function(err, data) { if(!err) { console.log('Creating POST Method'); params.httpMethod = 'POST'; apigateway.putMethod(params, function(err, data) { if(!err) { console.log('Creating OPTIONS Method'); params.httpMethod = 'OPTIONS'; params.authorizationType = 'None'; apigateway.putMethod(params, function(err, data) { if(!err) { callback(null); } else{ callback(err); } }); } else { callback(err); } }); } else { callback(err); } }); } function createMethodResponses(callback) { console.log('Creating GET Method Response'); var params = { httpMethod: 'GET', /* required */ resourceId: currentResourceId, /* required */ restApiId: restAPIId, /* required */ statusCode: '200', /* required */ responseModels: { 'application/json': 'Empty', }, responseParameters: { 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Methods': true } }; apigateway.putMethodResponse(params, function(err, data) { if(!err) { console.log('Creating POST Method Response'); params.httpMethod = 'POST'; apigateway.putMethodResponse(params, function(err, data) { if(!err) { console.log('Creating OPTIONS Method Response'); params.httpMethod = 'OPTIONS'; /* params.responseParameters = { 'method.response.header.Access-Control-Allow-Origin': true, 'method.response.header.Access-Control-Allow-Headers': true, 'method.response.header.Access-Control-Allow-Methods': true }; */ apigateway.putMethodResponse(params, function(err, data) { if(!err) { callback(null); } else { callback(err); } }); } else { callback(err); } }); } else { callback(err); } }); } function createIntegrations(callback) { console.log('Creating GET Integration'); var params = { httpMethod: 'GET', /* required */ resourceId: currentResourceId, /* required */ restApiId: restAPIId, /* required */ type: 'AWS', /* required */ credentials: iamRole, integrationHttpMethod: 'POST', uri: getmessagearn, }; apigateway.putIntegration(params, function(err, data) { if (!err) { console.log('Creating POST Integration'); params.httpMethod = 'POST'; params.uri = postmessagearn; params.requestTemplates = { "application/json": '{"message": $input.json(\'$.message\'), "name": $input.json(\'$.name\'), "channel" : $input.json(\'$.channel\') }' } apigateway.putIntegration(params, function(err, data) { if (!err) { console.log('Creating OPTIONS Integration'); params.httpMethod = 'OPTIONS'; params.uri = null; params.type = 'MOCK'; params.requestTemplates = { "application/json": '{"statusCode": 200}' }; apigateway.putIntegration(params, function(err, data) { if (!err) { callback(null); } else { callback(err); } }); } else { callback(err); } }); } else { callback(err); } }); } function createIntegrationResponses(callback) { console.log('Creating GET Integration Response'); var params = { httpMethod: 'GET', /* required */ resourceId: currentResourceId, /* required */ restApiId: restAPIId, /* required */ statusCode: '200', /* required */ responseParameters: { 'method.response.header.Access-Control-Allow-Origin': "'*'" }, responseTemplates : { "application/json":'{#set($inputRoot = $input.path("$")) \ "messages": [ \ #set($index = $inputRoot.Items.size()) \ #foreach($i in $inputRoot.Items) \ #set($index = $index - 1) \ #set($elem = $inputRoot.Items.get($index)) \ { \ "name": "$elem.name.S", \ "channel": "$elem.channel.S", \ "message": "$elem.message.S", \ "timestamp":"$elem.timestamp.N" \ } \ #if($foreach.hasNext),#end \ #end \ ]}' } }; apigateway.putIntegrationResponse(params, function(err, data) { if(!err) { console.log('Creating POST Integration Response'); params.httpMethod = 'POST'; apigateway.putIntegrationResponse(params, function(err, data) { if(!err) { console.log('Creating OPTIONS Integration Response'); params.httpMethod = 'OPTIONS'; params.responseParameters = { 'method.response.header.Access-Control-Allow-Origin': "'*'", 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'", 'method.response.header.Access-Control-Allow-Methods': "'GET,POST,OPTIONS'" }; params.responseTemplates = { "application/json":'{"statusCode": 200}' }; apigateway.putIntegrationResponse(params, function(err, data) { if(!err) { callback(null); } else { callback(err); } }); } else { callback(err); } }); } else { callback(err); } }); } function createDeployment(callback) { console.log('Creating Deployment'); var params = { restApiId: restAPIId, /* required */ stageName: 'ZombieWorkshopStage', /* required */ cacheClusterEnabled: false, description: 'ZombieWorkshopStage deployment', stageDescription: 'ZombieWorkshopStage deployment' }; apigateway.createDeployment(params, function(err, data) { if(!err) { callback(null); } else { callback(err); } }); } function createTalkerResource(callback) { console.log('Creating Talker Resource'); var params = { parentId: zombieResourceId, pathPart: 'talkers', restApiId: restAPIId }; apigateway.createResource(params, function(err, data) { if(!err) { talkerResourceId = data.id; return callback(null); } else { callback(err); } }); } function createTalkerMethods(callback) { console.log('Creating GET Method'); //this method is going to chain the callbacks for the 3 methods to create... //we don't need to save the IDs from these calls. var params = { authorizationType: 'AWS_IAM', /* required */ httpMethod: 'GET', /* required */ resourceId: talkerResourceId, /* required */ restApiId: restAPIId, /* required */ apiKeyRequired: false }; apigateway.putMethod(params, function(err, data) { if(!err) { console.log('Creating POST Method'); params.httpMethod = 'POST'; apigateway.putMethod(params, function(err, data) { if(!err) { console.log('Creating OPTIONS Method'); params.httpMethod = 'OPTIONS'; params.authorizationType = 'None'; apigateway.putMethod(params, function(err, data) { if(!err) { callback(null); } else { callback(err); } }); } else { callback(err); } }); } else { callback(err); } }); } function done(err, status) { if(err) { console.log('There was an error with APIGW Create waterfall callback.'); theDoneCallback(err, null); } else { console.log('Callback with rest ID of: ' + restAPIId); theDoneCallback(null, restAPIId); } } function createTalkerIntegrations(callback) { console.log('Creating GET Integration'); var params = { httpMethod: 'GET', /* required */ resourceId: talkerResourceId, /* required */ restApiId: restAPIId, /* required */ type: 'MOCK', /* required */ credentials: iamRole, integrationHttpMethod: 'POST', uri: null, requestTemplates: { "application/json": '{"statusCode": 200}' } }; apigateway.putIntegration(params, function(err, data) { if (!err) { console.log('Creating POST Integration'); params.httpMethod = 'POST'; apigateway.putIntegration(params, function(err, data) { if (!err) { console.log('Creating OPTIONS Integration'); params.httpMethod = 'OPTIONS'; params.uri = null; params.type = 'MOCK'; params.requestTemplates = { "application/json": '{"statusCode": 200}' }; apigateway.putIntegration(params, function(err, data) { if (!err) { callback(null); } else { callback(err); } }); } else { callback(err); } }); } else { callback(err); } }); } function createTwilioResource(callback) { console.log('Creating Twilio Resource'); var params = { parentId: zombieResourceId, pathPart: 'twilio', restApiId: restAPIId }; apigateway.createResource(params, function(err, data) { if(!err) { twilioResourceId = data.id; return callback(null); } else { callback(err); } }); } function createTwilioMethods(callback) { console.log('Creating Twilio POST Method'); var params = { authorizationType: 'None', /* required */ httpMethod: 'POST', /* required */ resourceId: twilioResourceId, /* required */ restApiId: restAPIId, /* required */ apiKeyRequired: false }; apigateway.putMethod(params, function(err, data) { if(!err) { console.log('Created Twilio POST Method'); return callback(null); } else { callback(err); } }); } function createTwilioMethodResponses(callback) { console.log('Creating Twilio POST Method Response'); var params = { httpMethod: 'POST', /* required */ resourceId: twilioResourceId, /* required */ restApiId: restAPIId, /* required */ statusCode: '200', /* required */ responseModels: { 'application/xml': 'Empty', } }; apigateway.putMethodResponse(params, function(err, data) { if(!err) { console.log('Created Twilio POST Method Response'); return callback(err); } else { callback(err); } }); } function createTwilioIntegrations(callback) { console.log('Creating Twilio POST Integration'); var params = { httpMethod: 'POST', /* required */ resourceId: twilioResourceId, /* required */ restApiId: restAPIId, /* required */ type: 'MOCK', /* required */ credentials: iamRole, integrationHttpMethod: 'POST', uri: null, requestTemplates: { "application/x-www-form-urlencoded": '{"postBody" : "$input.path(\'$\')"}' } }; apigateway.putIntegration(params, function(err, data) { if (!err) { console.log('Created Twilio POST Integration'); return callback(null); } else { callback(err); } }); } function createTwilioIntegrationResponses(callback) { console.log('Creating Twilio POST Integration Response'); var params = { httpMethod: 'POST', /* required */ resourceId: twilioResourceId, /* required */ restApiId: restAPIId, /* required */ statusCode: '200', /* required */ responseTemplates : { "application/xml": '#set($inputRoot = $input.path(\'$\'))$inputRoot' } }; apigateway.putIntegrationResponse(params, function(err, data) { if(!err) { console.log('Created Twilio POST Integration Response'); return callback(null); } else { callback(err); } }); } ================================================ FILE: CloudFormation/CustomResources/APIGatewayCreateScript/src/ApiGatewayDelete.js ================================================ var AWS = require('aws-sdk'); var apigateway; var apigatewayuuid; module.exports = { deleteGateway:function(event, context, callback) { console.log('deleting gateway, parameters passed in: '); console.log(event); region = event.ResourceProperties.region; apigatewayuuid = event.StackId; AWS.config.update({region: region}); apigateway = new AWS.APIGateway(); deleteGatewayImplementation(callback); } } function deleteGatewayImplementation(callback) { var params = {}; apigateway.getRestApis(params, function(err, data) { if (!err) { console.log('finding api gateway in list'); for (var i = 0; i < data.items.length; i++) { if(data.items[i].description == apigatewayuuid) { console.log('found gateway, deleting...'); var params = { restApiId: data.items[i].id }; apigateway.deleteRestApi(params, function(err, data) { if (!err) { console.log('successfully deleted api gateway'); callback(null); } else { callback(err); } }); } } } else { console.log(err, err.stack); callback(err); } }); } ================================================ FILE: CloudFormation/CustomResources/APIGatewayCreateScript/src/LambdaHandler.js ================================================ /** * New node file */ var AWS = require('aws-sdk'); var apigatewaycreate = require('./ApiGatewayCreate'); var apigatewaydelete = require('./ApiGatewayDelete'); var cloudformationsender = require('./cloudformationsender'); var zombieconfigupdater = require('./ZombieWebsiteConfigUpdate'); var theRegion; var theS3Bucket; var theS3Key var theEvent; var theContext; var RestApiID; exports.handleGatewayEvent = function(event, context) { theEvent = event; theContext = context; if(event.RequestType == 'Create') { theRegion = event.ResourceProperties.region; theS3Bucket = event.ResourceProperties.s3bucket; theS3Key = event.ResourceProperties.s3key; AWS.config.update({region: theRegion}); apigatewaycreate.createGateway(event, context, createApiGatewayCallback); } else if(event.RequestType == 'Delete') { apigatewaydelete.deleteGateway(event, context, finishedUpdatingCallback); } else { console.log(event); console.log('non-create requst type, sending suceed'); cloudformationsender.sendResponse(event, context, "SUCCESS", {}); } } function createApiGatewayCallback(err, restAPIId) { if(err) { console.log(err, err.stack); cloudformationsender.sendResponse(theEvent, theContext, "FAILED", {}); } else { //var url = "https://" + restAPIId + ".execute-api." + theRegion + ".amazonaws.com/ZombieWorkshopStage/zombie/message"; var url = "https://" + restAPIId + ".execute-api." + theRegion + ".amazonaws.com/ZombieWorkshopStage"; RestApiID = restAPIId; // set global var equal to the rest ID. console.log("calling s3 helper to create constants with url: " + url); zombieconfigupdater.updateConfig(theRegion, theS3Key, theS3Bucket, url, finishedUpdatingCallback); } } /** * callback that looks if it's an error and updates cloudformation appropriately... * @param err */ function finishedUpdatingCallback(err) { if(err) { console.log('Processing failed during finishedUpdatingCallback.'); cloudformationsender.sendResponse(theEvent, theContext, "FAILED", {}); } else { console.log('Calling cloudformationsender with SUCCESS param of of RestApiID: ' + RestApiID); cloudformationsender.sendResponse(theEvent, theContext, "SUCCESS", { "RestApiID": RestApiID }); } } ================================================ FILE: CloudFormation/CustomResources/APIGatewayCreateScript/src/ZombieWebsiteConfigUpdate.js ================================================ /** * This module writes the file out in the format needed for the website. * the S3 bucket/key and the url is passed in, and it writes the javascript file out. */ var AWS = require('aws-sdk'); module.exports = { updateConfig:function(region, s3key, s3bucketName, url, callback) { console.log('updating Zombie S3 web page located at: ' + s3key + ' and ' + s3bucketName); AWS.config.update({region: region}); var s3bucket = new AWS.S3({params: {Bucket: s3bucketName}}); s3bucket.createBucket(function() { var params = {Key: s3key, Body: 'var MESSAGES_ENDPOINT = "' + url + '";'}; s3bucket.upload(params, function(err, data) { if (err) { callback(err); } else { callback(null); } }); }); } } ================================================ FILE: CloudFormation/CustomResources/APIGatewayCreateScript/src/cloudformationsender.js ================================================ /** * New node file */ module.exports = { sendResponse: function(event, context, responseStatus, responseData) { var responseBody = JSON.stringify({ Status: responseStatus, Reason: "See the details in CloudWatch Log Stream: " + context.logStreamName, PhysicalResourceId: context.logStreamName, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: responseData }); console.log("RESPONSE BODY:\n", responseBody); var https = require("https"); var url = require("url"); var parsedUrl = url.parse(event.ResponseURL); var options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: "PUT", headers: { "content-type": "", "content-length": responseBody.length } }; console.log("SENDING RESPONSE...\n"); var request = https.request(options, function(response) { console.log("STATUS: " + response.statusCode); console.log("HEADERS: " + JSON.stringify(response.headers)); // Tell AWS Lambda that the function execution is done context.done(); }); request.on("error", function(error) { console.log("sendResponse Error:" + error); // Tell AWS Lambda that the function execution is done context.done(); }); // write data to request body request.write(responseBody); request.end(); } } ================================================ FILE: CloudFormation/CustomResources/IamUsers/IamLambdaHandler.js ================================================ var aws = require('aws-sdk'); var iamCreate = require('./create.js'); var iamDelete = require('./delete.js'); var cloudformationsender = require('./cloudformationsender.js'); var region; var theEvent; var theContext; var groupName; var stackName; exports.handleIAM = function(event, context) { theEvent = event; theContext = context; region = event.ResourceProperties.region; aws.config.update({region: region}); if(event.RequestType == 'Create') { stackName = event.ResourceProperties.StackName; groupName = stackName + '-IamGroup'; iamCreate.createIAM(event, context, finishedCreatingCallback); } else if(event.RequestType == 'Delete') { iamDelete.deleteIAM(event, context, finishedDeletingCallback); } else { console.log(event); console.log('Event is not a create or delete, send success'); cloudformationsender.sendResponse(event, context, "SUCCESS", {}); } } /** * Callback function for the IAM creation which should have 3 params coming in. */ function finishedCreatingCallback(err, usersForCloudFormation, IAMuserPassword, groupName) { if(err) { cloudformationsender.sendResponse(theEvent, theContext, "FAILED", {}); } else { cloudformationsender.sendResponse(theEvent, theContext, "SUCCESS", { "IamPassword": IAMuserPassword, "Users": usersForCloudFormation, "IamGroup": groupName }); } } /** * Callback function for the IAM deletion, no params. */ function finishedDeletingCallback(err) { if(err) { cloudformationsender.sendResponse(theEvent, theContext, "FAILED", {}); } else { cloudformationsender.sendResponse(theEvent, theContext, "SUCCESS", {}); } } ================================================ FILE: CloudFormation/CustomResources/IamUsers/cloudformationsender.js ================================================ /** * New node file */ module.exports = { sendResponse: function(event, context, responseStatus, responseData) { var responseBody = JSON.stringify({ Status: responseStatus, Reason: "See the details in CloudWatch Log Stream: " + context.logStreamName, PhysicalResourceId: context.logStreamName, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: responseData }); console.log("RESPONSE BODY:\n", responseBody); var https = require("https"); var url = require("url"); var parsedUrl = url.parse(event.ResponseURL); var options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: "PUT", headers: { "content-type": "", "content-length": responseBody.length } }; console.log("SENDING RESPONSE...\n"); var request = https.request(options, function(response) { console.log("STATUS: " + response.statusCode); console.log("HEADERS: " + JSON.stringify(response.headers)); // Tell AWS Lambda that the function execution is done context.done(); }); request.on("error", function(error) { console.log("sendResponse Error:" + error); // Tell AWS Lambda that the function execution is done context.done(); }); // write data to request body request.write(responseBody); request.end(); } } ================================================ FILE: CloudFormation/CustomResources/IamUsers/create.js ================================================ var aws = require('aws-sdk'); var async = require('async'); var iam; // Variables for the callback... var theEvent; var theContext; var theDoneCallback; var stackName; var groupName; var IAMuserPassword = "0Sa$3mJCC8xY"; var numIamUsers; // num users requested from cfn var requestedUserCountArray = []; // numIamUsers split and counted var usersCreatedArray = []; // Hold our created usernames module.exports = { createIAM:function(event, context, doneCallback) { console.log(event); theEvent = event; theContext = context; stackName = event.ResourceProperties.StackName; groupName = stackName + '-IamGroup'; numIamUsers = event.ResourceProperties.IamUsers; iam = new aws.IAM(); theDoneCallback = doneCallback; pushUsers(numIamUsers); createUsersImplementation(); } } function createUsersImplementation() { async.series([ createIamGroup, createUsers ], done); } function createIamGroup (callback) { console.log('Creating IAM Group'); var params = { GroupName: groupName }; iam.createGroup(params, function(err, data) { if (err) { console.log('Error creating group') return callback(err); } else { console.log('Created IAM Group ' + params.GroupName); callback(null, params.GroupName); } }); } function createUsers (callback) { async.forEachLimit(requestedUserCountArray, 1, function(item, callback) { async.waterfall([ async.apply(userCreate, item), userAddToGroup, userCreateLoginProfile ], function (err, data) { if (err) { return callback(err); } else{ console.log('Done creating user'); callback(null); } }); }, function(err){ if (err) { return callback(err); } else { callback(null); } }); } function userCreate(user, callback){ console.log('Creating user ' + user); var params = { UserName: stackName + "-user-" + user }; iam.createUser(params, function(err, data){ if (err) { console.log('Error creating user') return callback(err); } else { console.log('Created user ' + params.UserName); callback(null, params.UserName); } }); } function userAddToGroup(user, callback){ var params = { GroupName: groupName, UserName: user }; iam.addUserToGroup(params, function(err, data) { if (err) { console.log('Error adding user to group') return callback(err); } else { console.log('Added user ' + params.UserName + ' to IAM group.'); callback(null, params.UserName); } }); } function userCreateLoginProfile(user, callback){ console.log('Creating login profile for ' + user); var params = { Password: IAMuserPassword, UserName: user, PasswordResetRequired: false }; iam.createLoginProfile(params, function(err, data) { if (err) { console.log('Error creating login profile for user'); return callback(err); } else { console.log('Created login profile for ' + params.UserName); usersCreatedArray.push(params.UserName); callback(null); } }); } /** * Create incrementing user numbers. * Take numIamUsers from CFN and turn it into an array of numbers counting from 1. */ function pushUsers(numIamUsers) { for (var k = 1; k<=numIamUsers; k++) { requestedUserCountArray.push(k); } } function done(err, status) { if(err) { return theDoneCallback(err, null); } else { theDoneCallback(null, usersCreatedArray.toString(), IAMuserPassword, groupName); // pass back params for CFN output } } ================================================ FILE: CloudFormation/CustomResources/IamUsers/delete.js ================================================ var aws = require('aws-sdk'); var async = require('async'); var iam; var groupObject; var groupName; var stackName; // Variables for the callback... var theEvent; var theContext; var theDoneCallback; module.exports = { deleteIAM:function(event, context, doneCallback) { console.log('Deleting users'); theEvent = event; theContext = context; stackName = event.ResourceProperties.StackName; groupName = stackName + '-IamGroup'; iam = new aws.IAM(); theDoneCallback = doneCallback; deleteUsersImplementation(groupName); } } function deleteUsersImplementation(groupName) { async.waterfall([ async.apply(getGroupUsers, groupName), deleteUsers, deleteGroup ], done); } function getGroupUsers(groupName, callback) { var params = { GroupName: groupName }; var usersToDelete = []; iam.getGroup(params, function(err, data) { if (err) { console.log('Error getting group'); return callback(err); } else { groupObject = data.Users; groupName = data.Group.GroupName; for (var obj in groupObject) { var userName = groupObject[obj]['UserName']; console.log('UserName is ' + userName); usersToDelete.push(userName); } callback(null, usersToDelete, params.GroupName); } }); } function deleteUsers (usersToDelete, groupName, callback) { async.forEachLimit(usersToDelete, 1, function(item, callback) { async.waterfall([ async.apply(removeUserFromGroup, item, groupName), removeUserLoginProfile, deleteIamUser, ], function (err, data) { if (err) { console.log('Error occurred deleting user'); return callback(err); } else { callback(null); } }); }, function(err, data){ if (err) { console.log('Error in deleteusers function.'); return callback(err); } else { callback(null, groupName); } }); } function removeUserFromGroup(user, groupName, callback) { console.log('Removing user ' + user + ' from group'); var params = { GroupName: groupName, UserName: user }; iam.removeUserFromGroup(params, function(err, data) { if (err) { console.log('Error removing user from group'); return callback(err); } else { console.log('Removed IAM user ' + params.UserName); callback(null, params.UserName); } }); } function removeUserLoginProfile(user, callback){ console.log('Removing login profile for ' + user); var params = { UserName: user }; iam.deleteLoginProfile(params, function(err, data) { if (err) { console.log('Error deleting login profile for user'); return callback(err); } else { console.log('Removed login profile for user: ' + params.UserName); callback(null, params.UserName); } }); } function deleteIamUser(user, callback){ console.log('Deleting user ' + user); var params = { UserName: user }; iam.deleteUser(params, function(err, data) { if (err) { console.log('Error deleting user'); return callback(err); } else { console.log('Deleted IAM user ' + params.UserName); callback(null); } }); } function deleteGroup(groupName, callback) { var params = { GroupName: groupName }; iam.deleteGroup(params, function(err, data) { if (err) { console.log('Error deleting IAM group'); return callback(err); } else { console.log('IAM Group deleted: ' + params.GroupName); callback(null); } }); } function done(err, status) { if(err) { return theDoneCallback(err); } else { theDoneCallback(null); } } ================================================ FILE: CloudFormation/CustomResources/S3GetFilesFunction/S3GetFilesFunction.js ================================================ var AWS = require('aws-sdk'); var async = require('async'); exports.handler = function(event, context) { console.log('REQUEST RECEIVED:\n', JSON.stringify(event)); // Set region to the destination region where the user's bucket is hosted. //aws.config.update({region: event.ResourceProperties.S3Region}) var responseData = {}; var responseStatus = "FAILED"; // Start out with response of FAILED until we confirm SUCCESS explicitly. var srcS3Bucket = event.ResourceProperties.BucketName; // S3 bucket where AWS has hosted the lab content var dstS3Bucket = event.ResourceProperties.WebsiteBucketCreatedEarlier; var s3Region = event.ResourceProperties.S3Region; var s3 = new AWS.S3({params: {Bucket: srcS3Bucket}, region: s3Region}); // CloudFormation cannot delete S3 bucket if there are objects in it. // If DELETE request type is sent, delete the objects out of the user's bucket, then log SUCCESS so Cloudformation can proceed. if (event.RequestType == "Delete") { var params = { Bucket: dstS3Bucket } s3.listObjects(params, function(err, data) { if (err) { responseData = {Error: 'Failed to get objects from bucket for deletion.'}; console.log(responseData.Error + ':\\n', err); } params = {Bucket: dstS3Bucket}; params.Delete = {}; params.Delete.Objects = []; data.Contents.forEach(function(content) { params.Delete.Objects.push({Key: content.Key}); }); s3.deleteObjects(params, function(err, data) { if (err) { responseData = {Error: 'Failed to delete an object from bucket.'}; console.log(responseData.Error + ':\\n', err); } else { console.log(data); responseStatus = "SUCCESS"; } sendResponse(event, context, responseStatus, responseData); }); }); } // if request type is CREATE or UPDATE, list objects from the zombie workshop bucket and copy them to the user's new bucket. else { function initiateCopyObjects() { // List all objects, then invoke copy function with keys async.waterfall([ s3ListObjects, s3CopyObjects ], function(err, result) { if (err) { console.log('Error: ' + err); responseStatus = "FAILED"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData); } else { console.log('Done processing'); responseStatus = "SUCCESS"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData); } }); } function s3ListObjects(callback) { console.log('Starting s3 list objects function'); var keys = []; var params = { Bucket: srcS3Bucket }; s3.listObjects(params, function(err, data) { if (err) { console.log('Error listing S3 objects'); return callback('Failed to list objects in bucket with error ' + err); } else { console.log('Data.contents is: ' + data.Contents.Key); keys.push(data.Contents); callback(null, data.Contents); } }); } function s3CopyObjects(keys, callback) { async.each(keys, function(file, callback) { var params = { Bucket: dstS3Bucket, CopySource: srcS3Bucket + '/' + file.Key, Key: file.Key }; s3.copyObject(params, function(copyErr, copyData){ if (copyErr) { console.log('Failed to copy object: ' + copyErr); return callback(copyErr); } else { console.log('Copied: ', params.Key); callback(null); } }); }, function(err) { if (err) { console.log('There was an error'); return callback(err); } else { console.log('Finished copying'); callback(null, 'Finished copying all of the files'); } }); } initiateCopyObjects(); } // End CREATE/UPDATE section } function sendResponse(event, context, responseStatus, responseData) { var responseBody = JSON.stringify({ Status: responseStatus, Reason: 'See the details in CloudWatch Log Stream: ' + context.logStreamName, PhysicalResourceId: context.logStreamName, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: responseData }); console.log('RESPONSE BODY:\n', responseBody); var https = require('https'); var url = require('url'); var parsedUrl = url.parse(event.ResponseURL); var options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: 'PUT', headers: { "content-type": "", "content-length": responseBody.length } }; console.log('SENDING RESPONSE...\n'); var request = https.request(options, function(response) { console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); context.done(); }); request.on('error', function(error) { console.log('sendResponse Error:' + error); context.done(); }); request.write(responseBody); request.end(); } ================================================ FILE: CloudFormation/CustomResources/cognito/cognito.js ================================================ var AWS = require('aws-sdk'); var async = require('async'); exports.handler = function(event, context, callback) { console.log('REQUEST RECEIVED:\n', JSON.stringify(event)); var responseData = {}; var responseStatus = "FAILED"; // Start out with response of FAILED until we confirm SUCCESS explicitly. var bucket = event.ResourceProperties.bucket; // the bucket created for the app by CloudFormation var constantsFileKey = event.ResourceProperties.constantsFile; var stackName = event.ResourceProperties.StackName.replace(/-/g, ""); // remove hyphen from name so we can use it for Cognito which doesn't allow slashes. var cognitoRegion = event.ResourceProperties.CognitoRegion; // the region where Cognito exists. Cognito not in all regions so this is passed in from CFN. var stackRegion = event.ResourceProperties.region; // the region where the stack was launched. Might be diff than Cognito Region. var cognitoidentity = new AWS.CognitoIdentity({region: event.ResourceProperties.CognitoRegion}); var s3bucket = new AWS.S3(); var cognitoRoleARN = event.ResourceProperties.cognitoRoleARN; var clientId = ''; var userPoolId = ''; var identityPoolid = ''; // If DELETE request type is sent, return success to cloudformation. User will manually tear down Cognito resources if (event.RequestType == "Delete") { responseStatus = "SUCCESS"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData, callback); } // if request type is CREATE or UPDATE, create the resources else { function initiateCognitoBuild() { async.waterfall([ createIdentityPool, setRoles, getConstantsFile, replaceConstantsFile ], function(err, result) { if (err) { console.log('Error: ' + err); responseStatus = "FAILED"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData, callback); } else { console.log('Done processing'); responseStatus = "SUCCESS"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData, callback); } }); } function createIdentityPool(callback) { var params = { AllowUnauthenticatedIdentities: true, IdentityPoolName: stackName + '_identitypool', }; cognitoidentity.createIdentityPool(params, function(err, data) { if (err) { console.log('Error creating identity pool. Error is: ' + err); return callback(err); } else { console.log('Created identity pool. Pool Id is: ' + data.IdentityPoolId); identityPoolid = data.IdentityPoolId; callback(null, data.IdentityPoolId); } }); } function setRoles(identityPoolid, callback){ var params = { IdentityPoolId: identityPoolid, Roles: { authenticated: cognitoRoleARN, unauthenticated: cognitoRoleARN } }; cognitoidentity.setIdentityPoolRoles(params, function(err, data) { if (err) { console.log('Unable to add roles to identity pool. Error: ' + err); return callback(err); } else { console.log('Added roles to identity pool.'); callback(null); } }); } function getConstantsFile(callback) { var params = { Bucket: bucket, Key: constantsFileKey }; s3bucket.getObject(params, function(err, data) { if (err) { console.log('Unable to retrieve constants file from S3 bucket.'); return callback(err); } else { console.log('Retrieved constants.js file from S3 bucket.'); console.log('url from file is: ' + data.Body); apigwURL = data.Body; callback(null, data.Body); } }); } function replaceConstantsFile(url, callback) { var params = { Bucket: bucket, Key: constantsFileKey, Body: url + '\nvar COGNITO_REGION = "' + cognitoRegion + '";\nvar AWS_REGION = "' + stackRegion + '";\nvar IDENTITY_POOL_ID = "' + identityPoolid + '";\nvar USER_POOL_ID = "' + userPoolId + '";\nvar CLIENT_ID = "' + clientId + '";' }; s3bucket.upload(params, function(err, data) { if (err) { console.log('Unable to put constants file into S3 bucket.'); return callback(err); } else { console.log('Uploaded constants.js file to S3 bucket.'); console.log('Constants file contents: ' + data.Body); callback(null); } }); } initiateCognitoBuild(); } // End CREATE/UPDATE section } function sendResponse(event, context, responseStatus, responseData, callback) { var responseBody = JSON.stringify({ Status: responseStatus, Reason: 'See the details in CloudWatch Log Stream: ' + context.logStreamName, PhysicalResourceId: context.logStreamName, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: responseData }); console.log('RESPONSE BODY:\n', responseBody); var https = require('https'); var url = require('url'); var parsedUrl = url.parse(event.ResponseURL); var options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: 'PUT', headers: { "content-type": "", "content-length": responseBody.length } }; console.log('SENDING RESPONSE...\n'); var request = https.request(options, function(response) { console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); callback(null); }); request.on('error', function(error) { console.log('sendResponse Error:' + error); callback(null); }); request.write(responseBody); request.end(); } ================================================ FILE: CloudFormation/CustomResources/cognitoTriggerBuild/index.js ================================================ var AWS = require('aws-sdk'); // This custom resource Lambda function builds the Cognito Lambda Trigger in the AWS region where CloudFormation created the Cognito Identity Pool for the workshop. // Cognito is not available in all regions. If the stack is launched in an unsupported Cognito region, CloudFormation defaults back to us-east-1 to launch Cognito resources. // CloudFormation cannot natively launch Lambda functions in remote regions so we are doing this inside a custom resource. // If the user launched the stack in a region that supports Cognito then this function will launch Cognito will launch in that region, otherwise it defaults to us-east-1. exports.handler = function(event, context, callback) { console.log('REQUEST RECEIVED:\n', JSON.stringify(event)); var responseData = {}; var responseStatus = "FAILED"; // Start out with response of FAILED until we confirm SUCCESS explicitly. var lambdaBucket = event.ResourceProperties.LambdaFunctionBucket; // the workshop bucket where the Cogntio Trigger function zip is located. var stackName = event.ResourceProperties.StackName; var region = event.ResourceProperties.region; // Region where the stack was launched. var lambda = new AWS.Lambda({region: event.ResourceProperties.CognitoRegion}); // Set Lambda region to the local location where Cognito was built. CFN passes this as a parameter. var iamRole = event.ResourceProperties.IamRole; // the iam role to associate with the function we're creating. // If DELETE request type is sent, return success to cloudformation. User will manually tear down Cognito resources if (event.RequestType == "Delete") { responseStatus = "SUCCESS"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData, callback); } // if request type is CREATE or UPDATE, create the resources else { var params = { Code: { S3Bucket: lambdaBucket, S3Key: 'cognitoLambdaTrigger.zip' }, FunctionName: stackName + '-CognitoLambdaTrigger' + '-' + region, Handler: 'index.handler', Role: iamRole, Runtime: 'nodejs4.3', Timeout: '120' }; lambda.createFunction(params, function(err, data) { if (err) { console.log('Error creating cognitoLambdaTrigger function. Error is: ' + err); responseStatus = "FAILED"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData, callback); } else { console.log('Created cognitoLambdaTrigger. Function ARN is: ' + data.FunctionArn); responseData = {FunctionARN: data.functionArn}; responseStatus = "SUCCESS"; console.log('responseStatus is: ' + responseStatus + ' and event is: ' + event + ' and context is: ' + context); sendResponse(event, context, responseStatus, responseData, callback); } }); } // End CREATE/UPDATE section } function sendResponse(event, context, responseStatus, responseData, callback) { var responseBody = JSON.stringify({ Status: responseStatus, Reason: 'See the details in CloudWatch Log Stream: ' + context.logStreamName, PhysicalResourceId: context.logStreamName, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: responseData }); console.log('RESPONSE BODY:\n', responseBody); var https = require('https'); var url = require('url'); var parsedUrl = url.parse(event.ResponseURL); var options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: 'PUT', headers: { "content-type": "", "content-length": responseBody.length } }; console.log('SENDING RESPONSE...\n'); var request = https.request(options, function(response) { console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); callback(null); }); request.on('error', function(error) { console.log('sendResponse Error:' + error); callback(null); }); request.write(responseBody); request.end(); } ================================================ FILE: ElasticSearchLambda/ZombieWorkshopSearchIndexing.js ================================================ var AWS = require('aws-sdk'); var path = require('path'); /* == Globals == */ var esDomain = { region: 'us-west-2', endpoint: 'https://ENDPOINT_HERE', index: 'messages', doctype: 'message' }; var endpoint = new AWS.Endpoint(esDomain.endpoint); var creds = new AWS.EnvironmentCredentials('AWS'); /* Lambda "main": Execution begins here */ exports.handler = function(event, context) { console.log(JSON.stringify(event, null, ' ')); event.Records.forEach(function(record) { if (typeof record.dynamodb.NewImage != 'undefined') { var doc = {message: { name: record.dynamodb.NewImage.name.S, message: record.dynamodb.NewImage.message.S, channel: record.dynamodb.NewImage.channel.S, timestamp: record.dynamodb.NewImage.timestamp.N} } console.log('document posted to ElasticSearch: ' + JSON.stringify(doc)) postToES(JSON.stringify(doc), context); } else { console.log('skipping non-inserts'); } }); } /* * Post the given document to Elasticsearch */ function postToES(doc, context) { var req = new AWS.HttpRequest(endpoint); console.log('create post request'); req.method = 'POST'; req.path = path.join('/', esDomain.index, esDomain.doctype); req.region = esDomain.region; req.headers['presigned-expires'] = false; req.headers['Host'] = endpoint.host; req.body = doc; console.log('Creating the Signer for the post request'); var signer = new AWS.Signers.V4(req , 'es'); // es: service code signer.addAuthorization(creds, new Date()); console.log('Sending Data'); var send = new AWS.NodeHttpClient(); send.handleRequest(req, null, function(httpResp) { var respBody = ''; httpResp.on('data', function (chunk) { respBody += chunk; }); httpResp.on('end', function (chunk) { console.log('Response: ' + respBody); context.succeed('Lambda added document ' + doc); }); }, function(err) { console.log('Error: ' + err); context.fail('Lambda failed with error ' + err); }); } ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} 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. ================================================ FILE: NOTICE ================================================ Zombie Microservices Workshop: Lab Guide Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. ================================================ FILE: README.md ================================================ # This workshop is no longer actively being maintained and is not recommended for use. Please visit our [Wild Rydes Serverless Workshops](https://github.com/aws-samples/aws-serverless-workshops) for the latest hands-on examples of building serverless applications. This workshop is preserved here for interested community members to fork and update as separate project. # Zombie Microservices Workshop: Lab Guide ## Overview of Workshop Labs The [Zombie Microservices Workshop](http://aws.amazon.com/events/zombie-microservices-roadshow/) introduces the basics of building serverless applications using [AWS Lambda](https://aws.amazon.com/lambda/), [Amazon API Gateway](https://aws.amazon.com/api-gateway/), [Amazon DynamoDB](https://aws.amazon.com/dynamodb/), [Amazon Cognito](https://aws.amazon.com/cognito/), [Amazon SNS](https://aws.amazon.com/sns/), and other AWS services. In this workshop, as a new member of the AWS Lambda Signal Corps, you are tasked with completing the development of a serverless survivor communications system during the Zombie Apocalypse. This workshop has a baseline survivor chat app that is launched via [CloudFormation](https://aws.amazon.com/cloudformation/). Complete the lab exercises to extend the functionality of the communications system or add your own custom functionality! Prior to beginning the labs, you will need to finalize the setup of User authentication for the application with [Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html). This is a necessary step to finalize the readiness of the application. ### Required: Setup Authentication with Cognito User Pools In this setup lab, you will integrate user authentication into your serverless survivor chat application using Amazon Cognito User Pools. ### Labs Each of the labs in this workshop is an independent section and you may choose to do some or all of them, or in any order that you prefer. * **Lab 1: Typing Indicator** This exercise already has the UI and backend implemented, and focuses on how to setup the API Gateway to provide a RESTful endpoint. You will configure the survivor chat application to display which survivors are currently typing in the chat room. * **Lab 2: SMS Integration with Twilio** This exercise uses [Twilio](http://twilio.com) to integrate SMS text functionality with the survivor chat application. You will configure a free-trial Twilio phone number so that users can send text messages to the survivor chat application. You'll learn to leverage mapping templates in API Gateway to perform data transformations in an API. * **Lab 3: Search Integration with Elasticsearch** This exercise adds an Elasticsearch cluster to the application which is used to index chat messages streamed from the DynamoDB table containing chat messages. * **Lab 4: Slack Integration** This exercise integrates the popular messaging app, [Slack](http://slack.com), into the chat application so that survivors can send messages to the survivor chat from within the Slack app. * **Lab 5: Intel Edison Zombie Motion Sensor** (IoT device required) This exercise integrates motion sensor detection of zombies to the chat system using an Intel Edison board and a Grove PIR Motion Sensor. You will configure a Lambda function to consume motion detection events and push them into the survivor chat! ### Workshop Cleanup This section provides instructions to tear down your environment when you're done working on the labs. * * * ### Let's Begin! Launch the CloudFormation Stack *Prior to launching a stack, be aware that a few of the resources launched need to be manually deleted when the workshop is over. When finished working, please review the "Workshop Cleanup" section to learn what manual teardown is required by you.* 1\. To begin this workshop, **click one of the 'Deploy to AWS' buttons below for the region you'd like to use**. This is the AWS region where you will launch resources for the duration of this workshop. This will open the CloudFormation template in the AWS Management Console for the region you select. Region | Launch Template ------------ | ------------- **N. Virginia** (us-east-1) | [![Launch Zombie Workshop Stack into Virginia with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=zombiestack&templateURL=https://s3.amazonaws.com/aws-zombie-workshop-us-east-1/CreateZombieWorkshop.json) **Ohio** (us-east-2) | [![Launch Zombie Workshop Stack into Ohio with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/new?stackName=zombiestack&templateURL=https://s3-us-east-2.amazonaws.com/aws-zombie-workshop-us-east-2/CreateZombieWorkshop.json) **Oregon** (us-west-2) | [![Launch Zombie Workshop Stack into Oregon with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?stackName=zombiestack&templateURL=https://s3-us-west-2.amazonaws.com/aws-zombie-workshop-us-west-2/CreateZombieWorkshop.json) **Ireland** (eu-west-1) | [![Launch Zombie Workshop Stack into Ireland with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=zombiestack&templateURL=https://s3-eu-west-1.amazonaws.com/aws-zombie-workshop-eu-west-1/CreateZombieWorkshop.json) **Frankfurt** (eu-central-1) | [![Launch Zombie Workshop Stack into Frankfurt with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-central-1#/stacks/new?stackName=zombiestack&templateURL=https://s3-eu-central-1.amazonaws.com/aws-zombie-workshop-eu-central-1/CreateZombieWorkshop.json) **Tokyo** (ap-northeast-1) | [![Launch Zombie Workshop Stack into Tokyo with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=ap-northeast-1#/stacks/new?stackName=zombiestack&templateURL=https://s3-ap-northeast-1.amazonaws.com/aws-zombie-workshop-ap-northeast-1/CreateZombieWorkshop.json) **Seoul** (ap-northeast-2) | [![Launch Zombie Workshop Stack into Seoul with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=ap-northeast-2#/stacks/new?stackName=zombiestack&templateURL=https://s3-ap-northeast-2.amazonaws.com/aws-zombie-workshop-ap-northeast-2/CreateZombieWorkshop.json) **Singapore** (ap-southeast-1) | [![Launch Zombie Workshop Stack into Singapore with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=ap-southeast-1#/stacks/new?stackName=zombiestack&templateURL=https://s3-ap-southeast-1.amazonaws.com/aws-zombie-workshop-ap-southeast-1/CreateZombieWorkshop.json) **Sydney** (ap-southeast-2) | [![Launch Zombie Workshop Stack into Sydney with CloudFormation](/Images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=ap-southeast-2#/stacks/new?stackName=zombiestack&templateURL=https://s3-ap-southeast-2.amazonaws.com/aws-zombie-workshop-ap-southeast-2/CreateZombieWorkshop.json) *If you have CloudFormation launch FAILED issues, please try launching in us-east-1 (Virginia)* 2\. Once you have chosen a region and are inside the AWS CloudFormation Console, you should be on a screen titled "Select Template". We are providing CloudFormation with a template on your behalf, so click the blue **Next** button to proceed. 3\. On the following screen, "Specify Details", your Stack is pre-populated with the name "zombiestack". You can customize that to a name of your choice **less than 15 characters in length** or leave as is. For the parameters section, if you want to develop with a team and would like to create IAM Users in your account to grant your teammates access, then specify how many teammates/users you want to be created in the **NumberOfTeammates** text box. Otherwise, leave it defaulted to 0 and no additional users will be created. The user launching the stack (you) already have the necessary permissions. Click **Next**. *If you create IAM users, an IAM group will also be created and those users will be added to that group. On deletion of the stack, those resources will be deleted for you.* 4\. On the "Options" page, leave the defaults and click **Next**. 5\. On the "Review" page, verify your selections, then scroll to the bottom and select the checkbox **I acknowledge that AWS CloudFormation might create IAM resources**. Then click **Create** to launch your stack. 6\. Your stack will take about 3 minutes to launch and you can track its progress in the "Events" tab. When it is done creating, the status will change to "CREATE_COMPLETE". 7\. Click the "Outputs" tab in CloudFormation and click the link for "MyChatRoomURL". This should open your chat application in a new tab. Leave this tab open as you'll come back to it later. Please continue to the next section for the required Cognito User Pools authentication setup. ## Setup Authentication with Cognito User Pools (Required) The survivor chat uses [Amazon Cognito](https://aws.amazon.com/cognito/) for authentication. Cognito Federated Identity enables you to authenticate users through an external identity provider and provides temporary security credentials to access your app’s backend resources in AWS or any service behind Amazon API Gateway. Amazon Cognito works with external identity providers that support SAML or OpenID Connect, social identity providers (such as Facebook, Twitter, Amazon) and you can also integrate your own identity provider. In addition to federating 3rd party providers such as Facebook, Google, and other providers, Cognito also offers a new built-in Identity Provider called [Cognito User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html). A Cognito Federated Identity pool has already been created for you when you launched CloudFormation. You will now setup the Cognito User Pool as the user directory of your chat app survivors and configure it as a valid Authentication Provider with the Cognito Federated Identity Pool. API Gateway has been configured with IAM Authorization to only allow requests that are signed with valid AWS permissions. When a user signs into the Survivor Chat App (User Pool) successfully, a web call is made to the Cognito Federated Identity Pool to assume temporary AWS credentials for your authenticated user. These credentials are used to make signed [AWS SigV4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) HTTPS requests to your message API. ![Overview of Cognito Authentication](/Images/CognitoOverview.png) **Let's get started...** 1\. Navigate to the Cognito service console. ![Navigate to the Cognito service](/Images/Cognito-Step1.png) Cognito User Pools is not available in all AWS regions. Please review the list [here](https://docs.aws.amazon.com/general/latest/gr/rande.html#cognito_identity_region) for the regions that Cognito is available in. Therefore if you launched your CloudFormation stack in any region other than one of those listed on the above website, then please use the top navigation bar in the management console to switch AWS regions and navigate to **us-east-1 (Virginia)** to configure Cognito. Your application will stay hosted in the region you launched the CloudFormation template, but the authentication with Cognito will reside in us-east-1 (Virginia). If you launched the Cloudformation stack in one of those regions where Cognito exists, then please simply navigate to the Cognito service in the AWS Management Console as the service is available in that region already and you will configure it within that region. When inside the Cognito service console, click the blue button **Manage your User Pools**. You will setup the user directory that your chat application users will authenticate to when they use your app. 2\. Click the blue button **Create a User Pool** in the upper right corner. You'll create a new user directory. 3\. In the "Pool Name" text box, name your user pool **[Your CloudFormation stack name]-userpool**. For example, if you named your CloudFormation stack "sample" earlier, then your user pool name would be "sample-userpool". After naming your User Pool, click **Step through Settings** to continue with manual setup. 4\. On the attributes page, select the "Required" checkbox for the following attributes: **email, name, phone number**. * Cognito User Pools allows you to define attributes that you'd like to associate with users of your application. These represent values that your users will provide when they sign up for your app. They are available to your application as a part of the session data provided to your client apps when users authenticate with Cognito. 5\. Click the link "Add custom attribute". Leave all the defaults and type a "Name" of **slackuser** exactly as typed here. Add 2 additional custom attributes: **slackteamdomain** and **camp**. * Within a User Pool, you can specify custom attributes which you define when you create the User Pool. For the Zombie Survivor chat application, we will include 3 custom attributes. Your attributes configuration should match the image below: ![Cognito User Pools: Attributes Configuration](/Images/Cognito-Step5.png) Click **Next Step**. 6\. On the Policies page, leave the Password policy settings as default and click **Next step**. 7\. On the verifications page, leave the defaults and click **Next step**. * We will not require MFA for this application. However, for during sign up we are requiring verification via email address. This is denoted with the email checkbox selected for "Do you want to require verification of emails or phone numbers?". With this setting, when users sign up for the application, a confirmation code will be sent to their email which they'll be required to input into the application for confirmation. 8\. On the "Message Customizations" page, in the section titled **Do you want to customize your email verification message?** add a custom email subject such as "Signal Corps Survivor Confirmation". We won't modify the message body but you could add your own custom message in there. We'll let Cognito send the emails from the service email address, but in production you could configure Cognito to send these verifications from an email server you own. Leave the rest of the default settings and click **Next step**. On the Tags page, leave the defaults and click **Next step**. Next, on the Devices page, leave the default option of "No" selected. We will not configure the User Pool to remember user's devices. 9\. On the Apps page, click **Add an app**. In the **App Name** textbox, type "Zombie Survivor Chat App" and **deselect the client secret checkbox**. Click **Set attribute read and write permissions**. You need to make sure that the app has "writable" and "readable" access to the attributes you created. Make sure that **all of the checkboxes are selected** for "Readable Attributes" and "Writable Attributes". Then click **Create app**, and then click **Next step**. 10\. In the dropdowns for the **Pre authentication** and **Post confirmation** triggers, select the Lambda function named "[Your CloudFormation Stack name]-CognitoLambdaTrigger-[Your Region]". Click **Next step**. * Cognito User Pools allows developers to inject custom workflow logic into the signup and signin process. This custom workflow logic is represented with AWS Lambda functions known as Lambda Triggers. * With this feature, developers can pass information to a Lambda function and specify that function to invoke at different stages of the signup/signin process, allowing for a serverless and event driven authentication process. * In this application, we will create two (2) Lambda triggers: * Post-Confirmation: This trigger will invoke after a user successfully submits their verification code upon signup and becomes a confirmed user. The Lambda function associated with this trigger takes the attributes provided by the user and inserts them into a custom Users table in DynamoDB that was created with CloudFormation. This allows us to perform querying of user attributes within our application. * Pre-Authentication: This trigger will invoke when a user's information is submitted for authentication to Cognito each time the survivor signs into the web application. The code for with this Lambda Trigger takes the user's attributes have been passed in as parameters from the invoking User Pool and using them to perform an update on the User's record in DynamoDB Users table. This allows us to load the user's data into DynamoDB when they initially sign in and also keep it current with the values in User Pools in an on-going basis as they log in each time. * For this workshop we use the same backend Lambda function for both of the triggers. On invocation, the function checks what type of even has occurred, Post-Confirmation or Pre-Authentication, and executes the correct code accordingly. 11\. Review the settings for your User Pool and click **Create pool**. If your pool created successfully you should be returned to the Pool Details page and it will display a green box that says "Your user pool was created successfully". 12\. Open a text editor on your computer and copy into it the "Pool Id" displayed on the Pool details page. Then click into the **Apps** tab found on the left side navigation pane. You should see an **App client id** displayed. Copy that **App client id** into your text editor as well. You are done configuring the User Pool. You will now setup federation into the Cognito Identity Pool that has already been created for you. * An [Amazon Cognito Identity Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) has been configured for you. Identity Pools allow external federated users to assume temporary credentials from AWS to make service API calls from within your apps. * You've just created the User Pool for authentication into your app. Now your users still need access to make IAM Authorized AWS API calls. * You'll setup federation inside of Cognito Identity and allow your User Pool as an **Authentication Provider**. On the top navigation bar in the management console, switch to **Federated Identities** by clicking the link as shown below. ![Navigating to Federated Identities Console](/Images/Cognito-Step12.png) 13\. Click into the Identity Pool that has already been created for you. It should be named "[Your CloudFormation stack name] _ identitypool". On the Idenity pool dashboard, in the upper right, select **Edit identity pool**. 14\. Cognito Identity allows you to give access to both authenticated users and unauthenticated (guest) users. The permissions associated with these groups of users is dictated by the IAM role that you attach to these Cognito roles. Your Authenticated and Unauthenticated Cognito roles have already been configured for you in CloudFormation. The Authenticated role has been configured to give permissions to the principal (your Cognito authenticated application user) to make "execute-api:invoke" calls to the API Gateway endpoint ARNs associated with the survivor serverless app. * When users authenticate into the application, they become an authenticated user, and the application allows them to send chat messages to the survivor chat. 15\. Click the black dropdown arrow in the section titled "Authentication providers". You will configure your Identity pool to allow federated access from your Identity Provider, your Cognito User Pool. In the "Cognito" identity provider tab, insert your **User Pool ID** and **App Client ID** into their respective text boxes from your text editor file. Do not delete them from the text file, you'll need these items again in a later step. You should have copied these from your User Pool earlier when you set it up. If you do not have these copied, please navigate back to your Cognito User Pool you created earlier and locate your User Pool Id and App Client ID. Scroll to the bottom of the page and click **Save Changes** to save the User Pool configuration settings. Your Cognito Federated Identiy Pool has been configured with Congito User Pool as an IdP. When users authenticate to the User Pool, they will assume temporary credentials with the permissions allowed via the Authenticated Role. 16\. You will now make an update to an application config file so that the serverless Javascript application can communicate with your User Pool to log users in. Navigate to the Amazon S3 console **in the region where you launched your CloudFormation stack.** * If you changed regions to configure Cognito, please return back to the region where you launched the stack and navigate to the S3 service. ![Navigate to the S3 service](/Images/Cognito-Step16.png) 17\. On the Amazon S3 buckets listing page, find and click into the bucket that was created for you by CloudFormation. It should be named with your stack name prepended to the beginning. Something like [CloudFormation Stack Name]-s3bucketforwebsitecontent".... * In the S3 Console search bar you can type **s3bucketforwebsitecontent** and your S3 bucket will display. 18\. This bucket contains all the contents for hosting your serverless JS app as well as the source code for the workshop's Lambda functions and CloudFormation resources. Please do not delete these contents. Click into the folder (prefix) named **S3** and navigate through to the file **S3/assets/js/constants.js** Download the **S3/assets/js.constants.js** file to your local machine and open it with a text editor. ![Download the constants.js file](/Images/Cognito-Step18.png) 19\. Open up the constants.js file and copy over the User Pool ID into the "USER_POOL_ID" variable. Then copy the App Client ID into the "CLIENT_ID" variable. These should be copied from the open text file you had open from earlier. * Your serverless javascript zombie application requires this constants values in file communicate with the different services of the workshop. * The Identity Pool Id was automatically filled in with several other variables when the CloudFormation template was launched. 20\. Save the constants.js file and upload it back to S3. While in the S3 console window, make sure you are in the **js** directory. Click the blue **Upload** button and upload the constants.js file from your local machine. Within the upload dialog, select the "Manage public permissions" dropdown and set the permissions on the file to read-only for the public by selecting the **Read** checkbox next to Everyone under the Objects category. You can also drag your file from your local machine into the S3 browser console to initiate an upload and then when the object is uploaded, make sure to select **Make Public**. * Your application now has the configuration it needs to interact with Cognito. 21\. Navigate back to CloudFormation and find the Chat Room URL (MyChatRoomURL) in the Outputs tab of your CloudFormation stack. Click it to open the chat application in a new browser window. * If you already had the application opened in your browser, please refresh the page so that the new constants.js loads with the app. 22\. You should see a sign in page for the Zombie survivor web app. You need to create an account so click **Sign Up**. 23\. Fill out the form to sign up as a survivor. * **Select your Camp**: Specify the geography where you live! Currently this attribute is not used in the application and is available for those that want to tackle an extra credit opportunity!. When you're done with the workshop, try and tackle the Channel Challenge in the Appendix. * **Slack Username**: Type the Slack Username you will use during the Slack lab of this workshop. This associates your Slack username with your Survivor app user account and is required if you want to do the Slack lab. * **Slack Team Domain Name**: Slack users can be members of many teams. Type the Slack team domain name that you want to integrate with this survivor chat app. The combination of a Slack team domain and Slack Username will unique identity a user to associate with your new Survivor chat app account. When done, click **Sign Up**. 24\. A form should appear asking you to type in your confirmation code. Please check your inbox for the email address you signed up with. You should received an email with the subject "Signal Corps Survivor Confirmation" (May be in your Spam folder!). Copy over the verification code and enter into the confirmation window. **Troubleshooting tips:** * If you are getting errors during the signup, please revisit the settings for your Cognito User Pool. You need to make sure that you've done the following - * Configured your Cognito Lambda triggers for both the **Pre-Authentication** and **Post-Confirmation** steps as described in Step 10. * Properly modified the constants.js config file and re-uploaded it to the JS directory for your application in S3. After you uploaded this constants.js file, you should have refreshed your zombie chat browser application page so that it could pull down the latest JS files. The application is client-side and needs this file's properties in order to bootstrap itself. * Users created in the application are also stored in a DynamoDB table named "Users". If you did not have your Cognito triggers set up correctly, you will need to navigate to the DynamoDB Users table and delete the entry for your user. You can then re-register in the application again. ![Confirm your signup](/Images/Cognito-Step24.png) After confirming your account, sign in with your credentials and begin chatting! You should see a red button called **Start Chatting** - click that button to toggle your session on. You may then begin typing messages followed by the "Enter" key to submit them. 25\. Your messages should begin showing up in the central chat pane window. Feel free to share the URL with your teammates, have them signup for accounts and begin chatting as a group! If you are building this solution solo, you can create multiple user accounts with different email addresses. Then login to both user accounts in different browsers to simulate multiple users. **The baseline chat application is now configured and working! There is still important functionality missing and the Lambda Signal Corps needs you to build it out...so get started below!** *This workshop does not utilize API Gateway Cache. Please KEEP THIS FEATURE TURNED OFF as it is not covered under the AWS Free Tier and will incur additional charges. It is not a requirement for the workshop.* ## Lab 1 - Typing Indicator **What you'll do in this lab...** In this section you will create functionality in your chat application that allows survivors to see which survivors in the chat room are currently typing. To configure this functionality, you will modify your API to integrate with backend Lambda functions that are responsible for querying and returning the users currently typing in the system, as well as updating metadata in the "talkers" DynamoDB table that contains details about which survivors are typing at which times. The survivor chat app continuously polls this API endpoint with GET requests to determine who is typing. As survivors are typing, POST requests are made to this same endpoint to update the talkers DynamoDB table. The typing indicator shows up in the web chat client in a section below the chat message panel. The UI and backend Lambda functions have already been implemented, and this lab focuses on how to configure your new integration in API Gateway. The application uses [CORS](http://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html). This lab will both wire up the backend Lambda function as well as perform the necessary steps to enable CORS. **Typing Indicator Architecture** ![Overview of Typing Indicator Architecture](/Images/TypingIndicatorOverview.png) 1\. Navigate to the API Gateway service. You can search for it on the main console homepage or type in the service name to quickly access the service (as shown below) ![API Gateway in Management Console](/Images/Typing-Step1.png) 2\. On the APIs listing screen in API Gateway, click into your Zombie chat API. It should be prefixed with the name of your CloudFormation stack that launched it. By default this should be "zombiestack-". Select the Zombie Workshop API Gateway. 3\. Click the **GET** method of your /zombie/talkers resource located at **/zombie/talkers/GET**. You can do this by clicking the "GET" method under the /zombie/talkers resource. The GET method is highlighted in blue in the image below. Click there. ![GET Method](/Images/Typing-Step3.png) *This GET HTTP method is used by the survivor chat app to perform continuous queries on the DynamoDB talkers table to determine which users are typing.* 4\. Click the **Integration Request** box. 5\. Under "Integration Type", Select **Lambda Function.** * Currently, this API method is configured to a "MOCK" integration. MOCK integrations are dummy backends that are useful when you are testing and don't yet have the backend built out but need the API to return sample dummy data. You will remove the MOCK integration and configure this GET method to connect to a Lambda function that queries DynamoDB. 6\. For the **Lambda Region** field, select the region in which you launched the CloudFormation stack. (HINT: Select the region code that corresponds with the yellow CloudFormation button you clicked to launch the CloudFormation template. You can also look in the upper right corner of the Management Console to see which region you are in). For example if you launched your stack in Virginia (us-east-1), then you will select us-east-1 as your Lambda Region. * When you launched the CloudFormation template, the launch also created several Lambda functions for you locally in the region where you launched your CFN stack - this includes functions for retrieving data from and putting data into a DynamoDB "Talkers" table with details about which survivors are currently typing in the chat room. 7\. For the Lambda Function field, begin typing "gettalkers" in the text box. In the auto-fill dropdown, select the function that contains "GetTalkersFromDynamoDB" in the name. It should look something like this.... **[CloudformationTemplateName]-[XXXXXXX]-GetTalkersFromDynamoDB-[Your Region]**. * This Lambda function is written in NodeJs. It performs GetItem DynamoDB requests on a Table called Talkers. This talkers table contains records that are continuously updated whenever users type in the chat room. By hooking up this Lambda function to your GET method, it will get invoked by API Gateway when the chat app polls the API with GET requests. 8\. Select the blue **Save** button and click **OK** if a pop up asks you to confirm that you want to switch to Lambda integration. Then grant access for API Gateway to invoke the Lambda function by clicking "OK" again. This 2nd popup asks you to confirm that you want to allow API Gateway to be able to invoke your Lambda function. 9\. Click the **Method Execution** back button to return to the method execution overview page. You'll now tell API Gateway what types of HTTP response types you want your API to expose. Click the **Method Response** section of the Method Execution Flow. 10\. Add a 200 HTTP Status response. Click "Add Response", type "200" in the status code text box and then click the little checkmark to save the method response, as shown below. ![Method Response](/Images/Typing-Step10.png) * You've configured the GET method of the /zombie/talkers resource to allow responses with HTTP status of 200. We could add more response types but we'll skip that for simplicity in this workshop. 11\. Go to the /zombie/talkers/POST method by clicking the "POST" option in the resource tree on the left navigation pane. ![POST Method](/Images/Typing-Step11.png) 12\. We're now going to configure to the /zombie/talkers resource to properly integrate with AWS Lambda on POST requests. **Perform Steps 4-10 again** just as you did for the GET method. However, this time when you are selecting the Lambda Function for the Integration Request, you'll type "writetalkers" in the auto-fill and select the function that looks something like this... **[CloudformationTemplateName]-[XXXXXXX]-WriteTalkersToDynamoDB-[Your Region]**. This way on POST requests, API Gateway will invoke your **writetalkers** Lambda function. Don't forget to return to the Method Response section for this POST method and add a "200" HTTP response status as you did for the GET method earlier, if it doesn't exist already. * In these steps you are configuring the POST method that is used by the chat app to insert data into DynamoDB Talkers table with details about which users are typing. You're performing the same exact method configuration for the POST method as you did for your GET method. However, since this POST method is used for sending data to the database, it triggers a different backend Lambda function. This function writes data to DynamoDB while the "GetTalkersToDynamoDB" function was used to retrieve data from DynamoDB. * You could optionally include the logic for both the POST and GET operations inside of a single Lambda function with your own built-in logic that properly checks for and handles POSTs and GETs (or other actions). 13\. Go to the /zombie/talkers/OPTIONS method 14\. Select the Method Response. 15\. Add a 200 method response. Click "Add Response", type "200" in the status code text box and then click the little checkmark to save the method response. 16\. Go back to the OPTIONS method flow and select the Integration Response. (To go back, there should be a blue hyperlink titled "Method Execution" which will bring you back to the method execution overview screen). 17\. Select the Integration Response. 18\. Add a new Integration response with a method response status of 200. Click the "Method response status" dropdown and select "200". Leave the "Content Handling" option set to **Passthrough**. When done, click the blue **Save** button. * In this section you configured the OPTIONS method simply to respond with HTTP 200 status code. The OPTIONS method type is simply used so that clients can retrieve details about the API resources that are available as well as the methods associated with them. 19\. Select the /zombie/talkers resource on the left navigation tree. ![talker resource](/Images/Typing-Step19.png) 20\. Click the "Actions" box and select "Enable CORS" in the dropdown. 21\. Select Enable and Yes to replace the existing values. You should see all green checkmarks for the CORS options that were enabled, as shown below. ![talker resource](/Images/Typing-Step21.png) * If you don't see all green checkmarks, this is probably because you forgot to add the HTTP Status 200 code for the Method Response Section. Go back to the method overview section for your POST, GET, and OPTIONS method and make sure that it shows "HTTP Status: 200" in the Method Response box. 22\. Click the "Actions" box and select Deploy API ![talker resource](/Images/Typing-Step22.png) 23\. Select the ZombieWorkshopStage deployment and hit the Deploy button. * In this workshop we deploy the API to a stage called "ZombieWorkshopStage". In your real world scenario, you'll likely create different stages of the API to reflect different versions that you'd like to maintain. **LAB 1 COMPLETE** Head back to the survivor chat app and **Refresh the page** type messages. POST requests are being made to the Talkers API resource which is updating a DynamoDB table continuously with timestamps along with who is typing. Simultaneously, the application is performing a continuous polling (GET Requests) against /zombie/talkers to show which survivors are typing. This displays ![talker resource](/Images/Typing-Done.png) * * * ## Lab 2 - SMS Integration with Twilio **What you'll do in this lab...** In this section, you’ll create a free-trial Twilio SMS phone number. You will configure this Twilio phone number with a webhook to forward all incoming text messages sent to your Twilio number to the /zombie/twilio API resource in API Gateway. This will allow you to communicate with survivors in the chat room via text message. **SMS Twilio Integration Architecture** ![Overview of Twilio Integration](/Images/TwilioOverview.png) 1\. Sign up for a free trial Twilio account at https://www.twilio.com/try-twilio. Or if you have an existing Twilio account, login. 2\. Once you have created your account, login to the Twilio console and navigate to the Home icon on the left navigation pane. On the Home screen/console dashboard, scroll down to the **Phone Numbers** section and click "Phone Numbers". ![Manage Twilio Phone Number](/Images/Twilio-Step2.png) 3\. On the Phone Numbers screen, click **Get Started** to assign a phone number to your account. Then click the red **Get your first Twilio phone number** button. We’re going to generate a 10-digit phone number in this lab, but a short-code would also work if preferred. This number should be enabled for voice and messaging by default. A popup will appear with your new phone number, click **Choose this number**. If the proposed phone number does not support messaging, click "Search for a different number", select your country and select the checkbox "SMS", then click "Search". Twilio propose a list of phone number, select "Choose number" for one of them. Then, type your address, click "Save and continue" and "Done". * **International Users** - These are US phone numbers that you are provisioning in Twilio. You can also choose to configure an internationl number in Twilio, however there may be charges that apply. Currently this workshop only supports US phone numbers in the front end JS application due to the necessary formatting logic that has yet to be introduced into the code! If you have an international mobile device, you can still do this lab. When registering for a user account in the zombie chat, just use a dummy placeholder 10 digit phone number for now. Later steps in this lab will illustrate a workaround that allows you to send SMS using your international phne number* 4\. Once you’ve received a phone number, click the **Manage Numbers** button on the left navigation pane. Click on your phone number, which will take you to the properties page for that number. 5\. Scroll to the bottom of the properties page, to the **Messaging** section. In the **Configure With** dropdown, select the **Webhooks/TwiML** option. Leave this page open for now and proceed to the next step. * The Twilio webhooks section allows you to integrate your phone number with third party services. In this case, you're going to configure your Twilio phone number to forward any messages it receives over to your API Gateway /zombie/twilio resource with POST requests. 6\. Now you’ll retrieve your **/zombie/twilio** API endpoint from API Gateway and provide it to Twilio to hook up to AWS. Open the AWS Management console in a new tab, and navigate to API Gateway, as illustrated below. Be sure to leave the Twilio tab open as you’ll need it again to finish setup. ![API Gateway in Management Console](/Images/Twilio-Step6.png) 7\. In the API Gateway console, select your API. Then on the left navigation tree, under your API, click **Stages**. ![API Gateway Resources Page](/Images/Twilio-Step7.png) 8\. With "Stages" selected, expand the "ZombieWorkshopStage" by clicking the blue arrow. Once expanded, select the **POST** method for the **/zombie/twilio** resource. The **/zombie/twilio** resource is the endpoint that we automatically created for you in CloudFormation for SMS integration with twilio.com. You should see an **Invoke URL** displayed for your **/zombie/twilio** resource, as shown below. ![API Gateway Invoke URL](/Images/Twilio-Step8.png) 9\. Copy the **Invoke URL** and return to the Twilio website. On the Twilio page that you left open, paste the Invoke URL from API Gateway into the text box next to the label **A message comes in**. Ensure that the request type is set to **HTTP POST**. This is illustrated below. ![Twilio Request URL](/Images/Twilio-Step9.png) 10\. Click **Save** to finalize the setup connecting Twilio to your API. 11\. You will now create the Lambda Function that processes your incoming Twilio messages, parses the message, and proxies it along to your /zombie/message Chat Service. To begin, navigate to the Lambda console. * As you'll see throughout this workshop, we will leverage separate Lambda functions to pre-process data before sending standardized/formatted requests to the /zombie/message resource. This allows us to-reuse the existing DynamoDB logic sitting behind the /zombie/message resource rather than writing multiple separate functions that all interact with DynamoDB individually. As messages come in to your Twilio number, the Twilio webhook forwards them with HTTP POST requests to your /zombie/twilio resource, which will be integrated with a backend pre-processing Lambda function. This pre-processing function will strip apart the Twilio payload and format it before making a signed SigV4 HTTPS POST to your /zombie/message service which requires IAM authorization in order to be invoked. 12\. Click **Create a Lambda function** and select the blueprint titled **Blank Function** as we will be creating a brand new function. Click **Next** to skip through the Configure Triggers screen. 13\. Create a name for the function, such as **"[Your CloudFormation stack name]-TwilioProcessing"**. Set the "Runtime" as **Node.js 4.3**. In the source code found on Github, open the **TwilioProcessing.js** file found inside the **/Twilio** folder. Delete the sample code in the Lambda console editor and replace it with the entire contents from your TwilioProcessing.js file. Once you have copied the code into Lambda, scroll down to [line 8](/Twilio/TwilioProcessing.js#L8) in the code where the **API** variable is declared. **API.endpoint** should show a value of "INSERT YOUR API GATEWAY URL HERE INCLUDING THE HTTPS://". Please replace this string with the fully qualified domain name (FQDN) of the URL for your **/zombie/message** POST method found in API Gateway. For example, it should look something like "https://xxxxxxxx.execute-api.us-west-2.amazonaws.com". You should also fill in the region code in the variable **API.region**. This should be the region where you launched CloudFormation. Next, you will also copy in the name of your DynamoDB **Users** table that was created for you. This should be named as **[Your CloudFormation Stack Name]-users"**. You should copy this table name into the **table** variable in your Lambda code. You will also need to copy in the name of your "phoneindex" (this is an index that was created on the DynamoDB table to assist with querying). These attributes can be found in the Outputs section in CloudFormation. You should be copying the values for **DynamoDBUsersTableName** and **DynamoDBUsersPhoneIndex** from CloudFormation. * Some of the functions in this workshop were originally authored for Nodejs 0.10 but are still capable of running in the Node4.3 runtimes +. The workshop will soon be upgraded to use the latest Nodejs runtime that is supported by Lambda. 14\. After you have copied the code into the Lambda inline code console and modified the variables, scroll down to the **Lambda function handler and role** section. **Choose an existing role** should be selected from the dropdown. Then for the existing **role**, select the role that looks like **[Your stack name]-ZombieLabLambdaRole...**. For simplicity we are reusing the same Lambda role for our functions. 15\. Under "Advancted settings", set the **Timeout** field to 30 seconds and keep all the rest of the defaults set. Then click **Next** and then **Create function** on the Review page to create your Lambda function. * You have just created a Lambda function that is integrated as the backend for your /zombie/twilio resource POST method. The function converts the parameters to the correct format for our Chat Service including a conversion to JSON format, and makes an HTTPS POST request to the /zombie/message Chat Service resource. That endpoint will take care of inserting the data into the DynamoDB messages table. 16\. Now that you have created the TwilioProcessing function, you need to connect it to the **POST** method for your /zombie/twilio endpoint. Navigate back to the API Gateway console and select the **POST** method for your **/zombie/twilio** resource. 17\. On the **Method Execution** screen for the "POST" method, the "Integration Request" box should show a type of **MOCK** for your /twilio resource. 18\. You will now change the **Integration Request** so that instead of integrating with a Mock integration, it will integrate with your TwilioProcessing Lambda function. Click **Integration Request**. On the Integration Request screen, change the "Integration type" radio button to **Lambda Function**. In the "Lambda Region" dropdown, select the region in which you created your TwilioProcessing Lambda function, and where you launched your CloudFormation Stack. For the **Lambda Function**, begin typing "TwilioProcessing" and the autofill should display your function. Select your **TwilioProcessing** function from the autofill. Click **Save**. In the popup window, confirm that you want to switch to Lambda Integration by clicking **OK**. Then confirm that you want to give API Gateway permission to invoke your function by clicking **OK**. Wait a few seconds for the changes to save. 19\. You will be brought back to the Integration Request page for your "POST" method. 20\. Twilio sends data from their API with a content-type of "application/x-www-form-urlencoded", but Lambda requires the content-type to be "application/json" for any payload parameters sent to it. You will configure a Mapping Template so that API Gateway converts the content type of incoming messages into JSON before executing your backend Lambda TwilioProcessing function with the parameters. 21\. On the Integration Request screen for your /zombie/twilio POST method, expand the **Body Mapping Templates** section and click **Add mapping template**. In the textbox for "Content-Type", input **application/x-www-form-urlencoded** and click the little checkmark button to continue. Once you have clicked the little checkbox, a popup window will appear asking if you want to only allow requests that match the Content-Type you specified. Click **Yes, secure this integration**. A new section will appear below with a dropdown for **Generate Template**. Click that dropdown and select **Method Request Passthrough**. 22\. A "Template" text editor window will appear. In this section you will input a piece of VTL transformation logic to convert the incoming Twilio data to JSON format. In this text editor, **delete all of the pre-filled content** and copy the following code into the editor. ```{"postBody" : "$input.path('$')"}``` After copying the code into the editor, click the **Save** button. You have now setup the POST method to convert the incoming data to JSON anytime a POST request is made to your /zombie/twilio resource with a Content-Type of "application/x-www-form-urlencoded". This should look like the screenshot below: ![Twilio Integration Request Mapping Template](/Images/Twilio-Step22.png) 23\. Now that you have configured the Integration Request to transform incoming messages into JSON, we need to configure the Integration Response to transform outgoing responses back to Twilio into XML format since the Twilio API requires XML as a response Content-Type. This step is required so that when you send SMS messages to the survivor Chat Service, it can respond back to your Twilio Phone Number with a confirmation message that your message was received successfully. 24\. Head back to the Method Execution screen for the twilio POST method. On the "Method Execution" screen for your /zombie/twilio POST method, click **Integration Response**. On the "Integration Response" screen, click the black arrow to expand the method response section. Expand the **Body Mapping Templates** section. You should see a Content-Type of "application/json". We need a Content-Type of XML, not JSON, so **delete this Content-Type by clicking the little black minus icon** and click **Delete** on the pop-up window. 25\. Click **Add mapping template** similar to the way you did this in the earlier steps for the Integration Request section. 26\. In the "Content-Type" text box, insert **application/xml** and click the little black checkmark to continue. Similar to the steps done earlier, we are going to copy VTL mapping logic to convert the response data to XML from JSON. This will result in your /zombie/twilio POST method responding to requests with XML format. After you have created the new content-type, a new section will appear below with a dropdown for **Generate Template**. Click that dropdown and select **Method Request Passthrough**. In the text editor, delete all the code already in there and copy the following into the editor: ``` #set($inputRoot = $input.path('$')) $inputRoot ``` Click the grey "Save" button to continue. The result should look like the screenshot below: ![Twilio Integration Response Mapping Template](/Images/Twilio-Step26.png) 27\. Scroll up and click the blue **Save** button on the screen. Finally click the **Actions** button on the left side of the API Gateway console and choose **Deploy API** to deploy your API. In the Deploy API window, select **ZombieWorkshopStage** from the dropdown and click **Deploy**. 28\. You are now ready to test out Twilio integration with your API. Send a text message to your Twilio phone number from your mobile device. **LAB 2 COMPLETE** If the integration was successful, you should receive a confirmation response text message and your text message you sent should display in the web app chat room as coming from your Twilio Phone Number. You have successfully integrated Twilio text message functionality with API Gateway. * **Troubleshooting tip**: If you are unable to send text messages, please ensure you are sending from the same phone number that you registered when you signed up for a survivor account in the Zombie Chat. If you review the TwilioProcessing Lambda function you will see that the code is checking the DynamoDB users table to confirm if the incoming message forward to us from Twilio was sent from an authorized phone number. Twilio provides that to us when it sends the message to our API. * **For international users**: If you have an international phone number and want to send text messages - 1. Modify your user record in the DynamoDB Users table with your correct International Phone Number. You need to do this in DynamoDB directly, because the JS chat application performs validation that requires a 10 digit US phone number on the client. After modifying this in DynamoDB, you should be able to send text messages to your Twilio phone number from your international phone number because the the Lambda phone number validation in the code will recognize your phone number. * * * ## Lab 3 - Search over the chat messages with Elasticsearch Service **What you'll do in this lab...** In this lab you'll launch an Elasticsearch Service cluster and setup DynamoDB Streams to automatically index chat messages in Elasticsearch for future ad hoc analysis of messages. **Elasticsearch Service Architecture** ![Overview of Elasticsearch Service Integration](/Images/ElasticsearchServiceOverview.png) 1\. Select the Amazon Elasticsearch icon from the main console page. 2\. Create a new Amazon Elasticsearch domain. Provide it a name such as "[Your CloudFormation stack name]-zombiemessages". Click **Next**. 3\. On the **Configure Cluster** page, leave the default cluster settings and click **Next**. 4\. For the access policy, select the **Allow or deny access to one or more AWS accounts or IAM users** option in the dropdown and fill in your account ID. Your AWS Account ID is actually provided to you in the examples section so just copy and paste it into the text box. Make sure **Allow** is selected for the "Effect" dropdown option. Click **OK**. 5\. Select **Next** to go to the domain review page. 6\. On the Review page, select **Confirm and create** to create your Elasticsearch cluster. 7\. The creation of the Elasticsearch cluster takes approximately 10 minutes. * Since it takes roughly 10 minutes to launch an Elasticsearch cluster, you can either wait for this launch before proceeding, or you can move on to Lab 4 and come back to finish this lab when the cluster is ready. 8\. Take note of the Endpoint once the cluster starts, we'll need that for the Lambda function. ![API Gateway Invoke URL](/Images/Search-Step8.png) 9\. Go into the Lambda service page by clicking on Lambda in the Management Console. 10\. Select **Create a Lambda Function**. 11\. On the Blueprints screen select **Blank Function** to create a Lambda function from scratch. 12\. In Configure Triggers section, select the DynamoDB event source type and then select the **messages** DynamoDB table. It should appear as **"[Your CloudFormation stack name]-messages"**. Then set the **Batch size** to **5**, the **Starting position** to **Latest** and select the checkbox **Enable trigger**. Then click on Next button. 13\. Give your function a name, such as **"[Your CloudFormation stack name]-ESsearch"**. Keep the runtime at the default. You can set a description for the function if you'd like. 14\. Paste in the code from the ZombieWorkshopSearchIndexing.js file provided to you. This is found in the Github repo in the "ElasticsearchLambda" folder. 15\. On [line 6](/ElasticSearchLambda/ZombieWorkshopSearchIndexing.js#L6) in the code provided, replace the **region** variable with the code for the region you are working in (the region you launched your stack, created your Lambda function etc). If you're working in Oregon region, then leave the code us-west-2 as is. Then on line 7, replace the **endpoint** variable that has a value of **ENDPOINT_HERE** with the Elasticsearch endpoint created in step 8\. **Make sure the endpoint you paste starts with https://**. * This step requires that your cluster is finished creating and in "Active" state before you'll have access to see the endpoint of your cluster. 16\. Now you'll add an execution role to your Lambda function which gives permissions for your Lambda function to access AWS resources. For the Role, select **Choose an existing role**, and for the Existing Role, select **"[Your CloudFormation stack name]-ZombieLabLambdaRole"** which is the role that was created for you for this workshop. It has permissions to the Elasticsearch service. 17\. Expand the "Advanced settings" section and find the "Timeout" field for your Lambda function. In the timeout field, change the function timeout to **1** minute. This ensures Lambda can process the batch of messages before Lambda times out. Keep all the other defaults on the page set as is. Select **Next** and then on the Review page, select **Create function** to create your Lambda function. 18\. In the above step, we configured [DynamoDB Streams](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) to capture incoming messages on the table and trigger a Lambda function to push them to our Elasticsearch cluster. Your messages posted in the chat from this point forward will be indexed to Elasticsearch. Post a few messages in the chat, at least 5 as configured in the DynamoDB Streams event source (batch size). You should be able to see that messages are being indexed in the "Indices" section for your cluster in the Elasticsearch Service console. ![API Gateway Invoke URL](/Images/Search-Done.png) **LAB 3 COMPLETE** If you would like to explore and search over the messages in the Kibana web UI that is provided with your cluster, you will need to navigate to the Elasticsearch domain you created and change the permissions. Currently you've configured the permissions so that only your AWS account has access. This allows your Lambda function to index messages into the cluster. To use the web UI to build charts and search over the index, you will need to implement an IP based policy to whitelist your computer/laptop/network or for simplicity, choose to allow everyone access. For instructions on how to modify the access policy of an ES cluster, visit [this documentation](http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-gsg-configure-access.html). If you choose to open access to anyone be aware that anyone can see your messages, so please be sure to restrict access back to your AWS account when you're done exploring Kibana, or simply delete your ES cluster. * * * ## Lab 4 - Slack Integration **What you'll do in this lab...** In this lab, you'll integrate a Slack channel with your survivor chat. There may be survivors who use different chat systems and you'll want to communicate with them! After completing this lab, survivors communicating on Slack can send messages to survivors in the Zombie Chat App by configuring a slash command prefix to be used on any messages in their Slack channel that they want to send to the survivors. When Slack users type messages with this Slash command, it will pass the message to your survivor chat API, similiar to the webhook functionality enabled in the Twilio lab! If you aren't familiar with Slack, they offer a free chat communications service that is popular, especially among the developer community. Slack uses a concept called "Channels" to distinguish different chat rooms. Visit their website to learn more! **Slack Integration Architecture** ![Overview of Slack Integration](/Images/SlackOverview.png) 1\. Go to [http://www.slack.com](http://www.slack.com) and create a username, as well as a team. If you want to use your existing Slack username and existing team, then proceed with that profile instead of creating a new one. 2\. Once logged into your Slack team, navigate to [https://slack.com/apps](https://slack.com/apps) which should direct you to the app directory for your team. In the search bar in the middle of the App Directory page, type **slash commands** and select it from the options. This will take you to the Slash Commands portal. 3\. On the Slash Commands page, click **Add configuration**. Slash commands allow you to define a command that you can use within Slack to trigger Slack to perform actions in an event driven manner. In this case we are going to configure a slash command to forward messages to an external source with a webhook. You'll configure your Slash Command to make a POST request to a /zombie/slack API resource you will soon be creating in API Gateway. 4\. On the Slash Commands configuration page, define a command in the **Commands** text box. Insert **/survivors** as your Slash Command. Then select "Add Slash Command Integration" to save it. 5\. On the Integration Settings page, scroll down to the **Method** configuration andmake sure the **Method** section has "POST" selected from the dropdown options. Then scroll to the **Token** section and copy the Token (or generate a new one) to a text file as you'll need it in the following steps. 6\. Keep the Slack browser tab open and in another tab navigate to the AWS Lambda management console in the AWS Management Console. 7\. Click **Create a Lambda function**. You'll create a Lambda function to parse incoming Slack messages and send them to the Chat Service. 8\. On the Blueprints page select **Blank Function** to create a function from scratch. Also skip past the triggers page by selecting **Next**. 9\. Give your function a name such as **"[Your CloudFormation Stack name]-SlackService"**. For the Nodejs version, you can keep the default Nodejs version selected. Now navigate to the GitHub repo for this workshop, or the location where you downloaded the GitHub files to your local machine. 10\. Open the **SlackService.js** file from the GitHub repo, found in the slack folder. Copy the entire contents of this js file into the Lambda inline edit window. * This SlackService function will serve as the backend for a new /zombie/slack API resource you will create later. This function accepts incoming messages forwarded from Slack when you use the slash command, it then reformats the parameters and proxies the Slack messages to the zombie survivor chat service (/zombi/message) . This Lambda function verifies that the incoming message has the predefined Slack Token, and it also does a DynamoDB query against the Users table to validate that the user who submitted the message in Slack is a preconfigured survivor in our backend (Remember when you signed up for the chat, you provided your Slack username and team domain as part of the sign-up process). In this workshop, we're using this is as the way to authorize requests against the /zombie/slack resource. 11\. You should have saved the Slack Token string from earlier. Copy the Token string from Slack into the "token" variable on [line 15](/Slack/SlackService.js#L15) in the Lambda function, replacing the string **INSERT YOUR TOKEN FROM SLACK HERE** with your own token. * Slack provides a unique token associated with your integration. You are copying this token into your Lambda function as a form of validation. When incoming requests from Slack are sent to your API endpoint, and your Lambda function is invoked with the Slack payload, your Lambda function will check to verify that the incoming Token in the request matches the Token you provided in the code. If the token does not match, Lambda returns an error and doesn't process the request. 12\. There are 4 variables you need to insert in the code to communicate with the backend. a) In the "API" variable, you will insert the fully qualified domain name (FQDN) for your API. The **API.endpoint** variable should show a value of "INSERT YOUR API GATEWAY FQDN HERE INCLUDING THE HTTPS://" on [line 9](/Slack/SlackService.js#L9). Your final FQDN inserted into the code should look something like "https://xxxxxxxx.execute-api.us-west-2.amazonaws.com". This allows the SlackService function to communicate with your API. b) You should also fill in the region code in the variable **API.region**. This should be the region where you launched CloudFormation. c) Finally you will also copy in the name of your DynamoDB Users table that was created for you. This should be placed in the **table** variable. You will also need to copy in the name of your "slackindex" (this is an index that was created on the DynamoDB table to assist with querying). These attributes can be found in the Outputs section in CloudFormation. You should be copying the values for **DynamoDBUsersTableName** and **DynamoDBUsersSlackIndex** from CloudFormation. 13\. After you have copied the code into the Lambda inline code console and modified the variables, scroll down to the **Lambda function handler and role** section. For the role, select **Choose an existing role** from the dropdown and then select the role that looks like **[Your stack name]-ZombieLabLambdaRole...**. For simplicity we are reusing the same Lambda role for our functions. 14\. In the Advanced Settings, set the **Timeout** to **30** seconds. Then click **Next**. 15\. On the review page, make sure that everything looks correct. 16\. Click **Create function**. Your Lambda function will be created. 17\. When the function is created, navigate to the API Gateway service in the AWS Management Console. Click into your "Zombie Workshop API Gateway" API. On the left Resources pane, click/highlight the "/zombie" resource so that it is selected. Then select the **Actions** button and choose "Create Resource". For Resource Name, insert **slack** and for Resource Path, insert **slack**. Click "Create Resource" to create your slack API resource. The final resource for your Slack API should be as shown below. ![Create Slack API Resource](/Images/Slack-Step17.png) * In this step, you are creating a new API resource that the Slack slash command webhook can forward requests to. In the next steps, you'll create a POST method associated with this resource that triggers your Lambda function. When you type messages in Slack with the correct slash command, Slack will send requests to this resource, which will invoke your SlackService Lambda function to pre-process the payload and make a call to your /zombie/message endpoint to insert the data into DynamoDB. 18\. For your newly created "/slack" resource, highlight it, then click **Actions** and select **Create Method** to create the **POST** method for the /zombie/slack resource. In the dropdown, select **POST**. Click the checkmark to create the POST method. On the Setup page, choose an Integration Type of **Lambda Function**, and select the region that you are working in for the region dropdown. For the Lambda Function field, type "SlackService" for the name of the Lambda Function. It should autofill your function name. Click **Save** and then **OK** to confirm. 19\. Click **Integration Request** for the /slack POST method. We'll create a Mapping Template to convert the incoming query string parameters from Slack into JSON which is the format Lambda requires for parameters. This mapping template is required so that the incoming Slack message can be converted to the right format. 20\. Expand the **Body Mapping Templates** arrow and click **Add mapping template**. In the Content-Type box, enter **application/x-www-form-urlencoded** and click the little checkmark to continue. If a popup appears asking if you would like to secure the integration, click **Yes, secure this integration**. This ensures that only requests with the defined content-types will be allowed. As you did in the Twilio lab, we're going to copy VTL mapping logic to convert the request to JSON. A new section will appear on the right side of the screen with a dropdown for **Generate Template**. Click that dropdown and select **Method Request Passthrough**. In the text editor, delete all of the exiting VTL code and copy the following into the editor: ``` {"body": $input.json("$")} ``` Click the grey **Save** button to continue. The result should look like the screenshot below: ![Slack Integration Response Mapping Template](/Images/Slack-Step20.png) 21\. Click the **Actions** button on the left side of the API Gateway console and select **Deploy API** to deploy your API. In the Deploy API window, select **ZombieWorkshopStage** from the dropdown and click **Deploy**. 22\. On the left pane navigation tree, expand the ZombieWorkshopStage tree. Click the **POST** method for the **/zombie/slack** resource. You should see an Invoke URL appear for that resource as shown below. ![Slack Resource Invoke URL](/Images/Slack-Step22.png) 23\. Copy the entire Invoke URL. Navigate back to the Slack.com website to the Slash Command setup page and insert the Slack API Gateway Invoke URL you just copied into the "URL" textbox. Make sure to copy the entire url including "HTTPS://". Scroll to the bottom of the Slash Command screen and click **Save Integration**. 24\. You're ready to test out the Slash Command integration. In the team chat channel for your Slack account, type the Slash Command "/survivors" followed by a message. For example, type "/survivors Please help me I am stuck and zombies are trying to get me!". After sending it, you should get a confirmation response message from Slack Bot like the one below: ![Slack Command Success](/Images/Slack-Step24.png) **LAB 4 COMPLETE** Navigate to your zombie survivor chat app and you should see the message from Slack appear. You have configured Slack to send messages to your chat app! ![Slack Command in Chat App](/Images/Slack-Step25.png) **Bonus Step:** You've configured Slack to forward messages to your zombie survivor chat app. But can you get messages sent in the chat app to appear in your Slack chat (i.e.: the reverse)? Give it a try or come back and attempt it later when you've finished the rest of the labs! HINT: You'll want to configure Slack's "Incoming Webhooks" integration feature along with a Lambda code configuration change to make POST requests to the Slack Webhook whenever users send messages in the chat app! * * * ## Lab 5 - Motion Sensor Integration with Intel Edison and Grove In this section, you'll help protect suvivors from zombies. Zombie motion sensor devices allow communities to determine if zombies (or intruders) are nearby. You'll setup a Lambda function to consume motion sensor events from an IoT device and push the messages into your chat application. **IoT Integration Architecture** ![Zombie Sensor IoT Integration](/Images/EdisonOverview.png) If you wish to utilize the Zombie Sensor as a part of the workshop, this guide will walk you through the following: * Items required to create the physical Zombie sensor (Ignore this step if a zombie sensor is provided as a part of an AWS workshop) * How to create the AWS backend (Simple Notification Service Topic) for the Zombie Sensor * How to install the Node.js device code provided in this workshop onto the device **Please note that this section requires an IoT device that can emit messages to SNS. If you are setting this up on your own device outside of the workshop, please proceed through the sections below to do that, otherwise skip the device setup instructions as the device has been setup by AWS for you by the workshop instructor.** **Items Required** 1\. One Intel® Edison and Grove IoT Starter Kit Powered by AWS. This can be purchased [here](http://www.amazon.com/gp/product/B0168KU5FK?*Version*=1&*entries*=0). 2\. Within this starter kit you will be using the following components for this exercise: * Intel® Edison for Arduino * Base Shield * USB Cable; 480mm-Black x1 * USB Wall Power Supply x1 * Grove - PIR Motion Sensor: The application code is a very simple app that publishes a message to an Amazon Simple Notification Service (SNS) topic when motion is detected on the Grove PIR Motion Sensor. For the purpose of a workshop, this should be done only once in a central account by the workshop organizer - the SNS topic will be made public so that participants can subscribe to this topic and make use of it during the workshop. An example output message from the Intel Edison: ``` {"message":"A Zombie has been detected in London!", "value":"1", "city":"London", "longtitude":"-0.127758", "lattitude":"51.507351"} ``` A simple workflow of this architecture is: Intel Edison -> SNS topic -> Your AWS Lambda functions subscribed to the topic. ####Creating the AWS Backend **If you are following this guide during a workshop presented by AWS, please ignore the steps below, 1-3\. An SNS topic should already be configured for the workshop participants to consume messages from. That SNS topic ARN will be provided to you.** 1\. Create the SNS Topic. Navigate to the SNS product page within the AWS Management Console and click **Topics** in the left hand menu. Then click on 'Create New Topic'. You will be presented with the following window. Fill in the fields with your desired values and click create topic. ![Create Topic Screenshot](/Images/MotionSensor-createTopic.png) 2\. You will now need to edit the topic policy to permit any AWS account to subscribe lambda functions to your SNS topic. Select the check box next to your new topic, and then click **Actions -> Edit topic policy**. You need to configure these settings presented as shown the below screenshot. Then click **Update Policy**. This part is what allows others (perhaps teammates working on this lab with you, to consume notifications from your SNS topic. ![Edit Topic Policy Screenshot](/Images/MotionSensor-createTopicPolicy.png) 3\. You now have your central SNS topic configured and ready to use. Ensure that you make a note of the Topic ARN and region where you have created the topic, you will need it in some of the following steps. ####Installing the application on the Intel Edison **If you are following this guide during a workshop presented by AWS, please ignore this section. An Intel Edison board should already be configured for the workshop particants to consume messages from.** 1\. First, you will need to get your Edison board set up. You can find a getting started guide for this on the Intel site [here](https://software.intel.com/en-us/articles/assemble-intel-edison-on-the-arduino-board). Note that for the purpose of this tutorial, we will be writing our client code for the Edison in Node.js and will therefore be using the Intel® XDK for IoT (referred to as 'XDK' from here on, and which you will need to install) as our IDE. 2\. You will need to physically connect the Grove PIR Motion Sensor to pin D6 on the breakout board. 3\. Download all of the code from the 'zombieIntelEdisonCode' folder in the GitHub repository and store it in a folder locally on your machine. This simply consists of a main.js file (our application) and our package.json (our app dependencies). 4\. Navigate to the homepage in the XDK and start a new project. 5\. Choose to import an existing Node.js project and select the folder where you stored the code from this repository in the previous step. 6\. Give your project a name. We called ours **zombieSensor**. 7\. You now need to edit the code in main.js to include your AWS credentials and the SNS topic that you have created. Firstly, we'll need some AWS credentials. 8\. You will need to create an IAM User with Access and Secret Access Keys for your Edison to publish messages to your SNS topic. There is a guide on how to create IAM Users [here](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html). Your IAM policy for the user should look like the following: ``` { "Version": "2012-10-17", "Statement": [{ "Action": [ "sns:Publish" ], "Effect": "Allow", "Resource": "ENTER YOUR SNS TOPIC ARN HERE" }] } ``` 9\. Now let's add your credentials to the client side code. Edit the following line in main.js to include your user access keys and the region where you have set up your SNS topic. ``` AWS.config.update({accessKeyId: 'ENTER ACCESSKEY HERE', secretAccessKey: 'ENTER SECRET ACCESS KEY HERE', region: 'ENTER REGION HERE'}); ``` 10\. Edit the following line in main.js to reflect the region in which you created the SNS topic. ``` var sns = new AWS.SNS({region: 'ENTER REGION HERE'}); ``` 11\. Edit the following line in main.js to reflect the Amazon Resource Name (ARN) of the SNS topic that you created earlier. ``` TopicArn: "ENTER YOUR SNS TOPIC ARN HERE" ``` 12\. You now need to connect the XDK to your Intel Edison device. There is a guide on the Intel site on how to do this [here](https://software.intel.com/en-us/getting-started-with-the-intel-xdk-iot-edition) under the 'Connect to your Intel® IoT Platform' section. 13\. You now need to build the app and push it to your device. First, hit the build/install icon, this looks like a hammer in the XDK. It may take a couple of minutes to install the required packages etc. 14\. Once the app has been built succesfully, you can run the app by pressing the run icon, this looks like a circuit board with a green 'play' sign. 15\. Your app should now be running on the Edison device and your messages being published to the SNS topic. You can consume these messages using AWS Lambda. There is some documentation to get you started [here](http://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html). Continue below to learn how to integrate the SNS notifications into the chat application. ####Consuming the SNS Topic Messages with AWS Lambda Using the things learned in this workshop, can you develop a Lambda function that alerts survivors in the chat application when zombies are detected from the zombie sensor? In this section you will configure a Lambda function that triggers when messages are sent from the Edison device to the zombie sensor SNS topic. This function will push the messages to the chat application to notify survivors of zombies! 1\. Open up the Lambda console and click **Create a Lambda function**. 2\. On the blueprints screen, click **Skip** as we won't use one. 3\. On the next page (**Configure Triggers**), click the empty field next to the AWS Lambda logo and select SNS as an event source. ![Setup SNS as an Event Trigger for Lambda](/Images/Sensor-Step3.png) * For the SNS topic selection, either select the SNS topic from the dropdown you created earlier (if you're working on this outside of an AWS workshop) or if you are working in an AWS workshop, insert the shared SNS topic ARN provided to you by the organizer. Make sure the trigger checkbox option is set to enabled so that your Lambda function will immediately begin processing messages. Click **Next**. * The SNS Topic ARN provided by AWS (if in a workshop) is not in your AWS account and will not display in your dropdown of choices. It is an ARN provided by AWS in a separate account and needs to be typed in. 4\. On the "Configure Function" screen, name your function "[Your CloudFormation Stack Name]-sensor". Now open the **exampleSNSFunction.js** file from the workshop GitHub repository. It is located [here](/zombieSensor/lambda/exampleSNSFunction.js). Copy the entire contents of this JS file into the empty Lambda code editor. When you've copied the code into the Lambda browser editor, locate the variable **API**. Replace the variable **API.endpoint** with your /zombie/message/post endpoint. It should look like **https://xxxxxxxx.execute-api.us-west-2.amazonaws.com**. This is the "Invoke URL" which you can grab from the Stages page in the API Gateway console. Remember, don't insert anything after the ".com" portion, the function fills in the rest of the resource path for you. You also should insert the region for your API in the **API.region** variable. 5\. For the **Role**, leave the option as **Choose an existing role**. Then in the "Existing Role" dropdown, select the ZombieLabLambdaRole that was created for you by CloudFormation. It should look like "[Your CloudFormation stack name]-ZombieLabLambdaRole". 6\. Set the **Timeout** to **30** seconds. Leave all other options as default on the Lambda creation page and click **Next**. 7\. On the Review page, click **Create function**. 8\. That's it! When your function is created, head on over to your survivor chat application. If your session has expired you may need to login again. * Almost immediately you should begin seeing zombie sensor messages showing up in the chat application which means your messages are successfully sending from the Intel Edison device to the Zombie Sensor SNS Topic. Any survivors with Lambda functions subscribed to this topic will get notifications in their team's survivor chat service. * This Lambda Function takes the zombie sensor message from SNS, parses it, and makes an AWS SigV4 signed HTTPS POST request to your API Gateway message endpoint. That endpoint inserts the record into DynamoDB as a message making it available to the application on subsequent poll requests. ## Workshop Cleanup 1\. To cleanup your environment, it is recommended to first delete these manual resources you created in the labs before deleting your CloudFormation stack, as there may be resource dependencies that stop the Stack from deleting. Follow steps 2-6 before deleting your Stack. 2\. Be sure to delete the TwilioProcessing Lambda Function. Also if you no longer plan to use Twilio, please delete your Twilio free trial account and/or phone numbers that you provisioned. 3\. Be sure to delete the Elasticsearch cluster and the associated Lambda function that you created for the Elasticsearch lab. Also delete the IAM role you created for the Elasicsearch Lambda function, "ZombieLabLambdaDynamoESRole". 4\. Be sure to delete the Lambda function created as a part of the Slack lab and the Slack API resource you created. Also delete Slack if you no longer want an account with them. 5\. Be sure to delete the SNS topic (if you created one) and the Lambda function that you created in the Zombie Sensor lab. 6\. Delete the Cognito User Pool and Identity Pool associated with your application, that you created during lab setup. * User Pool: Click into your User Pool and click the "Delete pool" button to delete your user pool. * Identity Pool: Click into the Federated Identities page of Cognito and find your identity pool ([stackname]-identitypool). Then click **Edit identity pool**. Scroll to the bottom and delete the identity pool. 7\. Navigate to CloudWatch Logs and make sure to delete unnecessary Log Groups if they exist. 8\. Once those resources have been deleted, go to the CloudFormation console and find the Stack that you launched in the beginning of the workshop, select it, and click **Delete Stack**. * When the stack has been successfully deleted, it should no longer display in the list of Active stacks. If you run into any issues deleting stacks, please notify a workshop instructor or contact [AWS Support](https://console.aws.amazon.com/support/home) for additional assistance. * * * ## Appendix * Channel Challenge: Currently all messages sent in the survivor app are saved in the database with a channel of 'default' - all survivors can see these messages. Your challenge is to modify the application so that users have the option to scope their messages to only display to survivors in the same "Camp" (Camp is an attribute that is collected from users when they sign up for a user account). You will need to modify the JS application as well as the backend messages database and Lambda functions to work with this "Camp" attribute instead of the existing 'channel' attribute. ================================================ FILE: S3WebApp/S3/app.js ================================================ var app = angular.module("chatApp", ['ui.router', 'ngResource', 'ngMessages', 'chatApp.signin', 'chatApp.signup', 'chatApp.confirm', 'chatApp.chat', 'chatApp.chatPanel', 'chatApp.talkersPanel', 'chatApp.chatMessages'] ); app.config(function($stateProvider, $urlRouterProvider) { AWSCognito.config.region = COGNITO_REGION; AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: IDENTITY_POOL_ID }); AWSCognito.config.update({accessKeyId: 'anything', secretAccessKey: 'anything'}) var creds = new AWS.CognitoIdentityCredentials({ IdentityPoolId: IDENTITY_POOL_ID }); AWS.config.region = COGNITO_REGION; AWS.config.credentials = creds; $stateProvider .state('signin', { url: '/signin', views: { '' : { templateUrl: 'modules/signin/signin.html', controller: 'SigninCtrl' } } }) .state('signup', { url: '/signup', views: { '' : { templateUrl: 'modules/signup/signup.html', controller: 'SignupCtrl' } } }) .state('confirm', { url: '/confirm', views: { '' : { templateUrl: 'modules/confirm/confirm.html', controller: 'ConfirmCtrl' } } }) .state('chat', { url: '/chat', views: { '' : { templateUrl: 'modules/chat/chat.html', controller: 'ChatCtrl' }, 'chatPanel@chat' : { templateUrl: 'modules/chat/chatPanel.html', controller: 'chatPanelCtrl' }, 'talkersPanel@chat' : { templateUrl: 'modules/chat/talkersPanel.html', controller: 'talkersPanelCtrl' }, 'chatMessages@chat' : { templateUrl: 'modules/chat/chatMessages.html', controller: 'chatMessageCtrl' } } }); $urlRouterProvider.otherwise('/signin'); }); var apigClientFactory = {}; apigClientFactory.newClient = function (config) { var apigClient = { }; if(config === undefined) { config = { accessKey: '', secretKey: '', sessionToken: '', region: '', apiKey: undefined, defaultContentType: 'application/json; charset=UTF-8', defaultAcceptType: 'application/json; charset=UTF-8' }; } if(config.accessKey === undefined) { config.accessKey = ''; } if(config.secretKey === undefined) { config.secretKey = ''; } if(config.apiKey === undefined) { config.apiKey = ''; } if(config.sessionToken === undefined) { config.sessionToken = ''; } if(config.region === undefined) { config.region = AWS_REGION; } //If defaultContentType is not defined then default to application/json if(config.defaultContentType === undefined) { config.defaultContentType = 'application/json; charset=UTF-8'; } //If defaultAcceptType is not defined then default to application/json if(config.defaultAcceptType === undefined) { config.defaultAcceptType = 'application/json; charset=UTF-8'; } // extract endpoint and path from url var invokeUrl = MESSAGES_ENDPOINT; var endpoint = /(^https?:\/\/[^\/]+)/g.exec(invokeUrl)[1]; var pathComponent = invokeUrl.substring(endpoint.length); var sigV4ClientConfig = { accessKey: config.accessKey, secretKey: config.secretKey, sessionToken: config.sessionToken, serviceName: 'execute-api', region: config.region, endpoint: endpoint, defaultContentType: config.defaultContentType, defaultAcceptType: config.defaultAcceptType }; var authType = 'NONE'; if (sigV4ClientConfig.accessKey !== undefined && sigV4ClientConfig.accessKey !== '' && sigV4ClientConfig.secretKey !== undefined && sigV4ClientConfig.secretKey !== '') { authType = 'AWS_IAM'; } var simpleHttpClientConfig = { endpoint: endpoint, defaultContentType: config.defaultContentType, defaultAcceptType: config.defaultAcceptType }; var apiGatewayClient = apiGateway.core.apiGatewayClientFactory.newClient(simpleHttpClientConfig, sigV4ClientConfig); apigClient.zombieMessageGet = function (params, body, additionalParams) { if(additionalParams === undefined) { additionalParams = {}; } apiGateway.core.utils.assertParametersDefined(params, [], ['body']); var zombieMessageGetRequest = { verb: 'get'.toUpperCase(), path: pathComponent + uritemplate('/zombie/message').expand(apiGateway.core.utils.parseParametersToObject(params, [])), headers: apiGateway.core.utils.parseParametersToObject(params, []), queryParams: apiGateway.core.utils.parseParametersToObject(params, []), body: body }; return apiGatewayClient.makeRequest(zombieMessageGetRequest, authType, additionalParams, config.apiKey); }; apigClient.zombieMessagePost = function (params, body, additionalParams) { if(additionalParams === undefined) { additionalParams = {}; } apiGateway.core.utils.assertParametersDefined(params, [], ['body']); var zombieMessagePostRequest = { verb: 'post'.toUpperCase(), path: pathComponent + uritemplate('/zombie/message').expand(apiGateway.core.utils.parseParametersToObject(params, [])), headers: apiGateway.core.utils.parseParametersToObject(params, []), queryParams: apiGateway.core.utils.parseParametersToObject(params, []), body: body }; return apiGatewayClient.makeRequest(zombieMessagePostRequest, authType, additionalParams, config.apiKey); }; apigClient.zombieMessageOptions = function (params, body, additionalParams) { if(additionalParams === undefined) { additionalParams = {}; } apiGateway.core.utils.assertParametersDefined(params, [], ['body']); var zombieMessageOptionsRequest = { verb: 'options'.toUpperCase(), path: pathComponent + uritemplate('/zombie/message').expand(apiGateway.core.utils.parseParametersToObject(params, [])), headers: apiGateway.core.utils.parseParametersToObject(params, []), queryParams: apiGateway.core.utils.parseParametersToObject(params, []), body: body }; return apiGatewayClient.makeRequest(zombieMessageOptionsRequest, authType, additionalParams, config.apiKey); }; apigClient.zombieTalkersGet = function (params, body, additionalParams) { if(additionalParams === undefined) { additionalParams = {}; } apiGateway.core.utils.assertParametersDefined(params, [], ['body']); var zombieTalkersGetRequest = { verb: 'get'.toUpperCase(), path: pathComponent + uritemplate('/zombie/talkers').expand(apiGateway.core.utils.parseParametersToObject(params, [])), headers: apiGateway.core.utils.parseParametersToObject(params, []), queryParams: apiGateway.core.utils.parseParametersToObject(params, []), body: body }; return apiGatewayClient.makeRequest(zombieTalkersGetRequest, authType, additionalParams, config.apiKey); }; apigClient.zombieTalkersPost = function (params, body, additionalParams) { if(additionalParams === undefined) { additionalParams = {}; } apiGateway.core.utils.assertParametersDefined(params, [], ['body']); var zombieTalkersPostRequest = { verb: 'post'.toUpperCase(), path: pathComponent + uritemplate('/zombie/talkers').expand(apiGateway.core.utils.parseParametersToObject(params, [])), headers: apiGateway.core.utils.parseParametersToObject(params, []), queryParams: apiGateway.core.utils.parseParametersToObject(params, []), body: body }; return apiGatewayClient.makeRequest(zombieTalkersPostRequest, authType, additionalParams, config.apiKey); }; apigClient.zombieTalkersOptions = function (params, body, additionalParams) { if(additionalParams === undefined) { additionalParams = {}; } apiGateway.core.utils.assertParametersDefined(params, [], ['body']); var zombieTalkersOptionsRequest = { verb: 'options'.toUpperCase(), path: pathComponent + uritemplate('/zombie/talkers').expand(apiGateway.core.utils.parseParametersToObject(params, [])), headers: apiGateway.core.utils.parseParametersToObject(params, []), queryParams: apiGateway.core.utils.parseParametersToObject(params, []), body: body }; return apiGatewayClient.makeRequest(zombieTalkersOptionsRequest, authType, additionalParams, config.apiKey); }; /* apigClient.zombieTwilioPost = function (params, body, additionalParams) { if(additionalParams === undefined) { additionalParams = {}; } apiGateway.core.utils.assertParametersDefined(params, [], ['body']); var zombieTwilioPostRequest = { verb: 'post'.toUpperCase(), path: pathComponent + uritemplate('/zombie/twilio').expand(apiGateway.core.utils.parseParametersToObject(params, [])), headers: apiGateway.core.utils.parseParametersToObject(params, []), queryParams: apiGateway.core.utils.parseParametersToObject(params, []), body: body }; return apiGatewayClient.makeRequest(zombieTwilioPostRequest, authType, additionalParams, config.apiKey); }; */ return apigClient; }; var compareTo = function() { return { require: "ngModel", scope: { otherModelValue: "=compareTo" }, link: function(scope, element, attributes, ngModel) { ngModel.$validators.compareTo = function(modelValue) { return modelValue == scope.otherModelValue; }; scope.$watch("otherModelValue", function() { ngModel.$validate(); }); } }; }; app.directive("compareTo", compareTo); ================================================ FILE: S3WebApp/S3/assets/css/zombie.css ================================================ body{ width:100%; height:100%; position:static; background-repeat: no-repeat; background: black; font-family: 'Roboto', sans-serif; color:gray; /*min-width:895px;*/ } html { position: relative; min-height: 100%; background: black; overflow-y: scroll; } h1, h2, h3, h4, h5, h6 { color: #f1f2f7; font-family: 'Roboto', sans-serif; margin: 10px 0; font-weight: 300; } h1 { line-height: 48px; font-size: 36px; } h2 { line-height: 36px; font-size: 24px; } h3 { line-height: 30px; font-size: 21px; } h4 { line-height: 22px; font-size: 18px; } h5 { font-size: 18px; font-size: 16px; } h5 { font-size: 16px; font-size: 14px; } blockquote { border-left: 5px solid #13dafe !important; border: 1px solid rgba(120, 130, 140, 0.13); } p { line-height: 1.6; } b { font-weight: 600; } a:hover { outline: 0; text-decoration: none; } a:active { outline: 0; text-decoration: none; } a:focus { outline: 0; text-decoration: none; } .clear { clear: both; } .font-12 { font-size: 12px; } hr { border-color: rgba(120, 130, 140, 0.13); } .b-t { border-top: 1px solid rgba(120, 130, 140, 0.13); } .b-b { border-bottom: 1px solid rgba(120, 130, 140, 0.13); } .b-l { border-left: 1px solid rgba(120, 130, 140, 0.13); } .b-r { border-right: 1px solid rgba(120, 130, 140, 0.13); } .b-all { border: 1px solid rgba(120, 130, 140, 0.13); } .b-none { border: 0px!important; } .max-height { height: 310px; overflow: auto; } .p-0 { padding: 0px !important; } .p-10 { padding: 10px !important; } .p-20 { padding: 20px !important; } .p-30 { padding: 30px !important; } .p-l-0 { padding-left: 0px !important; } .p-l-10 { padding-left: 10px !important; } .p-l-20 { padding-left: 20px !important; } .p-r-0 { padding-right: 0px !important; } .p-r-10 { padding-right: 10px !important; } .p-r-20 { padding-right: 20px !important; } .p-t-0 { padding-top: 0px !important; } .p-t-10 { padding-top: 10px !important; } .p-t-20 { padding-top: 20px !important; } .p-b-0 { padding-bottom: 0px !important; } .p-b-10 { padding-bottom: 10px !important; } .p-b-20 { padding-bottom: 20px !important; } .m-0 { margin: 0px !important; } .m-l-5 { margin-left: 5px !important; } .m-l-10 { margin-left: 10px !important; } .m-l-15 { margin-left: 15px !important; } .m-l-20 { margin-left: 20px !important; } .m-l-30 { margin-left: 30px !important; } .m-l-40 { margin-left: 40px !important; } .m-r-5 { margin-right: 5px !important; } .m-r-10 { margin-right: 10px !important; } .m-r-15 { margin-right: 15px !important; } .m-r-20 { margin-right: 20px !important; } .m-r-30 { margin-right: 30px !important; } .m-r-40 { margin-right: 40px !important; } .m-t-5 { margin-top: 5px !important; } .m-t-0 { margin-top: 0px !important; } .m-t-10 { margin-top: 10px !important; } .m-t-15 { margin-top: 15px !important; } .m-t-20 { margin-top: 20px !important; } .m-t-30 { margin-top: 30px !important; } .m-t-40 { margin-top: 40px !important; } .m-b-0 { margin-bottom: 0px !important; } .m-b-5 { margin-bottom: 5px !important; } .m-b-10 { margin-bottom: 10px !important; } .m-b-15 { margin-bottom: 15px !important; } .m-b-20 { margin-bottom: 20px !important; } .m-b-30 { margin-bottom: 30px !important; } .m-b-40 { margin-bottom: 40px !important; } #square { position:absolute; z-index:-1; width:100%; background-color:black; height:80px; } #zombie-logo { float:left; padding-top:4px; } #main-header { text-align:left; color:black; font-size: 2.6em; padding-top:12px; display:inline; width:60%; float:left; } #logo { padding-top:15px; padding-right:10%; float:right; } #wrapper { padding-left: 3em; padding-right:3em; } #chat-toggle{ border:none; background-color:rgb(102,0,0); color:white; display:inline; } #chat-body { overflow-y: scroll; height:400px; background-color:#2a2a2a; border-style:solid; border-width: 1px; border-color:#414141; } #talkers-body { font-family: 'Roboto', sans-serif; } #name-input { background-color:#2a2a2a; border-style:solid; border-width: 1px; border-color:#414141; } p {display:inline;} #username { float:none; clear:both; padding-top:3em; padding-left:1em; padding-right:1em; padding-bottom:1.5em; } /*.form-group { padding: 1em;}*/ .panel-footer { background-color:transparent; } #chat-message-input { background-color:#2a2a2a; border-style:solid; border-width: 1px; border-color:#414141; } #chat-message-input::-webkit-input-placeholder { font-style:italic; } ::-webkit-scrollbar { background-color:#2a2a2a; } #name-input::-webkit-input-placeholder { font-style:italic; } .mainLoginInput:-moz-placeholder { font-style:italic; } input::-webkit-input-placeholder { background-color:#272727; } /* signin and signup */ #wrapper { width: 100%; height:100%; } .login-register { background: transparent url("../images/signalcorps.png") no-repeat scroll; /* transparent url("../images/zombie-login.jpg") no-repeat scroll center center / cover !important; */ height: 100%; float: left; } .login-signin { background: transparent url("../images/signalcorps.png") no-repeat scroll; /* background: transparent url("../images/title.png") no-repeat scroll; */ height: 100%; float: left; } .login-box { height: 100%; background: black none repeat scroll 0% 0%; float: right; width: 420px; } .white-box { background: black none repeat scroll 0% 0%; padding: 15px; margin-bottom: 20px; } .white-box h3 { margin: 0px 0px 12px; font-weight: 500; } .login-box .footer { width: 100%; left: 0px; right: 0px; } .footer { background: black none repeat scroll 0% 0%; color: #58666E; left: 0px; padding: 20px 30px; position: absolute; right: 0px; } .form-control { background-color: #272727; height: 38px; max-width: 100%; padding: 7px 12px; color: #f1f2f7; transition: all 300ms linear 0s; } .help-block { margin-bottom: 0px; } /*Phone*/ @media (max-width: 767px) { .login-box { max-width: 420px; width: 100%; } } ================================================ FILE: S3WebApp/S3/assets/js/aws-cognito-sdk.js ================================================ amazon-cognito-identity-js/aws-cognito-sdk.js at master · aws/amazon-cognito-identity-js · GitHub
Skip to content
Find file
0f28830 Apr 19, 2016
12230 lines (9932 sloc) 351 KB
// AWS SDK for JavaScript v2.3.4
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt
(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var AWS = require('./core');
AWS.apiLoader = function(svc, version) {
return AWS.apiLoader.services[svc][version];
};
AWS.apiLoader.services = {};
AWS.XML.Parser = require('./xml/browser_parser');
require('./http/xhr');
if (typeof window !== 'undefined') window.AWSCognito = AWS;
if (typeof module !== 'undefined') module.exports = AWS;
if (typeof self !== 'undefined') self.AWSCognito = AWS;
AWS.apiLoader.services['cognitoidp'] = {};
var AWSCognito = require('./core');
AWSCognito.CognitoIdentityServiceProvider = AWS.Service.defineService('cognitoidp', [ '2016-04-18' ]);
AWS.apiLoader.services['cognitoidp']['2016-04-18'] = {"version":"2.0","metadata":{"apiVersion":"2016-04-18","endpointPrefix":"cognito-idp","jsonVersion":"1.1","protocol":"json","serviceFullName":"AWSCognitoIdentityProviderService","signatureVersion":"v4","targetPrefix":"AWSCognitoIdentityProviderService"},"operations":{"AddCustomAttributes":{"input":{"type":"structure","required":["UserPoolId","CustomAttributes"],"members":{"UserPoolId":{},"CustomAttributes":{"type":"list","member":{"shape":"S4"}}}},"output":{"type":"structure","members":{}},"http":{}},"AdminConfirmSignUp":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}},"http":{}},"AdminDeleteUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"http":{}},"AdminDeleteUserAttributes":{"input":{"type":"structure","required":["UserPoolId","Username","UserAttributeNames"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"UserAttributeNames":{"shape":"Sh"}}},"output":{"type":"structure","members":{}},"http":{}},"AdminDisableUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}},"http":{}},"AdminEnableUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}},"http":{}},"AdminGetUser":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","required":["Username"],"members":{"Username":{"shape":"Sd"},"UserAttributes":{"shape":"Sq"},"UserCreateDate":{"type":"timestamp"},"UserLastModifiedDate":{"type":"timestamp"},"Enabled":{"type":"boolean"},"UserStatus":{},"MFAOptions":{"shape":"Sv"}}},"http":{}},"AdminResetUserPassword":{"input":{"type":"structure","required":["UserPoolId","Username"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{}},"http":{}},"AdminSetUserSettings":{"input":{"type":"structure","required":["UserPoolId","Username","MFAOptions"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"MFAOptions":{"shape":"Sv"}}},"output":{"type":"structure","members":{}},"http":{}},"AdminUpdateUserAttributes":{"input":{"type":"structure","required":["UserPoolId","Username","UserAttributes"],"members":{"UserPoolId":{},"Username":{"shape":"Sd"},"UserAttributes":{"shape":"Sq"}}},"output":{"type":"structure","members":{}},"http":{}},"Authenticate":{"input":{"type":"structure","required":["ClientId","Username","PasswordClaim"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"},"PasswordClaim":{"type":"structure","members":{"SecretBlock":{"type":"blob"},"Signature":{"type":"blob"}},"sensitive":true},"Timestamp":{"type":"timestamp"}}},"output":{"type":"structure","members":{"AuthenticationResult":{"shape":"S1a"},"AuthState":{"shape":"S1d"},"CodeDeliveryDetails":{"shape":"S1e"}}},"http":{}},"ChangePassword":{"input":{"type":"structure","required":["PreviousPassword","ProposedPassword"],"members":{"PreviousPassword":{"shape":"S1g"},"ProposedPassword":{"shape":"S1g"},"AccessToken":{"shape":"S1b"}}},"output":{"type":"structure","members":{}},"http":{}},"ConfirmForgotPassword":{"input":{"type":"structure","required":["ClientId","Username","ConfirmationCode","Password"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"},"ConfirmationCode":{},"Password":{"shape":"S1g"}}},"output":{"type":"structure","members":{}},"http":{}},"ConfirmSignUp":{"input":{"type":"structure","required":["ClientId","Username","ConfirmationCode"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"},"ConfirmationCode":{},"ForceAliasCreation":{"type":"boolean"}}},"output":{"type":"structure","members":{}},"http":{}},"CreateUserPool":{"input":{"type":"structure","required":["PoolName"],"members":{"PoolName":{},"Policies":{"shape":"S1q"},"LambdaConfig":{"shape":"S1t"},"AutoVerifiedAttributes":{"shape":"S1v"},"AliasAttributes":{"shape":"S1x"},"SmsVerificationMessage":{},"EmailVerificationMessage":{},"EmailVerificationSubject":{},"SmsAuthenticationMessage":{},"MfaConfiguration":{}}},"output":{"type":"structure","members":{"UserPool":{"shape":"S24"}}},"http":{}},"CreateUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientName"],"members":{"UserPoolId":{},"ClientName":{},"GenerateSecret":{"type":"boolean"}}},"output":{"type":"structure","members":{"UserPoolClient":{"shape":"S2b"}}},"http":{}},"DeleteUser":{"input":{"type":"structure","members":{"AccessToken":{"shape":"S1b"}}},"http":{}},"DeleteUserAttributes":{"input":{"type":"structure","required":["UserAttributeNames"],"members":{"UserAttributeNames":{"shape":"Sh"},"AccessToken":{"shape":"S1b"}}},"output":{"type":"structure","members":{}},"http":{}},"DeleteUserPool":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{}}},"http":{}},"DeleteUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S15"}}},"http":{}},"DescribeUserPool":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{}}},"output":{"type":"structure","members":{"UserPool":{"shape":"S24"}}},"http":{}},"DescribeUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S15"}}},"output":{"type":"structure","members":{"UserPoolClient":{"shape":"S2b"}}},"http":{}},"EnhanceAuth":{"input":{"type":"structure","required":["ClientId","Username","AuthState","Code"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"},"AuthState":{"shape":"S1d"},"Code":{}}},"output":{"type":"structure","members":{"AuthenticationResult":{"shape":"S1a"}}},"http":{}},"ForgotPassword":{"input":{"type":"structure","required":["ClientId","Username"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{"CodeDeliveryDetails":{"shape":"S1e"}}},"http":{}},"GetAuthenticationDetails":{"input":{"type":"structure","required":["ClientId","Username","SrpA"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"},"SrpA":{},"ValidationData":{"shape":"Sq"}}},"output":{"type":"structure","required":["Salt","SrpB","SecretBlock"],"members":{"Salt":{},"SrpB":{},"SecretBlock":{"type":"blob"},"Username":{"shape":"Sd"}}},"http":{}},"GetJWKS":{"http":{"method":"GET","requestUri":"/{userPoolId}/.well-known/jwks.json","responseCode":200},"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{"location":"uri","locationName":"userPoolId"}}},"output":{"type":"structure","members":{"keys":{"type":"list","member":{"type":"structure","members":{"kty":{},"alg":{},"use":{},"kid":{},"n":{},"e":{}}}}}}},"GetOpenIdConfiguration":{"http":{"method":"GET","requestUri":"/{userPoolId}/.well-known/openid-configuration","responseCode":200},"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{"location":"uri","locationName":"userPoolId"}}},"output":{"type":"structure","members":{"issuer":{},"jwks_uri":{},"authorization_endpoint":{},"subject_types_supported":{"shape":"S31"},"response_types_supported":{"shape":"S31"},"id_token_signing_alg_values_supported":{"shape":"S31"}}}},"GetUser":{"input":{"type":"structure","members":{"AccessToken":{"shape":"S1b"}}},"output":{"type":"structure","required":["Username","UserAttributes"],"members":{"Username":{"shape":"Sd"},"UserAttributes":{"shape":"Sq"},"MFAOptions":{"shape":"Sv"}}},"http":{}},"GetUserAttributeVerificationCode":{"input":{"type":"structure","required":["AttributeName"],"members":{"AccessToken":{"shape":"S1b"},"AttributeName":{}}},"output":{"type":"structure","members":{"CodeDeliveryDetails":{"shape":"S1e"}}},"http":{}},"ListUserPoolClients":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"MaxResults":{"type":"integer"},"NextToken":{}}},"output":{"type":"structure","members":{"UserPoolClients":{"type":"list","member":{"type":"structure","members":{"ClientId":{"shape":"S15"},"UserPoolId":{},"ClientName":{}}}},"NextToken":{}}},"http":{}},"ListUserPools":{"input":{"type":"structure","required":["MaxResults"],"members":{"NextToken":{},"MaxResults":{"type":"integer"}}},"output":{"type":"structure","members":{"UserPools":{"type":"list","member":{"type":"structure","members":{"Id":{},"Name":{},"LambdaConfig":{"shape":"S1t"},"Status":{},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"}}}},"NextToken":{}}},"http":{}},"ListUsers":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"AttributesToGet":{"type":"list","member":{}},"Limit":{"type":"integer"},"PaginationToken":{},"UserStatus":{}}},"output":{"type":"structure","members":{"Users":{"type":"list","member":{"type":"structure","members":{"Username":{"shape":"Sd"},"Attributes":{"shape":"Sq"},"UserCreateDate":{"type":"timestamp"},"UserLastModifiedDate":{"type":"timestamp"},"Enabled":{"type":"boolean"},"UserStatus":{}}}},"PaginationToken":{}}},"http":{}},"RefreshTokens":{"input":{"type":"structure","required":["ClientId","RefreshToken"],"members":{"ClientId":{"shape":"S15"},"ClientSecret":{"shape":"S2c"},"RefreshToken":{"shape":"S1b"}}},"output":{"type":"structure","members":{"AuthenticationResult":{"shape":"S1a"}}},"http":{}},"ResendConfirmationCode":{"input":{"type":"structure","required":["ClientId","Username"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"}}},"output":{"type":"structure","members":{"CodeDeliveryDetails":{"shape":"S1e"}}},"http":{}},"SetUserSettings":{"input":{"type":"structure","required":["AccessToken","MFAOptions"],"members":{"AccessToken":{"shape":"S1b"},"MFAOptions":{"shape":"Sv"}}},"output":{"type":"structure","members":{}},"http":{}},"SignUp":{"input":{"type":"structure","required":["ClientId","Username","Password"],"members":{"ClientId":{"shape":"S15"},"SecretHash":{"shape":"S16"},"Username":{"shape":"Sd"},"Password":{"shape":"S1g"},"UserAttributes":{"shape":"Sq"},"ValidationData":{"shape":"Sq"}}},"output":{"type":"structure","members":{"UserConfirmed":{"type":"boolean"},"CodeDeliveryDetails":{"shape":"S1e"}}},"http":{}},"UpdateUserAttributes":{"input":{"type":"structure","required":["UserAttributes"],"members":{"UserAttributes":{"shape":"Sq"},"AccessToken":{"shape":"S1b"}}},"output":{"type":"structure","members":{"CodeDeliveryDetailsList":{"type":"list","member":{"shape":"S1e"}}}},"http":{}},"UpdateUserPool":{"input":{"type":"structure","required":["UserPoolId"],"members":{"UserPoolId":{},"Policies":{"shape":"S1q"},"LambdaConfig":{"shape":"S1t"},"AutoVerifiedAttributes":{"shape":"S1v"},"SmsVerificationMessage":{},"EmailVerificationMessage":{},"EmailVerificationSubject":{},"SmsAuthenticationMessage":{},"MfaConfiguration":{}}},"output":{"type":"structure","members":{}},"http":{}},"UpdateUserPoolClient":{"input":{"type":"structure","required":["UserPoolId","ClientId"],"members":{"UserPoolId":{},"ClientId":{"shape":"S15"},"ClientName":{}}},"output":{"type":"structure","members":{"UserPoolClient":{"shape":"S2b"}}},"http":{}},"VerifyUserAttribute":{"input":{"type":"structure","required":["AttributeName","Code"],"members":{"AccessToken":{"shape":"S1b"},"AttributeName":{},"Code":{}}},"output":{"type":"structure","members":{}},"http":{}}},"shapes":{"S4":{"type":"structure","members":{"Name":{},"AttributeDataType":{},"DeveloperOnlyAttribute":{"type":"boolean"},"Mutable":{"type":"boolean"},"Required":{"type":"boolean"},"NumberAttributeConstraints":{"type":"structure","members":{"MinValue":{},"MaxValue":{}}},"StringAttributeConstraints":{"type":"structure","members":{"MinLength":{},"MaxLength":{}}}}},"Sd":{"type":"string","sensitive":true},"Sh":{"type":"list","member":{}},"Sq":{"type":"list","member":{"type":"structure","required":["Name"],"members":{"Name":{},"Value":{"type":"string","sensitive":true}}}},"Sv":{"type":"list","member":{"type":"structure","members":{"DeliveryMedium":{},"AttributeName":{}}}},"S15":{"type":"string","sensitive":true},"S16":{"type":"string","sensitive":true},"S1a":{"type":"structure","members":{"AccessToken":{"shape":"S1b"},"ExpiresIn":{"type":"integer"},"TokenType":{},"RefreshToken":{"shape":"S1b"},"IdToken":{"shape":"S1b"}}},"S1b":{"type":"string","sensitive":true},"S1d":{"type":"string","sensitive":true},"S1e":{"type":"structure","members":{"Destination":{},"DeliveryMedium":{},"AttributeName":{}}},"S1g":{"type":"string","sensitive":true},"S1q":{"type":"structure","members":{"PasswordPolicy":{"type":"structure","members":{"MinimumLength":{"type":"integer"},"RequireUppercase":{"type":"boolean"},"RequireLowercase":{"type":"boolean"},"RequireNumbers":{"type":"boolean"},"RequireSymbols":{"type":"boolean"}}}}},"S1t":{"type":"structure","members":{"PreSignUp":{},"CustomMessage":{},"PostConfirmation":{},"PreAuthentication":{},"PostAuthentication":{}}},"S1v":{"type":"list","member":{}},"S1x":{"type":"list","member":{}},"S24":{"type":"structure","members":{"Id":{},"Name":{},"Policies":{"shape":"S1q"},"LambdaConfig":{"shape":"S1t"},"Status":{},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"},"SchemaAttributes":{"type":"list","member":{"shape":"S4"}},"AutoVerifiedAttributes":{"shape":"S1v"},"AliasAttributes":{"shape":"S1x"},"SmsVerificationMessage":{},"EmailVerificationMessage":{},"EmailVerificationSubject":{},"SmsAuthenticationMessage":{},"MfaConfiguration":{},"EstimatedNumberOfUsers":{"type":"integer"}}},"S2b":{"type":"structure","members":{"UserPoolId":{},"ClientName":{},"ClientId":{"shape":"S15"},"ClientSecret":{"shape":"S2c"},"LastModifiedDate":{"type":"timestamp"},"CreationDate":{"type":"timestamp"}}},"S2c":{"type":"string","sensitive":true},"S31":{"type":"list","member":{}}}};
AWS.apiLoader.services['sts'] = {};
AWS.STS = AWS.Service.defineService('sts', [ '2011-06-15' ]);
require('./services/sts');
AWS.apiLoader.services['sts']['2011-06-15'] = {"version":"2.0","metadata":{"apiVersion":"2011-06-15","endpointPrefix":"sts","globalEndpoint":"sts.amazonaws.com","protocol":"query","serviceAbbreviation":"AWS STS","serviceFullName":"AWS Security Token Service","signatureVersion":"v4","xmlNamespace":"https://sts.amazonaws.com/doc/2011-06-15/"},"operations":{"AssumeRole":{"input":{"type":"structure","required":["RoleArn","RoleSessionName"],"members":{"RoleArn":{},"RoleSessionName":{},"Policy":{},"DurationSeconds":{"type":"integer"},"ExternalId":{},"SerialNumber":{},"TokenCode":{}}},"output":{"resultWrapper":"AssumeRoleResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"AssumedRoleUser":{"shape":"Sf"},"PackedPolicySize":{"type":"integer"}}},"http":{}},"AssumeRoleWithSAML":{"input":{"type":"structure","required":["RoleArn","PrincipalArn","SAMLAssertion"],"members":{"RoleArn":{},"PrincipalArn":{},"SAMLAssertion":{},"Policy":{},"DurationSeconds":{"type":"integer"}}},"output":{"resultWrapper":"AssumeRoleWithSAMLResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"AssumedRoleUser":{"shape":"Sf"},"PackedPolicySize":{"type":"integer"},"Subject":{},"SubjectType":{},"Issuer":{},"Audience":{},"NameQualifier":{}}},"http":{}},"AssumeRoleWithWebIdentity":{"input":{"type":"structure","required":["RoleArn","RoleSessionName","WebIdentityToken"],"members":{"RoleArn":{},"RoleSessionName":{},"WebIdentityToken":{},"ProviderId":{},"Policy":{},"DurationSeconds":{"type":"integer"}}},"output":{"resultWrapper":"AssumeRoleWithWebIdentityResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"SubjectFromWebIdentityToken":{},"AssumedRoleUser":{"shape":"Sf"},"PackedPolicySize":{"type":"integer"},"Provider":{},"Audience":{}}},"http":{}},"DecodeAuthorizationMessage":{"input":{"type":"structure","required":["EncodedMessage"],"members":{"EncodedMessage":{}}},"output":{"resultWrapper":"DecodeAuthorizationMessageResult","type":"structure","members":{"DecodedMessage":{}}},"http":{}},"GetFederationToken":{"input":{"type":"structure","required":["Name"],"members":{"Name":{},"Policy":{},"DurationSeconds":{"type":"integer"}}},"output":{"resultWrapper":"GetFederationTokenResult","type":"structure","members":{"Credentials":{"shape":"Sa"},"FederatedUser":{"type":"structure","required":["FederatedUserId","Arn"],"members":{"FederatedUserId":{},"Arn":{}}},"PackedPolicySize":{"type":"integer"}}},"http":{}},"GetSessionToken":{"input":{"type":"structure","members":{"DurationSeconds":{"type":"integer"},"SerialNumber":{},"TokenCode":{}}},"output":{"resultWrapper":"GetSessionTokenResult","type":"structure","members":{"Credentials":{"shape":"Sa"}}},"http":{}}},"shapes":{"Sa":{"type":"structure","required":["AccessKeyId","SecretAccessKey","SessionToken","Expiration"],"members":{"AccessKeyId":{},"SecretAccessKey":{},"SessionToken":{},"Expiration":{"type":"timestamp"}}},"Sf":{"type":"structure","required":["AssumedRoleId","Arn"],"members":{"AssumedRoleId":{},"Arn":{}}}}};
},{"./core":3,"./http/xhr":12,"./services/sts":35,"./xml/browser_parser":45}],2:[function(require,module,exports){
var AWS = require('./core');
require('./credentials');
require('./credentials/credential_provider_chain');
AWS.Config = AWS.util.inherit({
constructor: function Config(options) {
if (options === undefined) options = {};
options = this.extractCredentials(options);
AWS.util.each.call(this, this.keys, function (key, value) {
this.set(key, options[key], value);
});
},
getCredentials: function getCredentials(callback) {
var self = this;
function finish(err) {
callback(err, err ? null : self.credentials);
}
function credError(msg, err) {
return new AWS.util.error(err || new Error(), {
code: 'CredentialsError', message: msg
});
}
function getAsyncCredentials() {
self.credentials.get(function(err) {
if (err) {
var msg = 'Could not load credentials from ' +
self.credentials.constructor.name;
err = credError(msg, err);
}
finish(err);
});
}
function getStaticCredentials() {
var err = null;
if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
err = credError('Missing credentials');
}
finish(err);
}
if (self.credentials) {
if (typeof self.credentials.get === 'function') {
getAsyncCredentials();
} else { // static credentials
getStaticCredentials();
}
} else if (self.credentialProvider) {
self.credentialProvider.resolve(function(err, creds) {
if (err) {
err = credError('Could not load credentials from any providers', err);
}
self.credentials = creds;
finish(err);
});
} else {
finish(credError('No credentials to load'));
}
},
update: function update(options, allowUnknownKeys) {
allowUnknownKeys = allowUnknownKeys || false;
options = this.extractCredentials(options);
AWS.util.each.call(this, options, function (key, value) {
if (allowUnknownKeys || this.keys.hasOwnProperty(key) ||
AWS.Service.hasService(key)) {
this.set(key, value);
}
});
},
loadFromPath: function loadFromPath(path) {
this.clear();
var options = JSON.parse(AWS.util.readFileSync(path));
var fileSystemCreds = new AWS.FileSystemCredentials(path);
var chain = new AWS.CredentialProviderChain();
chain.providers.unshift(fileSystemCreds);
chain.resolve(function (err, creds) {
if (err) throw err;
else options.credentials = creds;
});
this.constructor(options);
return this;
},
clear: function clear() {
AWS.util.each.call(this, this.keys, function (key) {
delete this[key];
});
this.set('credentials', undefined);
this.set('credentialProvider', undefined);
},
set: function set(property, value, defaultValue) {
if (value === undefined) {
if (defaultValue === undefined) {
defaultValue = this.keys[property];
}
if (typeof defaultValue === 'function') {
this[property] = defaultValue.call(this);
} else {
this[property] = defaultValue;
}
} else if (property === 'httpOptions' && this[property]) {
this[property] = AWS.util.merge(this[property], value);
} else {
this[property] = value;
}
},
keys: {
credentials: null,
credentialProvider: null,
region: null,
logger: null,
apiVersions: {},
apiVersion: null,
endpoint: undefined,
httpOptions: {
timeout: 120000
},
maxRetries: undefined,
maxRedirects: 10,
paramValidation: true,
sslEnabled: true,
s3ForcePathStyle: false,
s3BucketEndpoint: false,
computeChecksums: true,
convertResponseTypes: true,
correctClockSkew: false,
customUserAgent: null,
dynamoDbCrc32: true,
systemClockOffset: 0,
signatureVersion: null,
signatureCache: true,
retryDelayOptions: {
base: 100
}
},
extractCredentials: function extractCredentials(options) {
if (options.accessKeyId && options.secretAccessKey) {
options = AWS.util.copy(options);
options.credentials = new AWS.Credentials(options);
}
return options;
}
});
AWS.config = new AWS.Config();
},{"./core":3,"./credentials":4,"./credentials/credential_provider_chain":6}],3:[function(require,module,exports){
var AWS = { util: require('./util') };
var _hidden = {}; _hidden.toString(); // hack to parse macro
module.exports = AWS;
AWS.util.update(AWS, {
VERSION: '2.2.40',
Signers: {},
Protocol: {
Json: require('./protocol/json'),
Query: require('./protocol/query'),
Rest: require('./protocol/rest'),
RestJson: require('./protocol/rest_json'),
RestXml: require('./protocol/rest_xml')
},
XML: {
Builder: require('./xml/builder'),
Parser: null // conditionally set based on environment
},
JSON: {
Builder: require('./json/builder'),
Parser: require('./json/parser')
},
Model: {
Api: require('./model/api'),
Operation: require('./model/operation'),
Shape: require('./model/shape'),
Paginator: require('./model/paginator'),
ResourceWaiter: require('./model/resource_waiter')
},
util: require('./util'),
apiLoader: function() { throw new Error('No API loader set'); }
});
require('./service');
require('./credentials');
require('./credentials/credential_provider_chain');
require('./credentials/temporary_credentials');
require('./credentials/web_identity_credentials');
require('./credentials/cognito_identity_credentials');
require('./credentials/saml_credentials');
require('./config');
require('./http');
require('./sequential_executor');
require('./event_listeners');
require('./request');
require('./response');
require('./resource_waiter');
require('./signers/request_signer');
require('./param_validator');
AWS.events = new AWS.SequentialExecutor();
},{"./config":2,"./credentials":4,"./credentials/cognito_identity_credentials":5,"./credentials/credential_provider_chain":6,"./credentials/saml_credentials":7,"./credentials/temporary_credentials":8,"./credentials/web_identity_credentials":9,"./event_listeners":10,"./http":11,"./json/builder":13,"./json/parser":14,"./model/api":15,"./model/operation":17,"./model/paginator":18,"./model/resource_waiter":19,"./model/shape":20,"./param_validator":21,"./protocol/json":22,"./protocol/query":23,"./protocol/rest":24,"./protocol/rest_json":25,"./protocol/rest_xml":26,"./request":30,"./resource_waiter":31,"./response":32,"./sequential_executor":33,"./service":34,"./signers/request_signer":37,"./util":44,"./xml/builder":46}],4:[function(require,module,exports){
var AWS = require('./core');
AWS.Credentials = AWS.util.inherit({
constructor: function Credentials() {
AWS.util.hideProperties(this, ['secretAccessKey']);
this.expired = false;
this.expireTime = null;
if (arguments.length === 1 && typeof arguments[0] === 'object') {
var creds = arguments[0].credentials || arguments[0];
this.accessKeyId = creds.accessKeyId;
this.secretAccessKey = creds.secretAccessKey;
this.sessionToken = creds.sessionToken;
} else {
this.accessKeyId = arguments[0];
this.secretAccessKey = arguments[1];
this.sessionToken = arguments[2];
}
},
expiryWindow: 15,
needsRefresh: function needsRefresh() {
var currentTime = AWS.util.date.getDate().getTime();
var adjustedTime = new Date(currentTime + this.expiryWindow * 1000);
if (this.expireTime && adjustedTime > this.expireTime) {
return true;
} else {
return this.expired || !this.accessKeyId || !this.secretAccessKey;
}
},
get: function get(callback) {
var self = this;
if (this.needsRefresh()) {
this.refresh(function(err) {
if (!err) self.expired = false; // reset expired flag
if (callback) callback(err);
});
} else if (callback) {
callback();
}
},
refresh: function refresh(callback) {
this.expired = false;
callback();
}
});
},{"./core":3}],5:[function(require,module,exports){
var AWS = require('../core');
AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, {
localStorageKey: {
id: 'aws.cognito.identity-id.',
providers: 'aws.cognito.identity-providers.'
},
constructor: function CognitoIdentityCredentials(params) {
AWS.Credentials.call(this);
this.expired = true;
this.params = params;
this.data = null;
this.identityId = null;
this.loadCachedId();
},
refresh: function refresh(callback) {
var self = this;
self.createClients();
self.data = null;
self.identityId = null;
self.getId(function(err) {
if (!err) {
if (!self.params.RoleArn) {
self.getCredentialsForIdentity(callback);
} else {
self.getCredentialsFromSTS(callback);
}
} else {
self.clearCachedId();
callback(err);
}
});
},
clearCachedId: function clearCache() {
this.identityId = null;
delete this.params.IdentityId;
var poolId = this.params.IdentityPoolId;
var loginId = this.params.LoginId || '';
delete this.storage[this.localStorageKey.id + poolId + loginId];
delete this.storage[this.localStorageKey.providers + poolId + loginId];
},
getId: function getId(callback) {
var self = this;
if (typeof self.params.IdentityId === 'string') {
return callback(null, self.params.IdentityId);
}
self.cognito.getId(function(err, data) {
if (!err && data.IdentityId) {
self.params.IdentityId = data.IdentityId;
callback(null, data.IdentityId);
} else {
callback(err);
}
});
},
loadCredentials: function loadCredentials(data, credentials) {
if (!data || !credentials) return;
credentials.expired = false;
credentials.accessKeyId = data.Credentials.AccessKeyId;
credentials.secretAccessKey = data.Credentials.SecretKey;
credentials.sessionToken = data.Credentials.SessionToken;
credentials.expireTime = data.Credentials.Expiration;
},
getCredentialsForIdentity: function getCredentialsForIdentity(callback) {
var self = this;
self.cognito.getCredentialsForIdentity(function(err, data) {
if (!err) {
self.cacheId(data);
self.data = data;
self.loadCredentials(self.data, self);
} else {
self.clearCachedId();
}
callback(err);
});
},
getCredentialsFromSTS: function getCredentialsFromSTS(callback) {
var self = this;
self.cognito.getOpenIdToken(function(err, data) {
if (!err) {
self.cacheId(data);
self.params.WebIdentityToken = data.Token;
self.webIdentityCredentials.refresh(function(webErr) {
if (!webErr) {
self.data = self.webIdentityCredentials.data;
self.sts.credentialsFrom(self.data, self);
} else {
self.clearCachedId();
}
callback(webErr);
});
} else {
self.clearCachedId();
callback(err);
}
});
},
loadCachedId: function loadCachedId() {
var self = this;
if (AWS.util.isBrowser() && !self.params.IdentityId) {
var id = self.getStorage('id');
if (id && self.params.Logins) {
var actualProviders = Object.keys(self.params.Logins);
var cachedProviders =
(self.getStorage('providers') || '').split(',');
var intersect = cachedProviders.filter(function(n) {
return actualProviders.indexOf(n) !== -1;
});
if (intersect.length !== 0) {
self.params.IdentityId = id;
}
} else if (id) {
self.params.IdentityId = id;
}
}
},
createClients: function() {
this.webIdentityCredentials = this.webIdentityCredentials ||
new AWS.WebIdentityCredentials(this.params);
this.cognito = this.cognito ||
new AWS.CognitoIdentity({params: this.params});
this.sts = this.sts || new AWS.STS();
},
cacheId: function cacheId(data) {
this.identityId = data.IdentityId;
this.params.IdentityId = this.identityId;
if (AWS.util.isBrowser()) {
this.setStorage('id', data.IdentityId);
if (this.params.Logins) {
this.setStorage('providers', Object.keys(this.params.Logins).join(','));
}
}
},
getStorage: function getStorage(key) {
return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')];
},
setStorage: function setStorage(key, val) {
try {
this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')] = val;
} catch (_) {}
},
storage: (function() {
try {
return AWS.util.isBrowser() && window.localStorage !== null && typeof window.localStorage === 'object' ?
window.localStorage : {};
} catch (_) {
return {};
}
})()
});
},{"../core":3}],6:[function(require,module,exports){
var AWS = require('../core');
AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {
constructor: function CredentialProviderChain(providers) {
if (providers) {
this.providers = providers;
} else {
this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
}
},
resolve: function resolve(callback) {
if (this.providers.length === 0) {
callback(new Error('No providers'));
return this;
}
var index = 0;
var providers = this.providers.slice(0);
function resolveNext(err, creds) {
if ((!err && creds) || index === providers.length) {
callback(err, creds);
return;
}
var provider = providers[index++];
if (typeof provider === 'function') {
creds = provider.call();
} else {
creds = provider;
}
if (creds.get) {
creds.get(function(getErr) {
resolveNext(getErr, getErr ? null : creds);
});
} else {
resolveNext(null, creds);
}
}
resolveNext();
return this;
}
});
AWS.CredentialProviderChain.defaultProviders = [];
},{"../core":3}],7:[function(require,module,exports){
var AWS = require('../core');
AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, {
constructor: function SAMLCredentials(params) {
AWS.Credentials.call(this);
this.expired = true;
this.params = params;
},
refresh: function refresh(callback) {
var self = this;
self.createClients();
if (!callback) callback = function(err) { if (err) throw err; };
self.service.assumeRoleWithSAML(function (err, data) {
if (!err) {
self.service.credentialsFrom(data, self);
}
callback(err);
});
},
createClients: function() {
this.service = this.service || new AWS.STS({params: this.params});
}
});
},{"../core":3}],8:[function(require,module,exports){
var AWS = require('../core');
AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, {
constructor: function TemporaryCredentials(params) {
AWS.Credentials.call(this);
this.loadMasterCredentials();
this.expired = true;
this.params = params || {};
if (this.params.RoleArn) {
this.params.RoleSessionName =
this.params.RoleSessionName || 'temporary-credentials';
}
},
refresh: function refresh(callback) {
var self = this;
self.createClients();
if (!callback) callback = function(err) { if (err) throw err; };
self.service.config.credentials = self.masterCredentials;
var operation = self.params.RoleArn ?
self.service.assumeRole : self.service.getSessionToken;
operation.call(self.service, function (err, data) {
if (!err) {
self.service.credentialsFrom(data, self);
}
callback(err);
});
},
loadMasterCredentials: function loadMasterCredentials() {
this.masterCredentials = AWS.config.credentials;
while (this.masterCredentials.masterCredentials) {
this.masterCredentials = this.masterCredentials.masterCredentials;
}
},
createClients: function() {
this.service = this.service || new AWS.STS({params: this.params});
}
});
},{"../core":3}],9:[function(require,module,exports){
var AWS = require('../core');
AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, {
constructor: function WebIdentityCredentials(params) {
AWS.Credentials.call(this);
this.expired = true;
this.params = params;
this.params.RoleSessionName = this.params.RoleSessionName || 'web-identity';
this.data = null;
},
refresh: function refresh(callback) {
var self = this;
self.createClients();
if (!callback) callback = function(err) { if (err) throw err; };
self.service.assumeRoleWithWebIdentity(function (err, data) {
self.data = null;
if (!err) {
self.data = data;
self.service.credentialsFrom(data, self);
}
callback(err);
});
},
createClients: function() {
this.service = this.service || new AWS.STS({params: this.params});
}
});
},{"../core":3}],10:[function(require,module,exports){
var AWS = require('./core');
var SequentialExecutor = require('./sequential_executor');
AWS.EventListeners = {
Core: {} /* doc hack */
};
AWS.EventListeners = {
Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) {
addAsync('VALIDATE_CREDENTIALS', 'validate',
function VALIDATE_CREDENTIALS(req, done) {
if (!req.service.api.signatureVersion) return done(); // none
req.service.config.getCredentials(function(err) {
if (err) {
req.response.error = AWS.util.error(err,
{code: 'CredentialsError', message: 'Missing credentials in config'});
}
done();
});
});
add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
if (!req.service.config.region && !req.service.isGlobalEndpoint) {
req.response.error = AWS.util.error(new Error(),
{code: 'ConfigError', message: 'Missing region in config'});
}
});
add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) {
var rules = req.service.api.operations[req.operation].input;
var validation = req.service.config.paramValidation;
new AWS.ParamValidator(validation).validate(rules, req.params);
});
addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) {
req.haltHandlersOnError();
if (!req.service.api.signatureVersion) return done(); // none
if (req.service.getSignerClass(req) === AWS.Signers.V4) {
var body = req.httpRequest.body || '';
AWS.util.computeSha256(body, function(err, sha) {
if (err) {
done(err);
}
else {
req.httpRequest.headers['X-Amz-Content-Sha256'] = sha;
done();
}
});
} else {
done();
}
});
add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) {
if (req.httpRequest.headers['Content-Length'] === undefined) {
var length = AWS.util.string.byteLength(req.httpRequest.body);
req.httpRequest.headers['Content-Length'] = length;
}
});
add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) {
req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host;
});
add('RESTART', 'restart', function RESTART() {
var err = this.response.error;
if (!err || !err.retryable) return;
this.httpRequest = new AWS.HttpRequest(
this.service.endpoint,
this.service.region
);
if (this.response.retryCount < this.service.config.maxRetries) {
this.response.retryCount++;
} else {
this.response.error = null;
}
});
addAsync('SIGN', 'sign', function SIGN(req, done) {
if (!req.service.api.signatureVersion) return done(); // none
req.service.config.getCredentials(function (err, credentials) {
if (err) {
req.response.error = err;
return done();
}
try {
var date = AWS.util.date.getDate();
var SignerClass = req.service.getSignerClass(req);
var signer = new SignerClass(req.httpRequest,
req.service.api.signingName || req.service.api.endpointPrefix,
req.service.config.signatureCache);
delete req.httpRequest.headers['Authorization'];
delete req.httpRequest.headers['Date'];
delete req.httpRequest.headers['X-Amz-Date'];
signer.addAuthorization(credentials, date);
req.signedAt = date;
} catch (e) {
req.response.error = e;
}
done();
});
});
add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) {
if (this.service.successfulResponse(resp, this)) {
resp.data = {};
resp.error = null;
} else {
resp.data = null;
resp.error = AWS.util.error(new Error(),
{code: 'UnknownError', message: 'An unknown error occurred.'});
}
});
addAsync('SEND', 'send', function SEND(resp, done) {
resp.httpResponse._abortCallback = done;
resp.error = null;
resp.data = null;
function callback(httpResp) {
resp.httpResponse.stream = httpResp;
httpResp.on('headers', function onHeaders(statusCode, headers) {
resp.request.emit('httpHeaders', [statusCode, headers, resp]);
if (!resp.httpResponse.streaming) {
if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check
httpResp.on('readable', function onReadable() {
var data = httpResp.read();
if (data !== null) {
resp.request.emit('httpData', [data, resp]);
}
});
} else { // legacy streams API
httpResp.on('data', function onData(data) {
resp.request.emit('httpData', [data, resp]);
});
}
}
});
httpResp.on('end', function onEnd() {
resp.request.emit('httpDone');
done();
});
}
function progress(httpResp) {
httpResp.on('sendProgress', function onSendProgress(value) {
resp.request.emit('httpUploadProgress', [value, resp]);
});
httpResp.on('receiveProgress', function onReceiveProgress(value) {
resp.request.emit('httpDownloadProgress', [value, resp]);
});
}
function error(err) {
resp.error = AWS.util.error(err, {
code: 'NetworkingError',
region: resp.request.httpRequest.region,
hostname: resp.request.httpRequest.endpoint.hostname,
retryable: true
});
resp.request.emit('httpError', [resp.error, resp], function() {
done();
});
}
function executeSend() {
var http = AWS.HttpClient.getInstance();
var httpOptions = resp.request.service.config.httpOptions || {};
try {
var stream = http.handleRequest(resp.request.httpRequest, httpOptions,
callback, error);
progress(stream);
} catch (err) {
error(err);
}
}
var timeDiff = (AWS.util.date.getDate() - this.signedAt) / 1000;
if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign
this.emit('sign', [this], function(err) {
if (err) done(err);
else executeSend();
});
} else {
executeSend();
}
});
add('HTTP_HEADERS', 'httpHeaders',
function HTTP_HEADERS(statusCode, headers, resp) {
resp.httpResponse.statusCode = statusCode;
resp.httpResponse.headers = headers;
resp.httpResponse.body = new AWS.util.Buffer('');
resp.httpResponse.buffers = [];
resp.httpResponse.numBytes = 0;
var dateHeader = headers.date || headers.Date;
if (dateHeader) {
var serverTime = Date.parse(dateHeader);
if (resp.request.service.config.correctClockSkew
&& AWS.util.isClockSkewed(serverTime)) {
AWS.util.applyClockOffset(serverTime);
}
}
});
add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) {
if (chunk) {
if (AWS.util.isNode()) {
resp.httpResponse.numBytes += chunk.length;
var total = resp.httpResponse.headers['content-length'];
var progress = { loaded: resp.httpResponse.numBytes, total: total };
resp.request.emit('httpDownloadProgress', [progress, resp]);
}
resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk));
}
});
add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {
if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) {
var body = AWS.util.buffer.concat(resp.httpResponse.buffers);
resp.httpResponse.body = body;
}
delete resp.httpResponse.numBytes;
delete resp.httpResponse.buffers;
});
add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) {
if (resp.httpResponse.statusCode) {
resp.error.statusCode = resp.httpResponse.statusCode;
if (resp.error.retryable === undefined) {
resp.error.retryable = this.service.retryableError(resp.error, this);
}
}
});
add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) {
if (!resp.error) return;
switch (resp.error.code) {
case 'RequestExpired': // EC2 only
case 'ExpiredTokenException':
case 'ExpiredToken':
resp.error.retryable = true;
resp.request.service.config.credentials.expired = true;
}
});
add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) {
var err = resp.error;
if (!err) return;
if (typeof err.code === 'string' && typeof err.message === 'string') {
if (err.code.match(/Signature/) && err.message.match(/expired/)) {
resp.error.retryable = true;
}
}
});
add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) {
if (!resp.error) return;
if (this.service.clockSkewError(resp.error)
&& this.service.config.correctClockSkew
&& AWS.config.isClockSkewed) {
resp.error.retryable = true;
}
});
add('REDIRECT', 'retry', function REDIRECT(resp) {
if (resp.error && resp.error.statusCode >= 300 &&
resp.error.statusCode < 400 && resp.httpResponse.headers['location']) {
this.httpRequest.endpoint =
new AWS.Endpoint(resp.httpResponse.headers['location']);
this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host;
resp.error.redirect = true;
resp.error.retryable = true;
}
});
add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) {
if (resp.error) {
if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
resp.error.retryDelay = 0;
} else if (resp.retryCount < resp.maxRetries) {
resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0;
}
}
});
addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) {
var delay, willRetry = false;
if (resp.error) {
delay = resp.error.retryDelay || 0;
if (resp.error.retryable && resp.retryCount < resp.maxRetries) {
resp.retryCount++;
willRetry = true;
} else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
resp.redirectCount++;
willRetry = true;
}
}
if (willRetry) {
resp.error = null;
setTimeout(done, delay);
} else {
done();
}
});
}),
CorePost: new SequentialExecutor().addNamedListeners(function(add) {
add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId);
add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId);
add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) {
if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') {
var message = 'Inaccessible host: `' + err.hostname +
'\'. This service may not be available in the `' + err.region +
'\' region.';
this.response.error = AWS.util.error(new Error(message), {
code: 'UnknownEndpoint',
region: err.region,
hostname: err.hostname,
retryable: true,
originalError: err
});
}
});
}),
Logger: new SequentialExecutor().addNamedListeners(function(add) {
add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) {
var req = resp.request;
var logger = req.service.config.logger;
if (!logger) return;
function buildMessage() {
var time = AWS.util.date.getDate().getTime();
var delta = (time - req.startTime.getTime()) / 1000;
var ansi = logger.isTTY ? true : false;
var status = resp.httpResponse.statusCode;
var params = require('util').inspect(req.params, true, null);
var message = '';
if (ansi) message += '\x1B[33m';
message += '[AWS ' + req.service.serviceIdentifier + ' ' + status;
message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]';
if (ansi) message += '\x1B[0;1m';
message += ' ' + AWS.util.string.lowerFirst(req.operation);
message += '(' + params + ')';
if (ansi) message += '\x1B[0m';
return message;
}
var line = buildMessage();
if (typeof logger.log === 'function') {
logger.log(line);
} else if (typeof logger.write === 'function') {
logger.write(line + '\n');
}
});
}),
Json: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/json');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
Rest: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/rest');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
RestJson: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/rest_json');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
RestXml: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/rest_xml');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
Query: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/query');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
})
};
},{"./core":3,"./protocol/json":22,"./protocol/query":23,"./protocol/rest":24,"./protocol/rest_json":25,"./protocol/rest_xml":26,"./sequential_executor":33,"util":65}],11:[function(require,module,exports){
var AWS = require('./core');
var inherit = AWS.util.inherit;
AWS.Endpoint = inherit({
constructor: function Endpoint(endpoint, config) {
AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']);
if (typeof endpoint === 'undefined' || endpoint === null) {
throw new Error('Invalid endpoint: ' + endpoint);
} else if (typeof endpoint !== 'string') {
return AWS.util.copy(endpoint);
}
if (!endpoint.match(/^http/)) {
var useSSL = config && config.sslEnabled !== undefined ?
config.sslEnabled : AWS.config.sslEnabled;
endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
}
AWS.util.update(this, AWS.util.urlParse(endpoint));
if (this.port) {
this.port = parseInt(this.port, 10);
} else {
this.port = this.protocol === 'https:' ? 443 : 80;
}
}
});
AWS.HttpRequest = inherit({
constructor: function HttpRequest(endpoint, region, customUserAgent) {
endpoint = new AWS.Endpoint(endpoint);
this.method = 'POST';
this.path = endpoint.path || '/';
this.headers = {};
this.body = '';
this.endpoint = endpoint;
this.region = region;
this.setUserAgent(customUserAgent);
},
setUserAgent: function setUserAgent(customUserAgent) {
var prefix = AWS.util.isBrowser() ? 'X-Amz-' : '';
var customSuffix = '';
if (typeof customUserAgent === 'string' && customUserAgent) {
customSuffix += ' ' + customUserAgent;
}
this.headers[prefix + 'User-Agent'] = AWS.util.userAgent() + customSuffix;
},
pathname: function pathname() {
return this.path.split('?', 1)[0];
},
search: function search() {
var query = this.path.split('?', 2)[1];
if (query) {
query = AWS.util.queryStringParse(query);
return AWS.util.queryParamsToString(query);
}
return '';
}
});
AWS.HttpResponse = inherit({
constructor: function HttpResponse() {
this.statusCode = undefined;
this.headers = {};
this.body = undefined;
this.streaming = false;
this.stream = null;
},
createUnbufferedStream: function createUnbufferedStream() {
this.streaming = true;
return this.stream;
}
});
AWS.HttpClient = inherit({});
AWS.HttpClient.getInstance = function getInstance() {
if (this.singleton === undefined) {
this.singleton = new this();
}
return this.singleton;
};
},{"./core":3}],12:[function(require,module,exports){
var AWS = require('../core');
var EventEmitter = require('events').EventEmitter;
require('../http');
AWS.XHRClient = AWS.util.inherit({
handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) {
var self = this;
var endpoint = httpRequest.endpoint;
var emitter = new EventEmitter();
var href = endpoint.protocol + '//' + endpoint.hostname;
if (endpoint.port !== 80 && endpoint.port !== 443) {
href += ':' + endpoint.port;
}
href += httpRequest.path;
var xhr = new XMLHttpRequest(), headersEmitted = false;
httpRequest.stream = xhr;
xhr.addEventListener('readystatechange', function() {
try {
if (xhr.status === 0) return; // 0 code is invalid
} catch (e) { return; }
if (this.readyState >= this.HEADERS_RECEIVED && !headersEmitted) {
try { xhr.responseType = 'arraybuffer'; } catch (e) {}
emitter.statusCode = xhr.status;
emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders());
emitter.emit('headers', emitter.statusCode, emitter.headers);
headersEmitted = true;
}
if (this.readyState === this.DONE) {
self.finishRequest(xhr, emitter);
}
}, false);
xhr.upload.addEventListener('progress', function (evt) {
emitter.emit('sendProgress', evt);
});
xhr.addEventListener('progress', function (evt) {
emitter.emit('receiveProgress', evt);
}, false);
xhr.addEventListener('timeout', function () {
errCallback(AWS.util.error(new Error('Timeout'), {code: 'TimeoutError'}));
}, false);
xhr.addEventListener('error', function () {
errCallback(AWS.util.error(new Error('Network Failure'), {
code: 'NetworkingError'
}));
}, false);
callback(emitter);
xhr.open(httpRequest.method, href, httpOptions.xhrAsync !== false);
AWS.util.each(httpRequest.headers, function (key, value) {
if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') {
xhr.setRequestHeader(key, value);
}
});
if (httpOptions.timeout && httpOptions.xhrAsync !== false) {
xhr.timeout = httpOptions.timeout;
}
if (httpOptions.xhrWithCredentials) {
xhr.withCredentials = true;
}
try {
xhr.send(httpRequest.body);
} catch (err) {
if (httpRequest.body && typeof httpRequest.body.buffer === 'object') {
xhr.send(httpRequest.body.buffer); // send ArrayBuffer directly
} else {
throw err;
}
}
return emitter;
},
parseHeaders: function parseHeaders(rawHeaders) {
var headers = {};
AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) {
var key = line.split(':', 1)[0];
var value = line.substring(key.length + 2);
if (key.length > 0) headers[key.toLowerCase()] = value;
});
return headers;
},
finishRequest: function finishRequest(xhr, emitter) {
var buffer;
if (xhr.responseType === 'arraybuffer' && xhr.response) {
var ab = xhr.response;
buffer = new AWS.util.Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
}
try {
if (!buffer && typeof xhr.responseText === 'string') {
buffer = new AWS.util.Buffer(xhr.responseText);
}
} catch (e) {}
if (buffer) emitter.emit('data', buffer);
emitter.emit('end');
}
});
AWS.HttpClient.prototype = AWS.XHRClient.prototype;
AWS.HttpClient.streamsApiVersion = 1;
},{"../core":3,"../http":11,"events":56}],13:[function(require,module,exports){
var util = require('../util');
function JsonBuilder() { }
JsonBuilder.prototype.build = function(value, shape) {
return JSON.stringify(translate(value, shape));
};
function translate(value, shape) {
if (!shape || value === undefined || value === null) return undefined;
switch (shape.type) {
case 'structure': return translateStructure(value, shape);
case 'map': return translateMap(value, shape);
case 'list': return translateList(value, shape);
default: return translateScalar(value, shape);
}
}
function translateStructure(structure, shape) {
var struct = {};
util.each(structure, function(name, value) {
var memberShape = shape.members[name];
if (memberShape) {
if (memberShape.location !== 'body') return;
var locationName = memberShape.isLocationName ? memberShape.name : name;
var result = translate(value, memberShape);
if (result !== undefined) struct[locationName] = result;
}
});
return struct;
}
function translateList(list, shape) {
var out = [];
util.arrayEach(list, function(value) {
var result = translate(value, shape.member);
if (result !== undefined) out.push(result);
});
return out;
}
function translateMap(map, shape) {
var out = {};
util.each(map, function(key, value) {
var result = translate(value, shape.value);
if (result !== undefined) out[key] = result;
});
return out;
}
function translateScalar(value, shape) {
return shape.toWireFormat(value);
}
module.exports = JsonBuilder;
},{"../util":44}],14:[function(require,module,exports){
var util = require('../util');
function JsonParser() { }
JsonParser.prototype.parse = function(value, shape) {
return translate(JSON.parse(value), shape);
};
function translate(value, shape) {
if (!shape || value === undefined) return undefined;
switch (shape.type) {
case 'structure': return translateStructure(value, shape);
case 'map': return translateMap(value, shape);
case 'list': return translateList(value, shape);
default: return translateScalar(value, shape);
}
}
function translateStructure(structure, shape) {
if (structure == null) return undefined;
var struct = {};
var shapeMembers = shape.members;
util.each(shapeMembers, function(name, memberShape) {
var locationName = memberShape.isLocationName ? memberShape.name : name;
if (structure.hasOwnProperty(locationName)) {
var value = structure[locationName];
var result = translate(value, memberShape);
if (result !== undefined) struct[name] = result;
}
});
return struct;
}
function translateList(list, shape) {
if (list == null) return undefined;
var out = [];
util.arrayEach(list, function(value) {
var result = translate(value, shape.member);
if (result === undefined) out.push(null);
else out.push(result);
});
return out;
}
function translateMap(map, shape) {
if (map == null) return undefined;
var out = {};
util.each(map, function(key, value) {
var result = translate(value, shape.value);
if (result === undefined) out[key] = null;
else out[key] = result;
});
return out;
}
function translateScalar(value, shape) {
return shape.toType(value);
}
module.exports = JsonParser;
},{"../util":44}],15:[function(require,module,exports){
var Collection = require('./collection');
var Operation = require('./operation');
var Shape = require('./shape');
var Paginator = require('./paginator');
var ResourceWaiter = require('./resource_waiter');
var util = require('../util');
var property = util.property;
var memoizedProperty = util.memoizedProperty;
function Api(api, options) {
api = api || {};
options = options || {};
options.api = this;
api.metadata = api.metadata || {};
property(this, 'isApi', true, false);
property(this, 'apiVersion', api.metadata.apiVersion);
property(this, 'endpointPrefix', api.metadata.endpointPrefix);
property(this, 'signingName', api.metadata.signingName);
property(this, 'globalEndpoint', api.metadata.globalEndpoint);
property(this, 'signatureVersion', api.metadata.signatureVersion);
property(this, 'jsonVersion', api.metadata.jsonVersion);
property(this, 'targetPrefix', api.metadata.targetPrefix);
property(this, 'protocol', api.metadata.protocol);
property(this, 'timestampFormat', api.metadata.timestampFormat);
property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace);
property(this, 'abbreviation', api.metadata.serviceAbbreviation);
property(this, 'fullName', api.metadata.serviceFullName);
memoizedProperty(this, 'className', function() {
var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName;
if (!name) return null;
name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, '');
if (name === 'ElasticLoadBalancing') name = 'ELB';
return name;
});
property(this, 'operations', new Collection(api.operations, options, function(name, operation) {
return new Operation(name, operation, options);
}, util.string.lowerFirst));
property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) {
return Shape.create(shape, options);
}));
property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) {
return new Paginator(name, paginator, options);
}));
property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) {
return new ResourceWaiter(name, waiter, options);
}, util.string.lowerFirst));
if (options.documentation) {
property(this, 'documentation', api.documentation);
property(this, 'documentationUrl', api.documentationUrl);
}
}
module.exports = Api;
},{"../util":44,"./collection":16,"./operation":17,"./paginator":18,"./resource_waiter":19,"./shape":20}],16:[function(require,module,exports){
var memoizedProperty = require('../util').memoizedProperty;
function memoize(name, value, fn, nameTr) {
memoizedProperty(this, nameTr(name), function() {
return fn(name, value);
});
}
function Collection(iterable, options, fn, nameTr) {
nameTr = nameTr || String;
var self = this;
for (var id in iterable) {
if (iterable.hasOwnProperty(id)) {
memoize.call(self, id, iterable[id], fn, nameTr);
}
}
}
module.exports = Collection;
},{"../util":44}],17:[function(require,module,exports){
var Shape = require('./shape');
var util = require('../util');
var property = util.property;
var memoizedProperty = util.memoizedProperty;
function Operation(name, operation, options) {
options = options || {};
property(this, 'name', operation.name || name);
property(this, 'api', options.api, false);
operation.http = operation.http || {};
property(this, 'httpMethod', operation.http.method || 'POST');
property(this, 'httpPath', operation.http.requestUri || '/');
memoizedProperty(this, 'input', function() {
if (!operation.input) {
return new Shape.create({type: 'structure'}, options);
}
return Shape.create(operation.input, options);
});
memoizedProperty(this, 'output', function() {
if (!operation.output) {
return new Shape.create({type: 'structure'}, options);
}
return Shape.create(operation.output, options);
});
memoizedProperty(this, 'errors', function() {
var list = [];
if (!operation.errors) return null;
for (var i = 0; i < operation.errors.length; i++) {
list.push(Shape.create(operation.errors[i], options));
}
return list;
});
memoizedProperty(this, 'paginator', function() {
return options.api.paginators[name];
});
if (options.documentation) {
property(this, 'documentation', operation.documentation);
property(this, 'documentationUrl', operation.documentationUrl);
}
}
module.exports = Operation;
},{"../util":44,"./shape":20}],18:[function(require,module,exports){
var property = require('../util').property;
function Paginator(name, paginator) {
property(this, 'inputToken', paginator.input_token);
property(this, 'limitKey', paginator.limit_key);
property(this, 'moreResults', paginator.more_results);
property(this, 'outputToken', paginator.output_token);
property(this, 'resultKey', paginator.result_key);
}
module.exports = Paginator;
},{"../util":44}],19:[function(require,module,exports){
var util = require('../util');
var property = util.property;
function ResourceWaiter(name, waiter, options) {
options = options || {};
function InnerResourceWaiter() {
property(this, 'name', name);
property(this, 'api', options.api, false);
if (waiter.operation) {
property(this, 'operation', util.string.lowerFirst(waiter.operation));
}
var self = this, map = {
ignoreErrors: 'ignore_errors',
successType: 'success_type',
successValue: 'success_value',
successPath: 'success_path',
acceptorType: 'acceptor_type',
acceptorValue: 'acceptor_value',
acceptorPath: 'acceptor_path',
failureType: 'failure_type',
failureValue: 'failure_value',
failurePath: 'success_path',
interval: 'interval',
maxAttempts: 'max_attempts'
};
Object.keys(map).forEach(function(key) {
var value = waiter[map[key]];
if (value) property(self, key, value);
});
}
if (options.api) {
var proto = null;
if (waiter['extends']) {
proto = options.api.waiters[waiter['extends']];
} else if (name !== '__default__') {
proto = options.api.waiters['__default__'];
}
if (proto) InnerResourceWaiter.prototype = proto;
}
return new InnerResourceWaiter();
}
module.exports = ResourceWaiter;
},{"../util":44}],20:[function(require,module,exports){
var Collection = require('./collection');
var util = require('../util');
function property(obj, name, value) {
if (value !== null && value !== undefined) {
util.property.apply(this, arguments);
}
}
function memoizedProperty(obj, name) {
if (!obj.constructor.prototype[name]) {
util.memoizedProperty.apply(this, arguments);
}
}
function Shape(shape, options, memberName) {
options = options || {};
property(this, 'shape', shape.shape);
property(this, 'api', options.api, false);
property(this, 'type', shape.type);
property(this, 'enum', shape.enum);
property(this, 'min', shape.min);
property(this, 'max', shape.max);
property(this, 'pattern', shape.pattern);
property(this, 'location', shape.location || this.location || 'body');
property(this, 'name', this.name || shape.xmlName || shape.queryName ||
shape.locationName || memberName);
property(this, 'isStreaming', shape.streaming || this.isStreaming || false);
property(this, 'isComposite', shape.isComposite || false);
property(this, 'isShape', true, false);
property(this, 'isQueryName', shape.queryName ? true : false, false);
property(this, 'isLocationName', shape.locationName ? true : false, false);
if (options.documentation) {
property(this, 'documentation', shape.documentation);
property(this, 'documentationUrl', shape.documentationUrl);
}
if (shape.xmlAttribute) {
property(this, 'isXmlAttribute', shape.xmlAttribute || false);
}
property(this, 'defaultValue', null);
this.toWireFormat = function(value) {
if (value === null || value === undefined) return '';
return value;
};
this.toType = function(value) { return value; };
}
Shape.normalizedTypes = {
character: 'string',
double: 'float',
long: 'integer',
short: 'integer',
biginteger: 'integer',
bigdecimal: 'float',
blob: 'binary'
};
Shape.types = {
'structure': StructureShape,
'list': ListShape,
'map': MapShape,
'boolean': BooleanShape,
'timestamp': TimestampShape,
'float': FloatShape,
'integer': IntegerShape,
'string': StringShape,
'base64': Base64Shape,
'binary': BinaryShape
};
Shape.resolve = function resolve(shape, options) {
if (shape.shape) {
var refShape = options.api.shapes[shape.shape];
if (!refShape) {
throw new Error('Cannot find shape reference: ' + shape.shape);
}
return refShape;
} else {
return null;
}
};
Shape.create = function create(shape, options, memberName) {
if (shape.isShape) return shape;
var refShape = Shape.resolve(shape, options);
if (refShape) {
var filteredKeys = Object.keys(shape);
if (!options.documentation) {
filteredKeys = filteredKeys.filter(function(name) {
return !name.match(/documentation/);
});
}
if (filteredKeys === ['shape']) { // no inline customizations
return refShape;
}
var InlineShape = function() {
refShape.constructor.call(this, shape, options, memberName);
};
InlineShape.prototype = refShape;
return new InlineShape();
} else {
if (!shape.type) {
if (shape.members) shape.type = 'structure';
else if (shape.member) shape.type = 'list';
else if (shape.key) shape.type = 'map';
else shape.type = 'string';
}
var origType = shape.type;
if (Shape.normalizedTypes[shape.type]) {
shape.type = Shape.normalizedTypes[shape.type];
}
if (Shape.types[shape.type]) {
return new Shape.types[shape.type](shape, options, memberName);
} else {
throw new Error('Unrecognized shape type: ' + origType);
}
}
};
function CompositeShape(shape) {
Shape.apply(this, arguments);
property(this, 'isComposite', true);
if (shape.flattened) {
property(this, 'flattened', shape.flattened || false);
}
}
function StructureShape(shape, options) {
var requiredMap = null, firstInit = !this.isShape;
CompositeShape.apply(this, arguments);
if (firstInit) {
property(this, 'defaultValue', function() { return {}; });
property(this, 'members', {});
property(this, 'memberNames', []);
property(this, 'required', []);
property(this, 'isRequired', function() { return false; });
}
if (shape.members) {
property(this, 'members', new Collection(shape.members, options, function(name, member) {
return Shape.create(member, options, name);
}));
memoizedProperty(this, 'memberNames', function() {
return shape.xmlOrder || Object.keys(shape.members);
});
}
if (shape.required) {
property(this, 'required', shape.required);
property(this, 'isRequired', function(name) {
if (!requiredMap) {
requiredMap = {};
for (var i = 0; i < shape.required.length; i++) {
requiredMap[shape.required[i]] = true;
}
}
return requiredMap[name];
}, false, true);
}
property(this, 'resultWrapper', shape.resultWrapper || null);
if (shape.payload) {
property(this, 'payload', shape.payload);
}
if (typeof shape.xmlNamespace === 'string') {
property(this, 'xmlNamespaceUri', shape.xmlNamespace);
} else if (typeof shape.xmlNamespace === 'object') {
property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix);
property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri);
}
}
function ListShape(shape, options) {
var self = this, firstInit = !this.isShape;
CompositeShape.apply(this, arguments);
if (firstInit) {
property(this, 'defaultValue', function() { return []; });
}
if (shape.member) {
memoizedProperty(this, 'member', function() {
return Shape.create(shape.member, options);
});
}
if (this.flattened) {
var oldName = this.name;
memoizedProperty(this, 'name', function() {
return self.member.name || oldName;
});
}
}
function MapShape(shape, options) {
var firstInit = !this.isShape;
CompositeShape.apply(this, arguments);
if (firstInit) {
property(this, 'defaultValue', function() { return {}; });
property(this, 'key', Shape.create({type: 'string'}, options));
property(this, 'value', Shape.create({type: 'string'}, options));
}
if (shape.key) {
memoizedProperty(this, 'key', function() {
return Shape.create(shape.key, options);
});
}
if (shape.value) {
memoizedProperty(this, 'value', function() {
return Shape.create(shape.value, options);
});
}
}
function TimestampShape(shape) {
var self = this;
Shape.apply(this, arguments);
if (this.location === 'header') {
property(this, 'timestampFormat', 'rfc822');
} else if (shape.timestampFormat) {
property(this, 'timestampFormat', shape.timestampFormat);
} else if (this.api) {
if (this.api.timestampFormat) {
property(this, 'timestampFormat', this.api.timestampFormat);
} else {
switch (this.api.protocol) {
case 'json':
case 'rest-json':
property(this, 'timestampFormat', 'unixTimestamp');
break;
case 'rest-xml':
case 'query':
case 'ec2':
property(this, 'timestampFormat', 'iso8601');
break;
}
}
}
this.toType = function(value) {
if (value === null || value === undefined) return null;
if (typeof value.toUTCString === 'function') return value;
return typeof value === 'string' || typeof value === 'number' ?
util.date.parseTimestamp(value) : null;
};
this.toWireFormat = function(value) {
return util.date.format(value, self.timestampFormat);
};
}
function StringShape() {
Shape.apply(this, arguments);
if (this.api) {
switch (this.api.protocol) {
case 'rest-xml':
case 'query':
case 'ec2':
this.toType = function(value) { return value || ''; };
}
}
}
function FloatShape() {
Shape.apply(this, arguments);
this.toType = function(value) {
if (value === null || value === undefined) return null;
return parseFloat(value);
};
this.toWireFormat = this.toType;
}
function IntegerShape() {
Shape.apply(this, arguments);
this.toType = function(value) {
if (value === null || value === undefined) return null;
return parseInt(value, 10);
};
this.toWireFormat = this.toType;
}
function BinaryShape() {
Shape.apply(this, arguments);
this.toType = util.base64.decode;
this.toWireFormat = util.base64.encode;
}
function Base64Shape() {
BinaryShape.apply(this, arguments);
}
function BooleanShape() {
Shape.apply(this, arguments);
this.toType = function(value) {
if (typeof value === 'boolean') return value;
if (value === null || value === undefined) return null;
return value === 'true';
};
}
Shape.shapes = {
StructureShape: StructureShape,
ListShape: ListShape,
MapShape: MapShape,
StringShape: StringShape,
BooleanShape: BooleanShape,
Base64Shape: Base64Shape
};
module.exports = Shape;
},{"../util":44,"./collection":16}],21:[function(require,module,exports){
var AWS = require('./core');
AWS.ParamValidator = AWS.util.inherit({
constructor: function ParamValidator(validation) {
if (validation === true || validation === undefined) {
validation = {'min': true};
}
this.validation = validation;
},
validate: function validate(shape, params, context) {
this.errors = [];
this.validateMember(shape, params || {}, context || 'params');
if (this.errors.length > 1) {
var msg = this.errors.join('\n* ');
msg = 'There were ' + this.errors.length +
' validation errors:\n* ' + msg;
throw AWS.util.error(new Error(msg),
{code: 'MultipleValidationErrors', errors: this.errors});
} else if (this.errors.length === 1) {
throw this.errors[0];
} else {
return true;
}
},
fail: function fail(code, message) {
this.errors.push(AWS.util.error(new Error(message), {code: code}));
},
validateStructure: function validateStructure(shape, params, context) {
this.validateType(params, context, ['object'], 'structure');
var paramName;
for (var i = 0; shape.required && i < shape.required.length; i++) {
paramName = shape.required[i];
var value = params[paramName];
if (value === undefined || value === null) {
this.fail('MissingRequiredParameter',
'Missing required key \'' + paramName + '\' in ' + context);
}
}
for (paramName in params) {
if (!params.hasOwnProperty(paramName)) continue;
var paramValue = params[paramName],
memberShape = shape.members[paramName];
if (memberShape !== undefined) {
var memberContext = [context, paramName].join('.');
this.validateMember(memberShape, paramValue, memberContext);
} else {
this.fail('UnexpectedParameter',
'Unexpected key \'' + paramName + '\' found in ' + context);
}
}
return true;
},
validateMember: function validateMember(shape, param, context) {
switch (shape.type) {
case 'structure':
return this.validateStructure(shape, param, context);
case 'list':
return this.validateList(shape, param, context);
case 'map':
return this.validateMap(shape, param, context);
default:
return this.validateScalar(shape, param, context);
}
},
validateList: function validateList(shape, params, context) {
if (this.validateType(params, context, [Array])) {
this.validateRange(shape, params.length, context, 'list member count');
for (var i = 0; i < params.length; i++) {
this.validateMember(shape.member, params[i], context + '[' + i + ']');
}
}
},
validateMap: function validateMap(shape, params, context) {
if (this.validateType(params, context, ['object'], 'map')) {
var mapCount = 0;
for (var param in params) {
if (!params.hasOwnProperty(param)) continue;
this.validateMember(shape.key, param,
context + '[key=\'' + param + '\']')
this.validateMember(shape.value, params[param],
context + '[\'' + param + '\']');
mapCount++;
}
this.validateRange(shape, mapCount, context, 'map member count');
}
},
validateScalar: function validateScalar(shape, value, context) {
switch (shape.type) {
case null:
case undefined:
case 'string':
return this.validateString(shape, value, context);
case 'base64':
case 'binary':
return this.validatePayload(value, context);
case 'integer':
case 'float':
return this.validateNumber(shape, value, context);
case 'boolean':
return this.validateType(value, context, ['boolean']);
case 'timestamp':
return this.validateType(value, context, [Date,
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'],
'Date object, ISO-8601 string, or a UNIX timestamp');
default:
return this.fail('UnkownType', 'Unhandled type ' +
shape.type + ' for ' + context);
}
},
validateString: function validateString(shape, value, context) {
if (this.validateType(value, context, ['string'])) {
this.validateEnum(shape, value, context);
this.validateRange(shape, value.length, context, 'string length');
this.validatePattern(shape, value, context);
}
},
validatePattern: function validatePattern(shape, value, context) {
if (this.validation['pattern'] && shape['pattern'] !== undefined) {
if (!(new RegExp(shape['pattern'])).test(value)) {
this.fail('PatternMatchError', 'Provided value "' + value + '" '
+ 'does not match regex pattern /' + shape['pattern'] + '/ for '
+ context);
}
}
},
validateRange: function validateRange(shape, value, context, descriptor) {
if (this.validation['min']) {
if (shape['min'] !== undefined && value < shape['min']) {
this.fail('MinRangeError', 'Expected ' + descriptor + ' >= '
+ shape['min'] + ', but found ' + value + ' for ' + context);
}
}
if (this.validation['max']) {
if (shape['max'] !== undefined && value > shape['max']) {
this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= '
+ shape['max'] + ', but found ' + value + ' for ' + context);
}
}
},
validateEnum: function validateRange(shape, value, context) {
if (this.validation['enum'] && shape['enum'] !== undefined) {
if (shape['enum'].indexOf(value) === -1) {
this.fail('EnumError', 'Found string value of ' + value + ', but '
+ 'expected ' + shape['enum'].join('|') + ' for ' + context);
}
}
},
validateType: function validateType(value, context, acceptedTypes, type) {
if (value === null || value === undefined) return false;
var foundInvalidType = false;
for (var i = 0; i < acceptedTypes.length; i++) {
if (typeof acceptedTypes[i] === 'string') {
if (typeof value === acceptedTypes[i]) return true;
} else if (acceptedTypes[i] instanceof RegExp) {
if ((value || '').toString().match(acceptedTypes[i])) return true;
} else {
if (value instanceof acceptedTypes[i]) return true;
if (AWS.util.isType(value, acceptedTypes[i])) return true;
if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice();
acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]);
}
foundInvalidType = true;
}
var acceptedType = type;
if (!acceptedType) {
acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1');
}
var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : '';
this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' +
vowel + ' ' + acceptedType);
return false;
},
validateNumber: function validateNumber(shape, value, context) {
if (value === null || value === undefined) return;
if (typeof value === 'string') {
var castedValue = parseFloat(value);
if (castedValue.toString() === value) value = castedValue;
}
if (this.validateType(value, context, ['number'])) {
this.validateRange(shape, value, context, 'numeric value');
}
},
validatePayload: function validatePayload(value, context) {
if (value === null || value === undefined) return;
if (typeof value === 'string') return;
if (value && typeof value.byteLength === 'number') return; // typed arrays
if (AWS.util.isNode()) { // special check for buffer/stream in Node.js
var Stream = AWS.util.nodeRequire('stream').Stream;
if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return;
}
var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView'];
if (value) {
for (var i = 0; i < types.length; i++) {
if (AWS.util.isType(value, types[i])) return;
if (AWS.util.typeName(value.constructor) === types[i]) return;
}
}
this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' +
'string, Buffer, Stream, Blob, or typed array object');
}
});
},{"./core":3}],22:[function(require,module,exports){
var util = require('../util');
var JsonBuilder = require('../json/builder');
var JsonParser = require('../json/parser');
function buildRequest(req) {
var httpRequest = req.httpRequest;
var api = req.service.api;
var target = api.targetPrefix + '.' + api.operations[req.operation].name;
var version = api.jsonVersion || '1.0';
var input = api.operations[req.operation].input;
var builder = new JsonBuilder();
if (version === 1) version = '1.0';
httpRequest.body = builder.build(req.params || {}, input);
httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
httpRequest.headers['X-Amz-Target'] = target;
}
function extractError(resp) {
var error = {};
var httpResponse = resp.httpResponse;
error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
if (typeof error.code === 'string') {
error.code = error.code.split(':')[0];
}
if (httpResponse.body.length > 0) {
var e = JSON.parse(httpResponse.body.toString());
if (e.__type || e.code) {
error.code = (e.__type || e.code).split('#').pop();
}
if (error.code === 'RequestEntityTooLarge') {
error.message = 'Request body must be less than 1 MB';
} else {
error.message = (e.message || e.Message || null);
}
} else {
error.statusCode = httpResponse.statusCode;
error.message = httpResponse.statusCode.toString();
}
resp.error = util.error(new Error(), error);
}
function extractData(resp) {
var body = resp.httpResponse.body.toString() || '{}';
if (resp.request.service.config.convertResponseTypes === false) {
resp.data = JSON.parse(body);
} else {
var operation = resp.request.service.api.operations[resp.request.operation];
var shape = operation.output || {};
var parser = new JsonParser();
resp.data = parser.parse(body, shape);
}
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
},{"../json/builder":13,"../json/parser":14,"../util":44}],23:[function(require,module,exports){
var AWS = require('../core');
var util = require('../util');
var QueryParamSerializer = require('../query/query_param_serializer');
var Shape = require('../model/shape');
function buildRequest(req) {
var operation = req.service.api.operations[req.operation];
var httpRequest = req.httpRequest;
httpRequest.headers['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
httpRequest.params = {
Version: req.service.api.apiVersion,
Action: operation.name
};
var builder = new QueryParamSerializer();
builder.serialize(req.params, operation.input, function(name, value) {
httpRequest.params[name] = value;
});
httpRequest.body = util.queryParamsToString(httpRequest.params);
}
function extractError(resp) {
var data, body = resp.httpResponse.body.toString();
if (body.match('<UnknownOperationException')) {
data = {
Code: 'UnknownOperation',
Message: 'Unknown operation ' + resp.request.operation
};
} else {
data = new AWS.XML.Parser().parse(body);
}
if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
if (data.Errors) data = data.Errors;
if (data.Error) data = data.Error;
if (data.Code) {
resp.error = util.error(new Error(), {
code: data.Code,
message: data.Message
});
} else {
resp.error = util.error(new Error(), {
code: resp.httpResponse.statusCode,
message: null
});
}
}
function extractData(resp) {
var req = resp.request;
var operation = req.service.api.operations[req.operation];
var shape = operation.output || {};
var origRules = shape;
if (origRules.resultWrapper) {
var tmp = Shape.create({type: 'structure'});
tmp.members[origRules.resultWrapper] = shape;
tmp.memberNames = [origRules.resultWrapper];
util.property(shape, 'name', shape.resultWrapper);
shape = tmp;
}
var parser = new AWS.XML.Parser();
if (shape && shape.members && !shape.members._XAMZRequestId) {
var requestIdShape = Shape.create(
{ type: 'string' },
{ api: { protocol: 'query' } },
'requestId'
);
shape.members._XAMZRequestId = requestIdShape;
}
var data = parser.parse(resp.httpResponse.body.toString(), shape);
resp.requestId = data._XAMZRequestId || data.requestId;
if (data._XAMZRequestId) delete data._XAMZRequestId;
if (origRules.resultWrapper) {
if (data[origRules.resultWrapper]) {
util.update(data, data[origRules.resultWrapper]);
delete data[origRules.resultWrapper];
}
}
resp.data = data;
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
},{"../core":3,"../model/shape":20,"../query/query_param_serializer":27,"../util":44}],24:[function(require,module,exports){
var util = require('../util');
function populateMethod(req) {
req.httpRequest.method = req.service.api.operations[req.operation].httpMethod;
}
function populateURI(req) {
var operation = req.service.api.operations[req.operation];
var input = operation.input;
var uri = [req.httpRequest.endpoint.path, operation.httpPath].join('/');
uri = uri.replace(/\/+/g, '/');
var queryString = {}, queryStringSet = false;
util.each(input.members, function (name, member) {
var paramValue = req.params[name];
if (paramValue === null || paramValue === undefined) return;
if (member.location === 'uri') {
var regex = new RegExp('\\{' + member.name + '(\\+)?\\}');
uri = uri.replace(regex, function(_, plus) {
var fn = plus ? util.uriEscapePath : util.uriEscape;
return fn(String(paramValue));
});
} else if (member.location === 'querystring') {
queryStringSet = true;
if (member.type === 'list') {
queryString[member.name] = paramValue.map(function(val) {
return util.uriEscape(String(val));
});
} else if (member.type === 'map') {
util.each(paramValue, function(key, value) {
if (Array.isArray(value)) {
queryString[key] = value.map(function(val) {
return util.uriEscape(String(val));
});
} else {
queryString[key] = util.uriEscape(String(value));
}
});
} else {
queryString[member.name] = util.uriEscape(String(paramValue));
}
}
});
if (queryStringSet) {
uri += (uri.indexOf('?') >= 0 ? '&' : '?');
var parts = [];
util.arrayEach(Object.keys(queryString).sort(), function(key) {
if (!Array.isArray(queryString[key])) {
queryString[key] = [queryString[key]];
}
for (var i = 0; i < queryString[key].length; i++) {
parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]);
}
});
uri += parts.join('&');
}
req.httpRequest.path = uri;
}
function populateHeaders(req) {
var operation = req.service.api.operations[req.operation];
util.each(operation.input.members, function (name, member) {
var value = req.params[name];
if (value === null || value === undefined) return;
if (member.location === 'headers' && member.type === 'map') {
util.each(value, function(key, memberValue) {
req.httpRequest.headers[member.name + key] = memberValue;
});
} else if (member.location === 'header') {
value = member.toWireFormat(value).toString();
req.httpRequest.headers[member.name] = value;
}
});
}
function buildRequest(req) {
populateMethod(req);
populateURI(req);
populateHeaders(req);
}
function extractError() {
}
function extractData(resp) {
var req = resp.request;
var data = {};
var r = resp.httpResponse;
var operation = req.service.api.operations[req.operation];
var output = operation.output;
var headers = {};
util.each(r.headers, function (k, v) {
headers[k.toLowerCase()] = v;
});
util.each(output.members, function(name, member) {
var header = (member.name || name).toLowerCase();
if (member.location === 'headers' && member.type === 'map') {
data[name] = {};
var location = member.isLocationName ? member.name : '';
var pattern = new RegExp('^' + location + '(.+)', 'i');
util.each(r.headers, function (k, v) {
var result = k.match(pattern);
if (result !== null) {
data[name][result[1]] = v;
}
});
} else if (member.location === 'header') {
if (headers[header] !== undefined) {
data[name] = headers[header];
}
} else if (member.location === 'statusCode') {
data[name] = parseInt(r.statusCode, 10);
}
});
resp.data = data;
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
},{"../util":44}],25:[function(require,module,exports){
var util = require('../util');
var Rest = require('./rest');
var Json = require('./json');
var JsonBuilder = require('../json/builder');
var JsonParser = require('../json/parser');
function populateBody(req) {
var builder = new JsonBuilder();
var input = req.service.api.operations[req.operation].input;
if (input.payload) {
var params = {};
var payloadShape = input.members[input.payload];
params = req.params[input.payload];
if (params === undefined) return;
if (payloadShape.type === 'structure') {
req.httpRequest.body = builder.build(params, payloadShape);
} else { // non-JSON payload
req.httpRequest.body = params;
}
} else {
req.httpRequest.body = builder.build(req.params, input);
}
}
function buildRequest(req) {
Rest.buildRequest(req);
if (['GET', 'HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) {
populateBody(req);
}
}
function extractError(resp) {
Json.extractError(resp);
}
function extractData(resp) {
Rest.extractData(resp);
var req = resp.request;
var rules = req.service.api.operations[req.operation].output || {};
if (rules.payload) {
var payloadMember = rules.members[rules.payload];
var body = resp.httpResponse.body;
if (payloadMember.isStreaming) {
resp.data[rules.payload] = body;
} else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
var parser = new JsonParser();
resp.data[rules.payload] = parser.parse(body, payloadMember);
} else {
resp.data[rules.payload] = body.toString();
}
} else {
var data = resp.data;
Json.extractData(resp);
resp.data = util.merge(data, resp.data);
}
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
},{"../json/builder":13,"../json/parser":14,"../util":44,"./json":22,"./rest":24}],26:[function(require,module,exports){
var AWS = require('../core');
var util = require('../util');
var Rest = require('./rest');
function populateBody(req) {
var input = req.service.api.operations[req.operation].input;
var builder = new AWS.XML.Builder();
var params = req.params;
var payload = input.payload;
if (payload) {
var payloadMember = input.members[payload];
params = params[payload];
if (params === undefined) return;
if (payloadMember.type === 'structure') {
var rootElement = payloadMember.name;
req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true);
} else { // non-xml payload
req.httpRequest.body = params;
}
} else {
req.httpRequest.body = builder.toXML(params, input, input.name ||
input.shape || util.string.upperFirst(req.operation) + 'Request');
}
}
function buildRequest(req) {
Rest.buildRequest(req);
if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) {
populateBody(req);
}
}
function extractError(resp) {
Rest.extractError(resp);
var data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString());
if (data.Errors) data = data.Errors;
if (data.Error) data = data.Error;
if (data.Code) {
resp.error = util.error(new Error(), {
code: data.Code,
message: data.Message
});
} else {
resp.error = util.error(new Error(), {
code: resp.httpResponse.statusCode,
message: null
});
}
}
function extractData(resp) {
Rest.extractData(resp);
var parser;
var req = resp.request;
var body = resp.httpResponse.body;
var operation = req.service.api.operations[req.operation];
var output = operation.output;
var payload = output.payload;
if (payload) {
var payloadMember = output.members[payload];
if (payloadMember.isStreaming) {
resp.data[payload] = body;
} else if (payloadMember.type === 'structure') {
parser = new AWS.XML.Parser();
resp.data[payload] = parser.parse(body.toString(), payloadMember);
} else {
resp.data[payload] = body.toString();
}
} else if (body.length > 0) {
parser = new AWS.XML.Parser();
var data = parser.parse(body.toString(), output);
util.update(resp.data, data);
}
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
},{"../core":3,"../util":44,"./rest":24}],27:[function(require,module,exports){
var util = require('../util');
function QueryParamSerializer() {
}
QueryParamSerializer.prototype.serialize = function(params, shape, fn) {
serializeStructure('', params, shape, fn);
};
function ucfirst(shape) {
if (shape.isQueryName || shape.api.protocol !== 'ec2') {
return shape.name;
} else {
return shape.name[0].toUpperCase() + shape.name.substr(1);
}
}
function serializeStructure(prefix, struct, rules, fn) {
util.each(rules.members, function(name, member) {
var value = struct[name];
if (value === null || value === undefined) return;
var memberName = ucfirst(member);
memberName = prefix ? prefix + '.' + memberName : memberName;
serializeMember(memberName, value, member, fn);
});
}
function serializeMap(name, map, rules, fn) {
var i = 1;
util.each(map, function (key, value) {
var prefix = rules.flattened ? '.' : '.entry.';
var position = prefix + (i++) + '.';
var keyName = position + (rules.key.name || 'key');
var valueName = position + (rules.value.name || 'value');
serializeMember(name + keyName, key, rules.key, fn);
serializeMember(name + valueName, value, rules.value, fn);
});
}
function serializeList(name, list, rules, fn) {
var memberRules = rules.member || {};
if (list.length === 0) {
fn.call(this, name, null);
return;
}
util.arrayEach(list, function (v, n) {
var suffix = '.' + (n + 1);
if (rules.api.protocol === 'ec2') {
suffix = suffix + ''; // make linter happy
} else if (rules.flattened) {
if (memberRules.name) {
var parts = name.split('.');
parts.pop();
parts.push(ucfirst(memberRules));
name = parts.join('.');
}
} else {
suffix = '.member' + suffix;
}
serializeMember(name + suffix, v, memberRules, fn);
});
}
function serializeMember(name, value, rules, fn) {
if (value === null || value === undefined) return;
if (rules.type === 'structure') {
serializeStructure(name, value, rules, fn);
} else if (rules.type === 'list') {
serializeList(name, value, rules, fn);
} else if (rules.type === 'map') {
serializeMap(name, value, rules, fn);
} else {
fn(name, rules.toWireFormat(value).toString());
}
}
module.exports = QueryParamSerializer;
},{"../util":44}],28:[function(require,module,exports){
var util = require('./util');
var regionConfig = require('./region_config.json');
function generateRegionPrefix(region) {
if (!region) return null;
var parts = region.split('-');
if (parts.length < 3) return null;
return parts.slice(0, parts.length - 2).join('-') + '-*';
}
function derivedKeys(service) {
var region = service.config.region;
var regionPrefix = generateRegionPrefix(region);
var endpointPrefix = service.api.endpointPrefix;
return [
[region, endpointPrefix],
[regionPrefix, endpointPrefix],
[region, '*'],
[regionPrefix, '*'],
['*', endpointPrefix],
['*', '*']
].map(function(item) {
return item[0] && item[1] ? item.join('/') : null;
});
}
function applyConfig(service, config) {
util.each(config, function(key, value) {
if (key === 'globalEndpoint') return;
if (service.config[key] === undefined || service.config[key] === null) {
service.config[key] = value;
}
});
}
function configureEndpoint(service) {
var keys = derivedKeys(service);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!key) continue;
if (regionConfig.rules.hasOwnProperty(key)) {
var config = regionConfig.rules[key];
if (typeof config === 'string') {
config = regionConfig.patterns[config];
}
service.isGlobalEndpoint = !!config.globalEndpoint;
if (!config.signatureVersion) config.signatureVersion = 'v4';
applyConfig(service, config);
return;
}
}
}
module.exports = configureEndpoint;
},{"./region_config.json":29,"./util":44}],29:[function(require,module,exports){
module.exports={
"rules": {
"*/*": {
"endpoint": "{service}.{region}.amazonaws.com"
},
"cn-*/*": {
"endpoint": "{service}.{region}.amazonaws.com.cn"
},
"*/cloudfront": "globalSSL",
"*/iam": "globalSSL",
"*/sts": "globalSSL",
"*/importexport": {
"endpoint": "{service}.amazonaws.com",
"signatureVersion": "v2",
"globalEndpoint": true
},
"*/route53": {
"endpoint": "https://{service}.amazonaws.com",
"signatureVersion": "v3https",
"globalEndpoint": true
},
"*/waf": "globalSSL",
"us-gov-*/iam": "globalGovCloud",
"us-gov-*/sts": {
"endpoint": "{service}.{region}.amazonaws.com"
},
"us-gov-west-1/s3": "s3dash",
"us-west-1/s3": "s3dash",
"us-west-2/s3": "s3dash",
"eu-west-1/s3": "s3dash",
"ap-southeast-1/s3": "s3dash",
"ap-southeast-2/s3": "s3dash",
"ap-northeast-1/s3": "s3dash",
"sa-east-1/s3": "s3dash",
"us-east-1/s3": {
"endpoint": "{service}.amazonaws.com",
"signatureVersion": "s3"
},
"us-east-1/sdb": {
"endpoint": "{service}.amazonaws.com",
"signatureVersion": "v2"
},
"*/sdb": {
"endpoint": "{service}.{region}.amazonaws.com",
"signatureVersion": "v2"
}
},
"patterns": {
"globalSSL": {
"endpoint": "https://{service}.amazonaws.com",
"globalEndpoint": true
},
"globalGovCloud": {
"endpoint": "{service}.us-gov.amazonaws.com"
},
"s3dash": {
"endpoint": "{service}-{region}.amazonaws.com",
"signatureVersion": "s3"
}
}
}
},{}],30:[function(require,module,exports){
(function (process){
var AWS = require('./core');
var AcceptorStateMachine = require('./state_machine');
var inherit = AWS.util.inherit;
var domain = AWS.util.nodeRequire('domain');
var hardErrorStates = {success: 1, error: 1, complete: 1};
function isTerminalState(machine) {
return hardErrorStates.hasOwnProperty(machine._asm.currentState);
}
var fsm = new AcceptorStateMachine();
fsm.setupStates = function() {
var transition = function(_, done) {
var self = this;
self._haltHandlersOnError = false;
self.emit(self._asm.currentState, function(err) {
if (err) {
if (isTerminalState(self)) {
if (domain && self.domain instanceof domain.Domain) {
err.domainEmitter = self;
err.domain = self.domain;
err.domainThrown = false;
self.domain.emit('error', err);
} else {
throw err;
}
} else {
self.response.error = err;
done(err);
}
} else {
done(self.response.error);
}
});
};
this.addState('validate', 'build', 'error', transition);
this.addState('build', 'afterBuild', 'restart', transition);
this.addState('afterBuild', 'sign', 'restart', transition);
this.addState('sign', 'send', 'retry', transition);
this.addState('retry', 'afterRetry', 'afterRetry', transition);
this.addState('afterRetry', 'sign', 'error', transition);
this.addState('send', 'validateResponse', 'retry', transition);
this.addState('validateResponse', 'extractData', 'extractError', transition);
this.addState('extractError', 'extractData', 'retry', transition);
this.addState('extractData', 'success', 'retry', transition);
this.addState('restart', 'build', 'error', transition);
this.addState('success', 'complete', 'complete', transition);
this.addState('error', 'complete', 'complete', transition);
this.addState('complete', null, null, transition);
};
fsm.setupStates();
AWS.Request = inherit({
constructor: function Request(service, operation, params) {
var endpoint = service.endpoint;
var region = service.config.region;
var customUserAgent = service.config.customUserAgent;
if (service.isGlobalEndpoint) region = 'us-east-1';
this.domain = domain && domain.active;
this.service = service;
this.operation = operation;
this.params = params || {};
this.httpRequest = new AWS.HttpRequest(endpoint, region, customUserAgent);
this.startTime = AWS.util.date.getDate();
this.response = new AWS.Response(this);
this._asm = new AcceptorStateMachine(fsm.states, 'validate');
this._haltHandlersOnError = false;
AWS.SequentialExecutor.call(this);
this.emit = this.emitEvent;
},
send: function send(callback) {
if (callback) {
this.on('complete', function (resp) {
callback.call(resp, resp.error, resp.data);
});
}
this.runTo();
return this.response;
},
build: function build(callback) {
return this.runTo('send', callback);
},
runTo: function runTo(state, done) {
this._asm.runTo(state, done, this);
return this;
},
abort: function abort() {
this.removeAllListeners('validateResponse');
this.removeAllListeners('extractError');
this.on('validateResponse', function addAbortedError(resp) {
resp.error = AWS.util.error(new Error('Request aborted by user'), {
code: 'RequestAbortedError', retryable: false
});
});
if (this.httpRequest.stream) { // abort HTTP stream
this.httpRequest.stream.abort();
if (this.httpRequest._abortCallback) {
this.httpRequest._abortCallback();
} else {
this.removeAllListeners('send'); // haven't sent yet, so let's not
}
}
return this;
},
eachPage: function eachPage(callback) {
callback = AWS.util.fn.makeAsync(callback, 3);
function wrappedCallback(response) {
callback.call(response, response.error, response.data, function (result) {
if (result === false) return;
if (response.hasNextPage()) {
response.nextPage().on('complete', wrappedCallback).send();
} else {
callback.call(response, null, null, AWS.util.fn.noop);
}
});
}
this.on('complete', wrappedCallback).send();
},
eachItem: function eachItem(callback) {
var self = this;
function wrappedCallback(err, data) {
if (err) return callback(err, null);
if (data === null) return callback(null, null);
var config = self.service.paginationConfig(self.operation);
var resultKey = config.resultKey;
if (Array.isArray(resultKey)) resultKey = resultKey[0];
var results = AWS.util.jamespath.query(resultKey, data);
AWS.util.arrayEach(results, function(result) {
AWS.util.arrayEach(result, function(item) { callback(null, item); });
});
}
this.eachPage(wrappedCallback);
},
isPageable: function isPageable() {
return this.service.paginationConfig(this.operation) ? true : false;
},
createReadStream: function createReadStream() {
var streams = AWS.util.nodeRequire('stream');
var req = this;
var stream = null;
if (AWS.HttpClient.streamsApiVersion === 2) {
stream = new streams.PassThrough();
req.send();
} else {
stream = new streams.Stream();
stream.readable = true;
stream.sent = false;
stream.on('newListener', function(event) {
if (!stream.sent && event === 'data') {
stream.sent = true;
process.nextTick(function() { req.send(); });
}
});
}
this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
if (statusCode < 300) {
req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
req.on('httpError', function streamHttpError(error) {
resp.error = error;
resp.error.retryable = false;
});
var httpStream = resp.httpResponse.createUnbufferedStream();
if (AWS.HttpClient.streamsApiVersion === 2) {
httpStream.pipe(stream);
} else {
httpStream.on('data', function(arg) {
stream.emit('data', arg);
});
httpStream.on('end', function() {
stream.emit('end');
});
}
httpStream.on('error', function(err) {
stream.emit('error', err);
});
}
});
this.on('error', function(err) {
stream.emit('error', err);
});
return stream;
},
emitEvent: function emit(eventName, args, done) {
if (typeof args === 'function') { done = args; args = null; }
if (!done) done = function() { };
if (!args) args = this.eventParameters(eventName, this.response);
var origEmit = AWS.SequentialExecutor.prototype.emit;
origEmit.call(this, eventName, args, function (err) {
if (err) this.response.error = err;
done.call(this, err);
});
},
eventParameters: function eventParameters(eventName) {
switch (eventName) {
case 'restart':
case 'validate':
case 'sign':
case 'build':
case 'afterValidate':
case 'afterBuild':
return [this];
case 'error':
return [this.response.error, this.response];
default:
return [this.response];
}
},
presign: function presign(expires, callback) {
if (!callback && typeof expires === 'function') {
callback = expires;
expires = null;
}
return new AWS.Signers.Presign().sign(this.toGet(), expires, callback);
},
toUnauthenticated: function toUnauthenticated() {
this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS);
this.removeListener('sign', AWS.EventListeners.Core.SIGN);
return this;
},
toGet: function toGet() {
if (this.service.api.protocol === 'query' ||
this.service.api.protocol === 'ec2') {
this.removeListener('build', this.buildAsGet);
this.addListener('build', this.buildAsGet);
}
return this;
},
buildAsGet: function buildAsGet(request) {
request.httpRequest.method = 'GET';
request.httpRequest.path = request.service.endpoint.path +
'?' + request.httpRequest.body;
request.httpRequest.body = '';
delete request.httpRequest.headers['Content-Length'];
delete request.httpRequest.headers['Content-Type'];
},
haltHandlersOnError: function haltHandlersOnError() {
this._haltHandlersOnError = true;
}
});
AWS.util.mixin(AWS.Request, AWS.SequentialExecutor);
}).call(this,require("FWaASH"))
},{"./core":3,"./state_machine":43,"FWaASH":58}],31:[function(require,module,exports){
var AWS = require('./core');
var inherit = AWS.util.inherit;
AWS.ResourceWaiter = inherit({
constructor: function constructor(service, state) {
this.service = service;
this.state = state;
if (typeof this.state === 'object') {
AWS.util.each.call(this, this.state, function (key, value) {
this.state = key;
this.expectedValue = value;
});
}
this.loadWaiterConfig(this.state);
if (!this.expectedValue) {
this.expectedValue = this.config.successValue;
}
},
service: null,
state: null,
expectedValue: null,
config: null,
waitDone: false,
Listeners: {
retry: new AWS.SequentialExecutor().addNamedListeners(function(add) {
add('RETRY_CHECK', 'retry', function(resp) {
var waiter = resp.request._waiter;
if (resp.error && resp.error.code === 'ResourceNotReady') {
resp.error.retryDelay = waiter.config.interval * 1000;
}
});
}),
output: new AWS.SequentialExecutor().addNamedListeners(function(add) {
add('CHECK_OUT_ERROR', 'extractError', function CHECK_OUT_ERROR(resp) {
if (resp.error) {
resp.request._waiter.setError(resp, true);
}
});
add('CHECK_OUTPUT', 'extractData', function CHECK_OUTPUT(resp) {
var waiter = resp.request._waiter;
var success = waiter.checkSuccess(resp);
if (!success) {
waiter.setError(resp, success === null ? false : true);
} else {
resp.error = null;
}
});
}),
error: new AWS.SequentialExecutor().addNamedListeners(function(add) {
add('CHECK_ERROR', 'extractError', function CHECK_ERROR(resp) {
var waiter = resp.request._waiter;
var success = waiter.checkError(resp);
if (!success) {
waiter.setError(resp, success === null ? false : true);
} else {
resp.error = null;
resp.data = {};
resp.request.removeAllListeners('extractData');
}
});
add('CHECK_ERR_OUTPUT', 'extractData', function CHECK_ERR_OUTPUT(resp) {
resp.request._waiter.setError(resp, true);
});
})
},
wait: function wait(params, callback) {
if (typeof params === 'function') {
callback = params; params = undefined;
}
var request = this.service.makeRequest(this.config.operation, params);
var listeners = this.Listeners[this.config.successType];
request._waiter = this;
request.response.maxRetries = this.config.maxAttempts;
request.addListeners(this.Listeners.retry);
if (listeners) request.addListeners(listeners);
if (callback) request.send(callback);
return request;
},
setError: function setError(resp, retryable) {
resp.data = null;
resp.error = AWS.util.error(resp.error || new Error(), {
code: 'ResourceNotReady',
message: 'Resource is not in the state ' + this.state,
retryable: retryable
});
},
checkSuccess: function checkSuccess(resp) {
if (!this.config.successPath) {
return resp.httpResponse.statusCode < 300;
}
var r = AWS.util.jamespath.find(this.config.successPath, resp.data);
if (this.config.failureValue &&
this.config.failureValue.indexOf(r) >= 0) {
return null; // fast fail
}
if (this.expectedValue) {
return r === this.expectedValue;
} else {
return r ? true : false;
}
},
checkError: function checkError(resp) {
var value = this.config.successValue;
if (typeof value === 'number') {
return resp.httpResponse.statusCode === value;
} else {
return resp.error && resp.error.code === value;
}
},
loadWaiterConfig: function loadWaiterConfig(state, noException) {
if (!this.service.api.waiters[state]) {
if (noException) return;
throw new AWS.util.error(new Error(), {
code: 'StateNotFoundError',
message: 'State ' + state + ' not found.'
});
}
this.config = this.service.api.waiters[state];
var config = this.config;
(function () { // anonymous function to avoid max complexity count
config.successType = config.successType || config.acceptorType;
config.successPath = config.successPath || config.acceptorPath;
config.successValue = config.successValue || config.acceptorValue;
config.failureType = config.failureType || config.acceptorType;
config.failurePath = config.failurePath || config.acceptorPath;
config.failureValue = config.failureValue || config.acceptorValue;
})();
}
});
},{"./core":3}],32:[function(require,module,exports){
var AWS = require('./core');
var inherit = AWS.util.inherit;
AWS.Response = inherit({
constructor: function Response(request) {
this.request = request;
this.data = null;
this.error = null;
this.retryCount = 0;
this.redirectCount = 0;
this.httpResponse = new AWS.HttpResponse();
if (request) {
this.maxRetries = request.service.numRetries();
this.maxRedirects = request.service.config.maxRedirects;
}
},
nextPage: function nextPage(callback) {
var config;
var service = this.request.service;
var operation = this.request.operation;
try {
config = service.paginationConfig(operation, true);
} catch (e) { this.error = e; }
if (!this.hasNextPage()) {
if (callback) callback(this.error, null);
else if (this.error) throw this.error;
return null;
}
var params = AWS.util.copy(this.request.params);
if (!this.nextPageTokens) {
return callback ? callback(null, null) : null;
} else {
var inputTokens = config.inputToken;
if (typeof inputTokens === 'string') inputTokens = [inputTokens];
for (var i = 0; i < inputTokens.length; i++) {
params[inputTokens[i]] = this.nextPageTokens[i];
}
return service.makeRequest(this.request.operation, params, callback);
}
},
hasNextPage: function hasNextPage() {
this.cacheNextPageTokens();
if (this.nextPageTokens) return true;
if (this.nextPageTokens === undefined) return undefined;
else return false;
},
cacheNextPageTokens: function cacheNextPageTokens() {
if (this.hasOwnProperty('nextPageTokens')) return this.nextPageTokens;
this.nextPageTokens = undefined;
var config = this.request.service.paginationConfig(this.request.operation);
if (!config) return this.nextPageTokens;
this.nextPageTokens = null;
if (config.moreResults) {
if (!AWS.util.jamespath.find(config.moreResults, this.data)) {
return this.nextPageTokens;
}
}
var exprs = config.outputToken;
if (typeof exprs === 'string') exprs = [exprs];
AWS.util.arrayEach.call(this, exprs, function (expr) {
var output = AWS.util.jamespath.find(expr, this.data);
if (output) {
this.nextPageTokens = this.nextPageTokens || [];
this.nextPageTokens.push(output);
}
});
return this.nextPageTokens;
}
});
},{"./core":3}],33:[function(require,module,exports){
var AWS = require('./core');
AWS.SequentialExecutor = AWS.util.inherit({
constructor: function SequentialExecutor() {
this._events = {};
},
listeners: function listeners(eventName) {
return this._events[eventName] ? this._events[eventName].slice(0) : [];
},
on: function on(eventName, listener) {
if (this._events[eventName]) {
this._events[eventName].push(listener);
} else {
this._events[eventName] = [listener];
}
return this;
},
onAsync: function onAsync(eventName, listener) {
listener._isAsync = true;
return this.on(eventName, listener);
},
removeListener: function removeListener(eventName, listener) {
var listeners = this._events[eventName];
if (listeners) {
var length = listeners.length;
var position = -1;
for (var i = 0; i < length; ++i) {
if (listeners[i] === listener) {
position = i;
}
}
if (position > -1) {
listeners.splice(position, 1);
}
}
return this;
},
removeAllListeners: function removeAllListeners(eventName) {
if (eventName) {
delete this._events[eventName];
} else {
this._events = {};
}
return this;
},
emit: function emit(eventName, eventArgs, doneCallback) {
if (!doneCallback) doneCallback = function() { };
var listeners = this.listeners(eventName);
var count = listeners.length;
this.callListeners(listeners, eventArgs, doneCallback);
return count > 0;
},
callListeners: function callListeners(listeners, args, doneCallback, prevError) {
var self = this;
var error = prevError || null;
function callNextListener(err) {
if (err) {
error = AWS.util.error(error || new Error(), err);
if (self._haltHandlersOnError) {
return doneCallback.call(self, error);
}
}
self.callListeners(listeners, args, doneCallback, error);
}
while (listeners.length > 0) {
var listener = listeners.shift();
if (listener._isAsync) { // asynchronous listener
listener.apply(self, args.concat([callNextListener]));
return; // stop here, callNextListener will continue
} else { // synchronous listener
try {
listener.apply(self, args);
} catch (err) {
error = AWS.util.error(error || new Error(), err);
}
if (error && self._haltHandlersOnError) {
doneCallback.call(self, error);
return;
}
}
}
doneCallback.call(self, error);
},
addListeners: function addListeners(listeners) {
var self = this;
if (listeners._events) listeners = listeners._events;
AWS.util.each(listeners, function(event, callbacks) {
if (typeof callbacks === 'function') callbacks = [callbacks];
AWS.util.arrayEach(callbacks, function(callback) {
self.on(event, callback);
});
});
return self;
},
addNamedListener: function addNamedListener(name, eventName, callback) {
this[name] = callback;
this.addListener(eventName, callback);
return this;
},
addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback) {
callback._isAsync = true;
return this.addNamedListener(name, eventName, callback);
},
addNamedListeners: function addNamedListeners(callback) {
var self = this;
callback(
function() {
self.addNamedListener.apply(self, arguments);
},
function() {
self.addNamedAsyncListener.apply(self, arguments);
}
);
return this;
}
});
AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;
module.exports = AWS.SequentialExecutor;
},{"./core":3}],34:[function(require,module,exports){
var AWS = require('./core');
var Api = require('./model/api');
var regionConfig = require('./region_config');
var inherit = AWS.util.inherit;
AWS.Service = inherit({
constructor: function Service(config) {
if (!this.loadServiceClass) {
throw AWS.util.error(new Error(),
'Service must be constructed with `new\' operator');
}
var ServiceClass = this.loadServiceClass(config || {});
if (ServiceClass) return new ServiceClass(config);
this.initialize(config);
},
initialize: function initialize(config) {
var svcConfig = AWS.config[this.serviceIdentifier];
this.config = new AWS.Config(AWS.config);
if (svcConfig) this.config.update(svcConfig, true);
if (config) this.config.update(config, true);
this.validateService();
if (!this.config.endpoint) regionConfig(this);
this.config.endpoint = this.endpointFromTemplate(this.config.endpoint);
this.setEndpoint(this.config.endpoint);
},
validateService: function validateService() {
},
loadServiceClass: function loadServiceClass(serviceConfig) {
var config = serviceConfig;
if (!AWS.util.isEmpty(this.api)) {
return null;
} else if (config.apiConfig) {
return AWS.Service.defineServiceApi(this.constructor, config.apiConfig);
} else if (!this.constructor.services) {
return null;
} else {
config = new AWS.Config(AWS.config);
config.update(serviceConfig, true);
var version = config.apiVersions[this.constructor.serviceIdentifier];
version = version || config.apiVersion;
return this.getLatestServiceClass(version);
}
},
getLatestServiceClass: function getLatestServiceClass(version) {
version = this.getLatestServiceVersion(version);
if (this.constructor.services[version] === null) {
AWS.Service.defineServiceApi(this.constructor, version);
}
return this.constructor.services[version];
},
getLatestServiceVersion: function getLatestServiceVersion(version) {
if (!this.constructor.services || this.constructor.services.length === 0) {
throw new Error('No services defined on ' +
this.constructor.serviceIdentifier);
}
if (!version) {
version = 'latest';
} else if (AWS.util.isType(version, Date)) {
version = AWS.util.date.iso8601(version).split('T')[0];
}
if (Object.hasOwnProperty(this.constructor.services, version)) {
return version;
}
var keys = Object.keys(this.constructor.services).sort();
var selectedVersion = null;
for (var i = keys.length - 1; i >= 0; i--) {
if (keys[i][keys[i].length - 1] !== '*') {
selectedVersion = keys[i];
}
if (keys[i].substr(0, 10) <= version) {
return selectedVersion;
}
}
throw new Error('Could not find ' + this.constructor.serviceIdentifier +
' API to satisfy version constraint `' + version + '\'');
},
api: {},
defaultRetryCount: 3,
makeRequest: function makeRequest(operation, params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
params = params || {};
if (this.config.params) { // copy only toplevel bound params
var rules = this.api.operations[operation];
if (rules) {
params = AWS.util.copy(params);
AWS.util.each(this.config.params, function(key, value) {
if (rules.input.members[key]) {
if (params[key] === undefined || params[key] === null) {
params[key] = value;
}
}
});
}
}
var request = new AWS.Request(this, operation, params);
this.addAllRequestListeners(request);
if (callback) request.send(callback);
return request;
},
makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) {
if (typeof params === 'function') {
callback = params;
params = {};
}
var request = this.makeRequest(operation, params).toUnauthenticated();
return callback ? request.send(callback) : request;
},
waitFor: function waitFor(state, params, callback) {
var waiter = new AWS.ResourceWaiter(this, state);
return waiter.wait(params, callback);
},
addAllRequestListeners: function addAllRequestListeners(request) {
var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(),
AWS.EventListeners.CorePost];
for (var i = 0; i < list.length; i++) {
if (list[i]) request.addListeners(list[i]);
}
if (!this.config.paramValidation) {
request.removeListener('validate',
AWS.EventListeners.Core.VALIDATE_PARAMETERS);
}
if (this.config.logger) { // add logging events
request.addListeners(AWS.EventListeners.Logger);
}
this.setupRequestListeners(request);
},
setupRequestListeners: function setupRequestListeners() {
},
getSignerClass: function getSignerClass() {
var version;
if (this.config.signatureVersion) {
version = this.config.signatureVersion;
} else {
version = this.api.signatureVersion;
}
return AWS.Signers.RequestSigner.getVersion(version);
},
serviceInterface: function serviceInterface() {
switch (this.api.protocol) {
case 'ec2': return AWS.EventListeners.Query;
case 'query': return AWS.EventListeners.Query;
case 'json': return AWS.EventListeners.Json;
case 'rest-json': return AWS.EventListeners.RestJson;
case 'rest-xml': return AWS.EventListeners.RestXml;
}
if (this.api.protocol) {
throw new Error('Invalid service `protocol\' ' +
this.api.protocol + ' in API config');
}
},
successfulResponse: function successfulResponse(resp) {
return resp.httpResponse.statusCode < 300;
},
numRetries: function numRetries() {
if (this.config.maxRetries !== undefined) {
return this.config.maxRetries;
} else {
return this.defaultRetryCount;
}
},
retryDelays: function retryDelays(retryCount) {
var retryDelayOptions = this.config.retryDelayOptions || {};
var customBackoff = retryDelayOptions.customBackoff || null;
if (typeof customBackoff === 'function') {
return customBackoff(retryCount);
}
var base = retryDelayOptions.base || 30;
var delay = Math.random() * (Math.pow(2, retryCount) * base);
return delay;
},
retryableError: function retryableError(error) {
if (this.networkingError(error)) return true;
if (this.expiredCredentialsError(error)) return true;
if (this.throttledError(error)) return true;
if (error.statusCode >= 500) return true;
return false;
},
networkingError: function networkingError(error) {
return error.code === 'NetworkingError';
},
expiredCredentialsError: function expiredCredentialsError(error) {
return (error.code === 'ExpiredTokenException');
},
clockSkewError: function clockSkewError(error) {
switch (error.code) {
case 'RequestTimeTooSkewed':
case 'RequestExpired':
case 'InvalidSignatureException':
case 'SignatureDoesNotMatch':
case 'AuthFailure':
case 'RequestInTheFuture':
return true;
default: return false;
}
},
throttledError: function throttledError(error) {
switch (error.code) {
case 'ProvisionedThroughputExceededException':
case 'Throttling':
case 'ThrottlingException':
case 'RequestLimitExceeded':
case 'RequestThrottled':
return true;
default:
return false;
}
},
endpointFromTemplate: function endpointFromTemplate(endpoint) {
if (typeof endpoint !== 'string') return endpoint;
var e = endpoint;
e = e.replace(/\{service\}/g, this.api.endpointPrefix);
e = e.replace(/\{region\}/g, this.config.region);
e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http');
return e;
},
setEndpoint: function setEndpoint(endpoint) {
this.endpoint = new AWS.Endpoint(endpoint, this.config);
},
paginationConfig: function paginationConfig(operation, throwException) {
var paginator = this.api.operations[operation].paginator;
if (!paginator) {
if (throwException) {
var e = new Error();
throw AWS.util.error(e, 'No pagination configuration for ' + operation);
}
return null;
}
return paginator;
}
});
AWS.util.update(AWS.Service, {
defineMethods: function defineMethods(svc) {
AWS.util.each(svc.prototype.api.operations, function iterator(method) {
if (svc.prototype[method]) return;
svc.prototype[method] = function (params, callback) {
return this.makeRequest(method, params, callback);
};
});
},
defineService: function defineService(serviceIdentifier, versions, features) {
AWS.Service._serviceMap[serviceIdentifier] = true;
if (!Array.isArray(versions)) {
features = versions;
versions = [];
}
var svc = inherit(AWS.Service, features || {});
if (typeof serviceIdentifier === 'string') {
AWS.Service.addVersions(svc, versions);
var identifier = svc.serviceIdentifier || serviceIdentifier;
svc.serviceIdentifier = identifier;
} else { // defineService called with an API
svc.prototype.api = serviceIdentifier;
AWS.Service.defineMethods(svc);
}
return svc;
},
addVersions: function addVersions(svc, versions) {
if (!Array.isArray(versions)) versions = [versions];
svc.services = svc.services || {};
for (var i = 0; i < versions.length; i++) {
if (svc.services[versions[i]] === undefined) {
svc.services[versions[i]] = null;
}
}
svc.apiVersions = Object.keys(svc.services).sort();
},
defineServiceApi: function defineServiceApi(superclass, version, apiConfig) {
var svc = inherit(superclass, {
serviceIdentifier: superclass.serviceIdentifier
});
function setApi(api) {
if (api.isApi) {
svc.prototype.api = api;
} else {
svc.prototype.api = new Api(api);
}
}
if (typeof version === 'string') {
if (apiConfig) {
setApi(apiConfig);
} else {
try {
setApi(AWS.apiLoader(superclass.serviceIdentifier, version));
} catch (err) {
throw AWS.util.error(err, {
message: 'Could not find API configuration ' +
superclass.serviceIdentifier + '-' + version
});
}
}
if (!superclass.services.hasOwnProperty(version)) {
superclass.apiVersions = superclass.apiVersions.concat(version).sort();
}
superclass.services[version] = svc;
} else {
setApi(version);
}
AWS.Service.defineMethods(svc);
return svc;
},
hasService: function(identifier) {
return AWS.Service._serviceMap.hasOwnProperty(identifier);
},
_serviceMap: {}
});
},{"./core":3,"./model/api":15,"./region_config":28}],35:[function(require,module,exports){
var AWS = require('../core');
AWS.util.update(AWS.STS.prototype, {
credentialsFrom: function credentialsFrom(data, credentials) {
if (!data) return null;
if (!credentials) credentials = new AWS.TemporaryCredentials();
credentials.expired = false;
credentials.accessKeyId = data.Credentials.AccessKeyId;
credentials.secretAccessKey = data.Credentials.SecretAccessKey;
credentials.sessionToken = data.Credentials.SessionToken;
credentials.expireTime = data.Credentials.Expiration;
return credentials;
},
assumeRoleWithWebIdentity: function assumeRoleWithWebIdentity(params, callback) {
return this.makeUnauthenticatedRequest('assumeRoleWithWebIdentity', params, callback);
},
assumeRoleWithSAML: function assumeRoleWithSAML(params, callback) {
return this.makeUnauthenticatedRequest('assumeRoleWithSAML', params, callback);
}
});
},{"../core":3}],36:[function(require,module,exports){
var AWS = require('../core');
var inherit = AWS.util.inherit;
var expiresHeader = 'presigned-expires';
function signedUrlBuilder(request) {
var expires = request.httpRequest.headers[expiresHeader];
delete request.httpRequest.headers['User-Agent'];
delete request.httpRequest.headers['X-Amz-User-Agent'];
if (request.service.getSignerClass() === AWS.Signers.V4) {
if (expires > 604800) { // one week expiry is invalid
var message = 'Presigning does not support expiry time greater ' +
'than a week with SigV4 signing.';
throw AWS.util.error(new Error(), {
code: 'InvalidExpiryTime', message: message, retryable: false
});
}
request.httpRequest.headers[expiresHeader] = expires;
} else if (request.service.getSignerClass() === AWS.Signers.S3) {
request.httpRequest.headers[expiresHeader] = parseInt(
AWS.util.date.unixTimestamp() + expires, 10).toString();
} else {
throw AWS.util.error(new Error(), {
message: 'Presigning only supports S3 or SigV4 signing.',
code: 'UnsupportedSigner', retryable: false
});
}
}
function signedUrlSigner(request) {
var endpoint = request.httpRequest.endpoint;
var parsedUrl = AWS.util.urlParse(request.httpRequest.path);
var queryParams = {};
if (parsedUrl.search) {
queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1));
}
AWS.util.each(request.httpRequest.headers, function (key, value) {
if (key === expiresHeader) key = 'Expires';
if (key.indexOf('x-amz-meta-') === 0) {
key = key.toLowerCase();
}
queryParams[key] = value;
});
delete request.httpRequest.headers[expiresHeader];
var auth = queryParams['Authorization'].split(' ');
if (auth[0] === 'AWS') {
auth = auth[1].split(':');
queryParams['AWSAccessKeyId'] = auth[0];
queryParams['Signature'] = auth[1];
} else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing
auth.shift();
var rest = auth.join(' ');
var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];
queryParams['X-Amz-Signature'] = signature;
delete queryParams['Expires'];
}
delete queryParams['Authorization'];
delete queryParams['Host'];
endpoint.pathname = parsedUrl.pathname;
endpoint.search = AWS.util.queryParamsToString(queryParams);
}
AWS.Signers.Presign = inherit({
sign: function sign(request, expireTime, callback) {
request.httpRequest.headers[expiresHeader] = expireTime || 3600;
request.on('build', signedUrlBuilder);
request.on('sign', signedUrlSigner);
request.removeListener('afterBuild',
AWS.EventListeners.Core.SET_CONTENT_LENGTH);
request.removeListener('afterBuild',
AWS.EventListeners.Core.COMPUTE_SHA256);
request.emit('beforePresign', [request]);
if (callback) {
request.build(function() {
if (this.response.error) callback(this.response.error);
else {
callback(null, AWS.util.urlFormat(request.httpRequest.endpoint));
}
});
} else {
request.build();
if (request.response.error) throw request.response.error;
return AWS.util.urlFormat(request.httpRequest.endpoint);
}
}
});
module.exports = AWS.Signers.Presign;
},{"../core":3}],37:[function(require,module,exports){
var AWS = require('../core');
var inherit = AWS.util.inherit;
AWS.Signers.RequestSigner = inherit({
constructor: function RequestSigner(request) {
this.request = request;
}
});
AWS.Signers.RequestSigner.getVersion = function getVersion(version) {
switch (version) {
case 'v2': return AWS.Signers.V2;
case 'v3': return AWS.Signers.V3;
case 'v4': return AWS.Signers.V4;
case 's3': return AWS.Signers.S3;
case 'v3https': return AWS.Signers.V3Https;
}
throw new Error('Unknown signing version ' + version);
};
require('./v2');
require('./v3');
require('./v3https');
require('./v4');
require('./s3');
require('./presign');
},{"../core":3,"./presign":36,"./s3":38,"./v2":39,"./v3":40,"./v3https":41,"./v4":42}],38:[function(require,module,exports){
var AWS = require('../core');
var inherit = AWS.util.inherit;
AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {
subResources: {
'acl': 1,
'cors': 1,
'lifecycle': 1,
'delete': 1,
'location': 1,
'logging': 1,
'notification': 1,
'partNumber': 1,
'policy': 1,
'requestPayment': 1,
'restore': 1,
'tagging': 1,
'torrent': 1,
'uploadId': 1,
'uploads': 1,
'versionId': 1,
'versioning': 1,
'versions': 1,
'website': 1
},
responseHeaders: {
'response-content-type': 1,
'response-content-language': 1,
'response-expires': 1,
'response-cache-control': 1,
'response-content-disposition': 1,
'response-content-encoding': 1
},
addAuthorization: function addAuthorization(credentials, date) {
if (!this.request.headers['presigned-expires']) {
this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date);
}
if (credentials.sessionToken) {
this.request.headers['x-amz-security-token'] = credentials.sessionToken;
}
var signature = this.sign(credentials.secretAccessKey, this.stringToSign());
var auth = 'AWS ' + credentials.accessKeyId + ':' + signature;
this.request.headers['Authorization'] = auth;
},
stringToSign: function stringToSign() {
var r = this.request;
var parts = [];
parts.push(r.method);
parts.push(r.headers['Content-MD5'] || '');
parts.push(r.headers['Content-Type'] || '');
parts.push(r.headers['presigned-expires'] || '');
var headers = this.canonicalizedAmzHeaders();
if (headers) parts.push(headers);
parts.push(this.canonicalizedResource());
return parts.join('\n');
},
canonicalizedAmzHeaders: function canonicalizedAmzHeaders() {
var amzHeaders = [];
AWS.util.each(this.request.headers, function (name) {
if (name.match(/^x-amz-/i))
amzHeaders.push(name);
});
amzHeaders.sort(function (a, b) {
return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
});
var parts = [];
AWS.util.arrayEach.call(this, amzHeaders, function (name) {
parts.push(name.toLowerCase() + ':' + String(this.request.headers[name]));
});
return parts.join('\n');
},
canonicalizedResource: function canonicalizedResource() {
var r = this.request;
var parts = r.path.split('?');
var path = parts[0];
var querystring = parts[1];
var resource = '';
if (r.virtualHostedBucket)
resource += '/' + r.virtualHostedBucket;
resource += path;
if (querystring) {
var resources = [];
AWS.util.arrayEach.call(this, querystring.split('&'), function (param) {
var name = param.split('=')[0];
var value = param.split('=')[1];
if (this.subResources[name] || this.responseHeaders[name]) {
var subresource = { name: name };
if (value !== undefined) {
if (this.subResources[name]) {
subresource.value = value;
} else {
subresource.value = decodeURIComponent(value);
}
}
resources.push(subresource);
}
});
resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
if (resources.length) {
querystring = [];
AWS.util.arrayEach(resources, function (res) {
if (res.value === undefined) {
querystring.push(res.name);
} else {
querystring.push(res.name + '=' + res.value);
}
});
resource += '?' + querystring.join('&');
}
}
return resource;
},
sign: function sign(secret, string) {
return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1');
}
});
module.exports = AWS.Signers.S3;
},{"../core":3}],39:[function(require,module,exports){
var AWS = require('../core');
var inherit = AWS.util.inherit;
AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, {
addAuthorization: function addAuthorization(credentials, date) {
if (!date) date = AWS.util.date.getDate();
var r = this.request;
r.params.Timestamp = AWS.util.date.iso8601(date);
r.params.SignatureVersion = '2';
r.params.SignatureMethod = 'HmacSHA256';
r.params.AWSAccessKeyId = credentials.accessKeyId;
if (credentials.sessionToken) {
r.params.SecurityToken = credentials.sessionToken;
}
delete r.params.Signature; // delete old Signature for re-signing
r.params.Signature = this.signature(credentials);
r.body = AWS.util.queryParamsToString(r.params);
r.headers['Content-Length'] = r.body.length;
},
signature: function signature(credentials) {
return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
},
stringToSign: function stringToSign() {
var parts = [];
parts.push(this.request.method);
parts.push(this.request.endpoint.host.toLowerCase());
parts.push(this.request.pathname());
parts.push(AWS.util.queryParamsToString(this.request.params));
return parts.join('\n');
}
});
module.exports = AWS.Signers.V2;
},{"../core":3}],40:[function(require,module,exports){
var AWS = require('../core');
var inherit = AWS.util.inherit;
AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, {
addAuthorization: function addAuthorization(credentials, date) {
var datetime = AWS.util.date.rfc822(date);
this.request.headers['X-Amz-Date'] = datetime;
if (credentials.sessionToken) {
this.request.headers['x-amz-security-token'] = credentials.sessionToken;
}
this.request.headers['X-Amzn-Authorization'] =
this.authorization(credentials, datetime);
},
authorization: function authorization(credentials) {
return 'AWS3 ' +
'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
'Algorithm=HmacSHA256,' +
'SignedHeaders=' + this.signedHeaders() + ',' +
'Signature=' + this.signature(credentials);
},
signedHeaders: function signedHeaders() {
var headers = [];
AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
headers.push(h.toLowerCase());
});
return headers.sort().join(';');
},
canonicalHeaders: function canonicalHeaders() {
var headers = this.request.headers;
var parts = [];
AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim());
});
return parts.sort().join('\n') + '\n';
},
headersToSign: function headersToSign() {
var headers = [];
AWS.util.each(this.request.headers, function iterator(k) {
if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) {
headers.push(k);
}
});
return headers;
},
signature: function signature(credentials) {
return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
},
stringToSign: function stringToSign() {
var parts = [];
parts.push(this.request.method);
parts.push('/');
parts.push('');
parts.push(this.canonicalHeaders());
parts.push(this.request.body);
return AWS.util.crypto.sha256(parts.join('\n'));
}
});
module.exports = AWS.Signers.V3;
},{"../core":3}],41:[function(require,module,exports){
var AWS = require('../core');
var inherit = AWS.util.inherit;
require('./v3');
AWS.Signers.V3Https = inherit(AWS.Signers.V3, {
authorization: function authorization(credentials) {
return 'AWS3-HTTPS ' +
'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
'Algorithm=HmacSHA256,' +
'Signature=' + this.signature(credentials);
},
stringToSign: function stringToSign() {
return this.request.headers['X-Amz-Date'];
}
});
module.exports = AWS.Signers.V3Https;
},{"../core":3,"./v3":40}],42:[function(require,module,exports){
var AWS = require('../core');
var inherit = AWS.util.inherit;
var cachedSecret = {};
var expiresHeader = 'presigned-expires';
AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, {
constructor: function V4(request, serviceName, signatureCache) {
AWS.Signers.RequestSigner.call(this, request);
this.serviceName = serviceName;
this.signatureCache = signatureCache;
},
algorithm: 'AWS4-HMAC-SHA256',
addAuthorization: function addAuthorization(credentials, date) {
var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '');
if (this.isPresigned()) {
this.updateForPresigned(credentials, datetime);
} else {
this.addHeaders(credentials, datetime);
}
this.request.headers['Authorization'] =
this.authorization(credentials, datetime);
},
addHeaders: function addHeaders(credentials, datetime) {
this.request.headers['X-Amz-Date'] = datetime;
if (credentials.sessionToken) {
this.request.headers['x-amz-security-token'] = credentials.sessionToken;
}
},
updateForPresigned: function updateForPresigned(credentials, datetime) {
var credString = this.credentialString(datetime);
var qs = {
'X-Amz-Date': datetime,
'X-Amz-Algorithm': this.algorithm,
'X-Amz-Credential': credentials.accessKeyId + '/' + credString,
'X-Amz-Expires': this.request.headers[expiresHeader],
'X-Amz-SignedHeaders': this.signedHeaders()
};
if (credentials.sessionToken) {
qs['X-Amz-Security-Token'] = credentials.sessionToken;
}
if (this.request.headers['Content-Type']) {
qs['Content-Type'] = this.request.headers['Content-Type'];
}
if (this.request.headers['Content-MD5']) {
qs['Content-MD5'] = this.request.headers['Content-MD5'];
}
if (this.request.headers['Cache-Control']) {
qs['Cache-Control'] = this.request.headers['Cache-Control'];
}
AWS.util.each.call(this, this.request.headers, function(key, value) {
if (key === expiresHeader) return;
if (this.isSignableHeader(key) &&
key.toLowerCase().indexOf('x-amz-') === 0) {
qs[key] = value;
}
});
var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?';
this.request.path += sep + AWS.util.queryParamsToString(qs);
},
authorization: function authorization(credentials, datetime) {
var parts = [];
var credString = this.credentialString(datetime);
parts.push(this.algorithm + ' Credential=' +
credentials.accessKeyId + '/' + credString);
parts.push('SignedHeaders=' + this.signedHeaders());
parts.push('Signature=' + this.signature(credentials, datetime));
return parts.join(', ');
},
signature: function signature(credentials, datetime) {
var cache = null;
if (this.signatureCache) {
var cache = cachedSecret[this.serviceName];
}
var date = datetime.substr(0, 8);
if (!cache ||
cache.akid !== credentials.accessKeyId ||
cache.region !== this.request.region ||
cache.date !== date) {
var kSecret = credentials.secretAccessKey;
var kDate = AWS.util.crypto.hmac('AWS4' + kSecret, date, 'buffer');
var kRegion = AWS.util.crypto.hmac(kDate, this.request.region, 'buffer');
var kService = AWS.util.crypto.hmac(kRegion, this.serviceName, 'buffer');
var kCredentials = AWS.util.crypto.hmac(kService, 'aws4_request', 'buffer');
if (!this.signatureCache) {
return AWS.util.crypto.hmac(kCredentials, this.stringToSign(datetime), 'hex');
}
cachedSecret[this.serviceName] = {
region: this.request.region, date: date,
key: kCredentials, akid: credentials.accessKeyId
};
}
var key = cachedSecret[this.serviceName].key;
return AWS.util.crypto.hmac(key, this.stringToSign(datetime), 'hex');
},
stringToSign: function stringToSign(datetime) {
var parts = [];
parts.push('AWS4-HMAC-SHA256');
parts.push(datetime);
parts.push(this.credentialString(datetime));
parts.push(this.hexEncodedHash(this.canonicalString()));
return parts.join('\n');
},
canonicalString: function canonicalString() {
var parts = [], pathname = this.request.pathname();
if (this.serviceName !== 's3') pathname = AWS.util.uriEscapePath(pathname);
parts.push(this.request.method);
parts.push(pathname);
parts.push(this.request.search());
parts.push(this.canonicalHeaders() + '\n');
parts.push(this.signedHeaders());
parts.push(this.hexEncodedBodyHash());
return parts.join('\n');
},
canonicalHeaders: function canonicalHeaders() {
var headers = [];
AWS.util.each.call(this, this.request.headers, function (key, item) {
headers.push([key, item]);
});
headers.sort(function (a, b) {
return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
});
var parts = [];
AWS.util.arrayEach.call(this, headers, function (item) {
var key = item[0].toLowerCase();
if (this.isSignableHeader(key)) {
parts.push(key + ':' +
this.canonicalHeaderValues(item[1].toString()));
}
});
return parts.join('\n');
},
canonicalHeaderValues: function canonicalHeaderValues(values) {
return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
},
signedHeaders: function signedHeaders() {
var keys = [];
AWS.util.each.call(this, this.request.headers, function (key) {
key = key.toLowerCase();
if (this.isSignableHeader(key)) keys.push(key);
});
return keys.sort().join(';');
},
credentialString: function credentialString(datetime) {
var parts = [];
parts.push(datetime.substr(0, 8));
parts.push(this.request.region);
parts.push(this.serviceName);
parts.push('aws4_request');
return parts.join('/');
},
hexEncodedHash: function hash(string) {
return AWS.util.crypto.sha256(string, 'hex');
},
hexEncodedBodyHash: function hexEncodedBodyHash() {
if (this.isPresigned() && this.serviceName === 's3') {
return 'UNSIGNED-PAYLOAD';
} else if (this.request.headers['X-Amz-Content-Sha256']) {
return this.request.headers['X-Amz-Content-Sha256'];
} else {
return this.hexEncodedHash(this.request.body || '');
}
},
unsignableHeaders: ['authorization', 'content-type', 'content-length',
'user-agent', expiresHeader],
isSignableHeader: function isSignableHeader(key) {
if (key.toLowerCase().indexOf('x-amz-') === 0) return true;
return this.unsignableHeaders.indexOf(key) < 0;
},
isPresigned: function isPresigned() {
return this.request.headers[expiresHeader] ? true : false;
}
});
module.exports = AWS.Signers.V4;
},{"../core":3}],43:[function(require,module,exports){
function AcceptorStateMachine(states, state) {
this.currentState = state || null;
this.states = states || {};
}
AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) {
if (typeof finalState === 'function') {
inputError = bindObject; bindObject = done;
done = finalState; finalState = null;
}
var self = this;
var state = self.states[self.currentState];
state.fn.call(bindObject || self, inputError, function(err) {
if (err) {
if (state.fail) self.currentState = state.fail;
else return done ? done.call(bindObject, err) : null;
} else {
if (state.accept) self.currentState = state.accept;
else return done ? done.call(bindObject) : null;
}
if (self.currentState === finalState) {
return done ? done.call(bindObject, err) : null;
}
self.runTo(finalState, done, bindObject, err);
});
};
AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) {
if (typeof acceptState === 'function') {
fn = acceptState; acceptState = null; failState = null;
} else if (typeof failState === 'function') {
fn = failState; failState = null;
}
if (!this.currentState) this.currentState = name;
this.states[name] = { accept: acceptState, fail: failState, fn: fn };
return this;
};
module.exports = AcceptorStateMachine;
},{}],44:[function(require,module,exports){
(function (process){
var cryptoLib = require('crypto');
var Buffer = require('buffer').Buffer;
var AWS;
var util = {
engine: function engine() {
if (util.isBrowser() && typeof navigator !== 'undefined') {
return navigator.userAgent;
} else {
return process.platform + '/' + process.version;
}
},
userAgent: function userAgent() {
var name = util.isBrowser() ? 'js' : 'nodejs';
var agent = 'aws-sdk-' + name + '/' + require('./core').VERSION;
if (name === 'nodejs') agent += ' ' + util.engine();
return agent;
},
isBrowser: function isBrowser() { return process && process.browser; },
isNode: function isNode() { return !util.isBrowser(); },
nodeRequire: function nodeRequire(module) {
if (util.isNode()) return require(module);
},
multiRequire: function multiRequire(module1, module2) {
return require(util.isNode() ? module1 : module2);
},
uriEscape: function uriEscape(string) {
var output = encodeURIComponent(string);
output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape);
output = output.replace(/[*]/g, function(ch) {
return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
});
return output;
},
uriEscapePath: function uriEscapePath(string) {
var parts = [];
util.arrayEach(string.split('/'), function (part) {
parts.push(util.uriEscape(part));
});
return parts.join('/');
},
urlParse: function urlParse(url) {
return require('url').parse(url);
},
urlFormat: function urlFormat(url) {
return require('url').format(url);
},
queryStringParse: function queryStringParse(qs) {
return require('querystring').parse(qs);
},
queryParamsToString: function queryParamsToString(params) {
var items = [];
var escape = util.uriEscape;
var sortedKeys = Object.keys(params).sort();
util.arrayEach(sortedKeys, function(name) {
var value = params[name];
var ename = escape(name);
var result = ename + '=';
if (Array.isArray(value)) {
var vals = [];
util.arrayEach(value, function(item) { vals.push(escape(item)); });
result = ename + '=' + vals.sort().join('&' + ename + '=');
} else if (value !== undefined && value !== null) {
result = ename + '=' + escape(value);
}
items.push(result);
});
return items.join('&');
},
readFileSync: function readFileSync(path) {
if (typeof window !== 'undefined') return null;
return util.nodeRequire('fs').readFileSync(path, 'utf-8');
},
base64: {
encode: function encode64(string) {
return new Buffer(string).toString('base64');
},
decode: function decode64(string) {
return new Buffer(string, 'base64');
}
},
Buffer: Buffer,
buffer: {
toStream: function toStream(buffer) {
if (!util.Buffer.isBuffer(buffer)) buffer = new util.Buffer(buffer);
var readable = new (util.nodeRequire('stream').Readable)();
var pos = 0;
readable._read = function(size) {
if (pos >= buffer.length) return readable.push(null);
var end = pos + size;
if (end > buffer.length) end = buffer.length;
readable.push(buffer.slice(pos, end));
pos = end;
};
return readable;
},
concat: function(buffers) {
var length = 0,
offset = 0,
buffer = null, i;
for (i = 0; i < buffers.length; i++) {
length += buffers[i].length;
}
buffer = new Buffer(length);
for (i = 0; i < buffers.length; i++) {
buffers[i].copy(buffer, offset);
offset += buffers[i].length;
}
return buffer;
}
},
string: {
byteLength: function byteLength(string) {
if (string === null || string === undefined) return 0;
if (typeof string === 'string') string = new Buffer(string);
if (typeof string.byteLength === 'number') {
return string.byteLength;
} else if (typeof string.length === 'number') {
return string.length;
} else if (typeof string.size === 'number') {
return string.size;
} else if (typeof string.path === 'string') {
return util.nodeRequire('fs').lstatSync(string.path).size;
} else {
throw util.error(new Error('Cannot determine length of ' + string),
{ object: string });
}
},
upperFirst: function upperFirst(string) {
return string[0].toUpperCase() + string.substr(1);
},
lowerFirst: function lowerFirst(string) {
return string[0].toLowerCase() + string.substr(1);
}
},
ini: {
parse: function string(ini) {
var currentSection, map = {};
util.arrayEach(ini.split(/\r?\n/), function(line) {
line = line.split(/(^|\s);/)[0]; // remove comments
var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/);
if (section) {
currentSection = section[1];
} else if (currentSection) {
var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/);
if (item) {
map[currentSection] = map[currentSection] || {};
map[currentSection][item[1]] = item[2];
}
}
});
return map;
}
},
fn: {
noop: function() {},
makeAsync: function makeAsync(fn, expectedArgs) {
if (expectedArgs && expectedArgs <= fn.length) {
return fn;
}
return function() {
var args = Array.prototype.slice.call(arguments, 0);
var callback = args.pop();
var result = fn.apply(null, args);
callback(result);
};
}
},
jamespath: {
query: function query(expression, data) {
if (!data) return [];
var results = [];
var expressions = expression.split(/\s+\|\|\s+/);
util.arrayEach.call(this, expressions, function (expr) {
var objects = [data];
var tokens = expr.split('.');
util.arrayEach.call(this, tokens, function (token) {
var match = token.match('^(.+?)(?:\\[(-?\\d+|\\*|)\\])?$');
var newObjects = [];
util.arrayEach.call(this, objects, function (obj) {
if (match[1] === '*') {
util.arrayEach.call(this, obj, function (value) {
newObjects.push(value);
});
} else if (obj.hasOwnProperty(match[1])) {
newObjects.push(obj[match[1]]);
}
});
objects = newObjects;
if (match[2] !== undefined) {
newObjects = [];
util.arrayEach.call(this, objects, function (obj) {
if (Array.isArray(obj)) {
if (match[2] === '*' || match[2] === '') {
newObjects = newObjects.concat(obj);
} else {
var idx = parseInt(match[2], 10);
if (idx < 0) idx = obj.length + idx; // negative indexing
newObjects.push(obj[idx]);
}
}
});
objects = newObjects;
}
if (objects.length === 0) return util.abort;
});
if (objects.length > 0) {
results = objects;
return util.abort;
}
});
return results;
},
find: function find(expression, data) {
return util.jamespath.query(expression, data)[0];
}
},
date: {
getDate: function getDate() {
if (!AWS) AWS = require('./core');
if (AWS.config.systemClockOffset) { // use offset when non-zero
return new Date(new Date().getTime() + AWS.config.systemClockOffset);
} else {
return new Date();
}
},
iso8601: function iso8601(date) {
if (date === undefined) { date = util.date.getDate(); }
return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
},
rfc822: function rfc822(date) {
if (date === undefined) { date = util.date.getDate(); }
return date.toUTCString();
},
unixTimestamp: function unixTimestamp(date) {
if (date === undefined) { date = util.date.getDate(); }
return date.getTime() / 1000;
},
from: function format(date) {
if (typeof date === 'number') {
return new Date(date * 1000); // unix timestamp
} else {
return new Date(date);
}
},
format: function format(date, formatter) {
if (!formatter) formatter = 'iso8601';
return util.date[formatter](util.date.from(date));
},
parseTimestamp: function parseTimestamp(value) {
if (typeof value === 'number') { // unix timestamp (number)
return new Date(value * 1000);
} else if (value.match(/^\d+$/)) { // unix timestamp
return new Date(value * 1000);
} else if (value.match(/^\d{4}/)) { // iso8601
return new Date(value);
} else if (value.match(/^\w{3},/)) { // rfc822
return new Date(value);
} else {
throw util.error(
new Error('unhandled timestamp format: ' + value),
{code: 'TimestampParserError'});
}
}
},
crypto: {
crc32Table: [
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
0x2D02EF8D],
crc32: function crc32(data) {
var tbl = util.crypto.crc32Table;
var crc = 0 ^ -1;
if (typeof data === 'string') {
data = new Buffer(data);
}
for (var i = 0; i < data.length; i++) {
var code = data.readUInt8(i);
crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF];
}
return (crc ^ -1) >>> 0;
},
hmac: function hmac(key, string, digest, fn) {
if (!digest) digest = 'binary';
if (digest === 'buffer') { digest = undefined; }
if (!fn) fn = 'sha256';
if (typeof string === 'string') string = new Buffer(string);
return cryptoLib.createHmac(fn, key).update(string).digest(digest);
},
md5: function md5(data, digest, callback) {
return util.crypto.hash('md5', data, digest, callback);
},
sha256: function sha256(data, digest, callback) {
return util.crypto.hash('sha256', data, digest, callback);
},
hash: function(algorithm, data, digest, callback) {
var hash = util.crypto.createHash(algorithm);
if (!digest) { digest = 'binary'; }
if (digest === 'buffer') { digest = undefined; }
if (typeof data === 'string') data = new Buffer(data);
var sliceFn = util.arraySliceFn(data);
var isBuffer = Buffer.isBuffer(data);
if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true;
if (callback && typeof data === 'object' &&
typeof data.on === 'function' && !isBuffer) {
data.on('data', function(chunk) { hash.update(chunk); });
data.on('error', function(err) { callback(err); });
data.on('end', function() { callback(null, hash.digest(digest)); });
} else if (callback && sliceFn && !isBuffer &&
typeof FileReader !== 'undefined') {
var index = 0, size = 1024 * 512;
var reader = new FileReader();
reader.onerror = function() {
callback(new Error('Failed to read data.'));
};
reader.onload = function() {
var buf = new Buffer(new Uint8Array(reader.result));
hash.update(buf);
index += buf.length;
reader._continueReading();
};
reader._continueReading = function() {
if (index >= data.size) {
callback(null, hash.digest(digest));
return;
}
var back = index + size;
if (back > data.size) back = data.size;
reader.readAsArrayBuffer(sliceFn.call(data, index, back));
};
reader._continueReading();
} else {
if (util.isBrowser() && typeof data === 'object' && !isBuffer) {
data = new Buffer(new Uint8Array(data));
}
var out = hash.update(data).digest(digest);
if (callback) callback(null, out);
return out;
}
},
toHex: function toHex(data) {
var out = [];
for (var i = 0; i < data.length; i++) {
out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2));
}
return out.join('');
},
createHash: function createHash(algorithm) {
return cryptoLib.createHash(algorithm);
}
},
abort: {},
each: function each(object, iterFunction) {
for (var key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
var ret = iterFunction.call(this, key, object[key]);
if (ret === util.abort) break;
}
}
},
arrayEach: function arrayEach(array, iterFunction) {
for (var idx in array) {
if (array.hasOwnProperty(idx)) {
var ret = iterFunction.call(this, array[idx], parseInt(idx, 10));
if (ret === util.abort) break;
}
}
},
update: function update(obj1, obj2) {
util.each(obj2, function iterator(key, item) {
obj1[key] = item;
});
return obj1;
},
merge: function merge(obj1, obj2) {
return util.update(util.copy(obj1), obj2);
},
copy: function copy(object) {
if (object === null || object === undefined) return object;
var dupe = {};
for (var key in object) {
dupe[key] = object[key];
}
return dupe;
},
isEmpty: function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
},
arraySliceFn: function arraySliceFn(obj) {
var fn = obj.slice || obj.webkitSlice || obj.mozSlice;
return typeof fn === 'function' ? fn : null;
},
isType: function isType(obj, type) {
if (typeof type === 'function') type = util.typeName(type);
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
},
typeName: function typeName(type) {
if (type.hasOwnProperty('name')) return type.name;
var str = type.toString();
var match = str.match(/^\s*function (.+)\(/);
return match ? match[1] : str;
},
error: function error(err, options) {
var originalError = null;
if (typeof err.message === 'string' && err.message !== '') {
if (typeof options === 'string' || (options && options.message)) {
originalError = util.copy(err);
originalError.message = err.message;
}
}
err.message = err.message || null;
if (typeof options === 'string') {
err.message = options;
} else if (typeof options === 'object' && options !== null) {
util.update(err, options);
if (options.message)
err.message = options.message;
if (options.code || options.name)
err.code = options.code || options.name;
if (options.stack)
err.stack = options.stack;
}
if (typeof Object.defineProperty === 'function') {
Object.defineProperty(err, 'name', {writable: true, enumerable: false});
Object.defineProperty(err, 'message', {enumerable: true});
}
err.name = options && options.name || err.name || err.code || 'Error';
err.time = new Date();
if (originalError) err.originalError = originalError;
return err;
},
inherit: function inherit(klass, features) {
var newObject = null;
if (features === undefined) {
features = klass;
klass = Object;
newObject = {};
} else {
var ctor = function ConstructorWrapper() {};
ctor.prototype = klass.prototype;
newObject = new ctor();
}
if (features.constructor === Object) {
features.constructor = function() {
if (klass !== Object) {
return klass.apply(this, arguments);
}
};
}
features.constructor.prototype = newObject;
util.update(features.constructor.prototype, features);
features.constructor.__super__ = klass;
return features.constructor;
},
mixin: function mixin() {
var klass = arguments[0];
for (var i = 1; i < arguments.length; i++) {
for (var prop in arguments[i].prototype) {
var fn = arguments[i].prototype[prop];
if (prop !== 'constructor') {
klass.prototype[prop] = fn;
}
}
}
return klass;
},
hideProperties: function hideProperties(obj, props) {
if (typeof Object.defineProperty !== 'function') return;
util.arrayEach(props, function (key) {
Object.defineProperty(obj, key, {
enumerable: false, writable: true, configurable: true });
});
},
property: function property(obj, name, value, enumerable, isValue) {
var opts = {
configurable: true,
enumerable: enumerable !== undefined ? enumerable : true
};
if (typeof value === 'function' && !isValue) {
opts.get = value;
}
else {
opts.value = value; opts.writable = true;
}
Object.defineProperty(obj, name, opts);
},
memoizedProperty: function memoizedProperty(obj, name, get, enumerable) {
var cachedValue = null;
util.property(obj, name, function() {
if (cachedValue === null) {
cachedValue = get();
}
return cachedValue;
}, enumerable);
},
hoistPayloadMember: function hoistPayloadMember(resp) {
var req = resp.request;
var operation = req.operation;
var output = req.service.api.operations[operation].output;
if (output.payload) {
var payloadMember = output.members[output.payload];
var responsePayload = resp.data[output.payload];
if (payloadMember.type === 'structure') {
util.each(responsePayload, function(key, value) {
util.property(resp.data, key, value, false);
});
}
}
},
computeSha256: function computeSha256(body, done) {
if (util.isNode()) {
var Stream = util.nodeRequire('stream').Stream;
var fs = util.nodeRequire('fs');
if (body instanceof Stream) {
if (typeof body.path === 'string') { // assume file object
body = fs.createReadStream(body.path);
} else { // TODO support other stream types
return done(new Error('Non-file stream objects are ' +
'not supported with SigV4'));
}
}
}
util.crypto.sha256(body, 'hex', function(err, sha) {
if (err) done(err);
else done(null, sha);
});
},
isClockSkewed: function isClockSkewed(serverTime) {
if (serverTime) {
util.property(AWS.config, 'isClockSkewed',
Math.abs(new Date().getTime() - serverTime) >= 300000, false);
return AWS.config.isClockSkewed;
}
},
applyClockOffset: function applyClockOffset(serverTime) {
if (serverTime)
AWS.config.systemClockOffset = serverTime - new Date().getTime();
},
extractRequestId: function extractRequestId(resp) {
var requestId = resp.httpResponse.headers['x-amz-request-id'] ||
resp.httpResponse.headers['x-amzn-requestid'];
if (!requestId && resp.data && resp.data.ResponseMetadata) {
requestId = resp.data.ResponseMetadata.RequestId;
}
if (requestId) {
resp.requestId = requestId;
}
if (resp.error) {
resp.error.requestId = requestId;
}
}
};
module.exports = util;
}).call(this,require("FWaASH"))
},{"./core":3,"FWaASH":58,"buffer":47,"crypto":51,"querystring":62,"url":63}],45:[function(require,module,exports){
var util = require('../util');
var Shape = require('../model/shape');
function DomXmlParser() { }
DomXmlParser.prototype.parse = function(xml, shape) {
if (xml.replace(/^\s+/, '') === '') return {};
var result, error;
try {
if (window.DOMParser) {
try {
var parser = new DOMParser();
result = parser.parseFromString(xml, 'text/xml');
} catch (syntaxError) {
throw util.error(new Error('Parse error in document'),
{
originalError: syntaxError,
code: 'XMLParserError',
retryable: true
});
}
if (result.documentElement === null) {
throw util.error(new Error('Cannot parse empty document.'),
{
code: 'XMLParserError',
retryable: true
});
}
var isError = result.getElementsByTagName('parsererror')[0];
if (isError && (isError.parentNode === result ||
isError.parentNode.nodeName === 'body' ||
isError.parentNode.parentNode === result ||
isError.parentNode.parentNode.nodeName === 'body')) {
var errorElement = isError.getElementsByTagName('div')[0] || isError;
throw util.error(new Error(errorElement.textContent || 'Parser error in document'),
{
code: 'XMLParserError',
retryable: true
});
}
} else if (window.ActiveXObject) {
result = new window.ActiveXObject('Microsoft.XMLDOM');
result.async = false;
if (!result.loadXML(xml)) {
throw util.error(new Error('Parse error in document'),
{
code: 'XMLParserError',
retryable: true
});
}
} else {
throw new Error('Cannot load XML parser');
}
} catch (e) {
error = e;
}
if (result && result.documentElement && !error) {
var data = parseXml(result.documentElement, shape);
var metadata = result.getElementsByTagName('ResponseMetadata')[0];
if (metadata) {
data.ResponseMetadata = parseXml(metadata, {});
}
return data;
} else if (error) {
throw util.error(error || new Error(), {code: 'XMLParserError', retryable: true});
} else { // empty xml document
return {};
}
};
function parseXml(xml, shape) {
if (!shape) shape = {};
switch (shape.type) {
case 'structure': return parseStructure(xml, shape);
case 'map': return parseMap(xml, shape);
case 'list': return parseList(xml, shape);
case undefined: case null: return parseUnknown(xml);
default: return parseScalar(xml, shape);
}
}
function parseStructure(xml, shape) {
var data = {};
if (xml === null) return data;
util.each(shape.members, function(memberName, memberShape) {
if (memberShape.isXmlAttribute) {
if (xml.attributes.hasOwnProperty(memberShape.name)) {
var value = xml.attributes[memberShape.name].value;
data[memberName] = parseXml({textContent: value}, memberShape);
}
} else {
var xmlChild = memberShape.flattened ? xml :
xml.getElementsByTagName(memberShape.name)[0];
if (xmlChild) {
data[memberName] = parseXml(xmlChild, memberShape);
} else if (!memberShape.flattened && memberShape.type === 'list') {
data[memberName] = memberShape.defaultValue;
}
}
});
return data;
}
function parseMap(xml, shape) {
var data = {};
var xmlKey = shape.key.name || 'key';
var xmlValue = shape.value.name || 'value';
var tagName = shape.flattened ? shape.name : 'entry';
var child = xml.firstElementChild;
while (child) {
if (child.nodeName === tagName) {
var key = child.getElementsByTagName(xmlKey)[0].textContent;
var value = child.getElementsByTagName(xmlValue)[0];
data[key] = parseXml(value, shape.value);
}
child = child.nextElementSibling;
}
return data;
}
function parseList(xml, shape) {
var data = [];
var tagName = shape.flattened ? shape.name : (shape.member.name || 'member');
var child = xml.firstElementChild;
while (child) {
if (child.nodeName === tagName) {
data.push(parseXml(child, shape.member));
}
child = child.nextElementSibling;
}
return data;
}
function parseScalar(xml, shape) {
if (xml.getAttribute) {
var encoding = xml.getAttribute('encoding');
if (encoding === 'base64') {
shape = new Shape.create({type: encoding});
}
}
var text = xml.textContent;
if (text === '') text = null;
if (typeof shape.toType === 'function') {
return shape.toType(text);
} else {
return text;
}
}
function parseUnknown(xml) {
if (xml === undefined || xml === null) return '';
if (!xml.firstElementChild) {
if (xml.parentNode.parentNode === null) return {};
if (xml.childNodes.length === 0) return '';
else return xml.textContent;
}
var shape = {type: 'structure', members: {}};
var child = xml.firstElementChild;
while (child) {
var tag = child.nodeName;
if (shape.members.hasOwnProperty(tag)) {
shape.members[tag].type = 'list';
} else {
shape.members[tag] = {name: tag};
}
child = child.nextElementSibling;
}
return parseStructure(xml, shape);
}
module.exports = DomXmlParser;
},{"../model/shape":20,"../util":44}],46:[function(require,module,exports){
var util = require('../util');
var builder = require('xmlbuilder');
function XmlBuilder() { }
XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) {
var xml = builder.create(rootElement);
applyNamespaces(xml, shape);
serialize(xml, params, shape);
return xml.children.length > 0 || noEmpty ? xml.root().toString() : '';
};
function serialize(xml, value, shape) {
switch (shape.type) {
case 'structure': return serializeStructure(xml, value, shape);
case 'map': return serializeMap(xml, value, shape);
case 'list': return serializeList(xml, value, shape);
default: return serializeScalar(xml, value, shape);
}
}
function serializeStructure(xml, params, shape) {
util.arrayEach(shape.memberNames, function(memberName) {
var memberShape = shape.members[memberName];
if (memberShape.location !== 'body') return;
var value = params[memberName];
var name = memberShape.name;
if (value !== undefined && value !== null) {
if (memberShape.isXmlAttribute) {
xml.att(name, value);
} else if (memberShape.flattened) {
serialize(xml, value, memberShape);
} else {
var element = xml.ele(name);
applyNamespaces(element, memberShape);
serialize(element, value, memberShape);
}
}
});
}
function serializeMap(xml, map, shape) {
var xmlKey = shape.key.name || 'key';
var xmlValue = shape.value.name || 'value';
util.each(map, function(key, value) {
var entry = xml.ele(shape.flattened ? shape.name : 'entry');
serialize(entry.ele(xmlKey), key, shape.key);
serialize(entry.ele(xmlValue), value, shape.value);
});
}
function serializeList(xml, list, shape) {
if (shape.flattened) {
util.arrayEach(list, function(value) {
var name = shape.member.name || shape.name;
var element = xml.ele(name);
serialize(element, value, shape.member);
});
} else {
util.arrayEach(list, function(value) {
var name = shape.member.name || 'member';
var element = xml.ele(name);
serialize(element, value, shape.member);
});
}
}
function serializeScalar(xml, value, shape) {
xml.txt(shape.toWireFormat(value));
}
function applyNamespaces(xml, shape) {
var uri, prefix = 'xmlns';
if (shape.xmlNamespaceUri) {
uri = shape.xmlNamespaceUri;
if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix;
} else if (xml.isRoot && shape.api.xmlNamespaceUri) {
uri = shape.api.xmlNamespaceUri;
}
if (uri) xml.att(prefix, uri);
}
module.exports = XmlBuilder;
},{"../util":44,"xmlbuilder":82}],47:[function(require,module,exports){
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = Buffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192
Buffer._useTypedArrays = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return 42 === arr.foo() &&
typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
} catch (e) {
return false
}
})()
function Buffer (subject, encoding, noZero) {
if (!(this instanceof Buffer))
return new Buffer(subject, encoding, noZero)
var type = typeof subject
if (encoding === 'base64' && type === 'string') {
subject = stringtrim(subject)
while (subject.length % 4 !== 0) {
subject = subject + '='
}
}
var length
if (type === 'number')
length = coerce(subject)
else if (type === 'string')
length = Buffer.byteLength(subject, encoding)
else if (type === 'object')
length = coerce(subject.length) // assume that object is array-like
else
throw new Error('First argument needs to be a number, array or string.')
var buf
if (Buffer._useTypedArrays) {
buf = Buffer._augment(new Uint8Array(length))
} else {
buf = this
buf.length = length
buf._isBuffer = true
}
var i
if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
buf._set(subject)
} else if (isArrayish(subject)) {
for (i = 0; i < length; i++) {
if (Buffer.isBuffer(subject))
buf[i] = subject.readUInt8(i)
else
buf[i] = subject[i]
}
} else if (type === 'string') {
buf.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
for (i = 0; i < length; i++) {
buf[i] = 0
}
}
return buf
}
Buffer.isEncoding = function (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.isBuffer = function (b) {
return !!(b !== null && b !== undefined && b._isBuffer)
}
Buffer.byteLength = function (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'hex':
ret = str.length / 2
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'base64':
ret = base64ToBytes(str).length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.concat = function (list, totalLength) {
assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' +
'list should be an Array.')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (typeof totalLength !== 'number') {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
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
assert(strLen % 2 === 0, 'Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var byte = parseInt(string.substr(i * 2, 2), 16)
assert(!isNaN(byte), 'Invalid hex string')
buf[offset + i] = byte
}
Buffer._charsWritten = i * 2
return i
}
function _utf8Write (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(utf8ToBytes(string), buf, offset, length)
return charsWritten
}
function _asciiWrite (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function _binaryWrite (buf, string, offset, length) {
return _asciiWrite(buf, string, offset, length)
}
function _base64Write (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function _utf16leWrite (buf, string, offset, length) {
var charsWritten = Buffer._charsWritten =
blitBuffer(utf16leToBytes(string), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function (string, offset, length, encoding) {
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = _hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = _utf8Write(this, string, offset, length)
break
case 'ascii':
ret = _asciiWrite(this, string, offset, length)
break
case 'binary':
ret = _binaryWrite(this, string, offset, length)
break
case 'base64':
ret = _base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = _utf16leWrite(this, string, offset, length)
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.prototype.toString = function (encoding, start, end) {
var self = this
encoding = String(encoding || 'utf8').toLowerCase()
start = Number(start) || 0
end = (end !== undefined)
? Number(end)
: end = self.length
if (end === start)
return ''
var ret
switch (encoding) {
case 'hex':
ret = _hexSlice(self, start, end)
break
case 'utf8':
case 'utf-8':
ret = _utf8Slice(self, start, end)
break
case 'ascii':
ret = _asciiSlice(self, start, end)
break
case 'binary':
ret = _binarySlice(self, start, end)
break
case 'base64':
ret = _base64Slice(self, start, end)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = _utf16leSlice(self, start, end)
break
default:
throw new Error('Unknown encoding')
}
return ret
}
Buffer.prototype.toJSON = function () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
Buffer.prototype.copy = function (target, target_start, start, end) {
var source = this
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (!target_start) target_start = 0
if (end === start) return
if (target.length === 0 || source.length === 0) return
assert(end >= start, 'sourceEnd < sourceStart')
assert(target_start >= 0 && target_start < target.length,
'targetStart out of bounds')
assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
if (end > this.length)
end = this.length
if (target.length - target_start < end - start)
end = target.length - target_start + start
var len = end - start
if (len < 100 || !Buffer._useTypedArrays) {
for (var i = 0; i < len; i++)
target[i + target_start] = this[i + start]
} else {
target._set(this.subarray(start, start + len), target_start)
}
}
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) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
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])
return ret
}
function _binarySlice (buf, start, end) {
return _asciiSlice(buf, start, end)
}
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 (start, end) {
var len = this.length
start = clamp(start, len, 0)
end = clamp(end, len, len)
if (Buffer._useTypedArrays) {
return Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
var newBuf = new Buffer(sliceLen, undefined, true)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
return newBuf
}
}
Buffer.prototype.get = function (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
Buffer.prototype.set = function (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
Buffer.prototype.readUInt8 = function (offset, noAssert) {
if (!noAssert) {
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'Trying to read beyond buffer length')
}
if (offset >= this.length)
return
return this[offset]
}
function _readUInt16 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val
if (littleEndian) {
val = buf[offset]
if (offset + 1 < len)
val |= buf[offset + 1] << 8
} else {
val = buf[offset] << 8
if (offset + 1 < len)
val |= buf[offset + 1]
}
return val
}
Buffer.prototype.readUInt16LE = function (offset, noAssert) {
return _readUInt16(this, offset, true, noAssert)
}
Buffer.prototype.readUInt16BE = function (offset, noAssert) {
return _readUInt16(this, offset, false, noAssert)
}
function _readUInt32 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val
if (littleEndian) {
if (offset + 2 < len)
val = buf[offset + 2] << 16
if (offset + 1 < len)
val |= buf[offset + 1] << 8
val |= buf[offset]
if (offset + 3 < len)
val = val + (buf[offset + 3] << 24 >>> 0)
} else {
if (offset + 1 < len)
val = buf[offset + 1] << 16
if (offset + 2 < len)
val |= buf[offset + 2] << 8
if (offset + 3 < len)
val |= buf[offset + 3]
val = val + (buf[offset] << 24 >>> 0)
}
return val
}
Buffer.prototype.readUInt32LE = function (offset, noAssert) {
return _readUInt32(this, offset, true, noAssert)
}
Buffer.prototype.readUInt32BE = function (offset, noAssert) {
return _readUInt32(this, offset, false, noAssert)
}
Buffer.prototype.readInt8 = function (offset, noAssert) {
if (!noAssert) {
assert(offset !== undefined && offset !== null,
'missing offset')
assert(offset < this.length, 'Trying to read beyond buffer length')
}
if (offset >= this.length)
return
var neg = this[offset] & 0x80
if (neg)
return (0xff - this[offset] + 1) * -1
else
return this[offset]
}
function _readInt16 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val = _readUInt16(buf, offset, littleEndian, true)
var neg = val & 0x8000
if (neg)
return (0xffff - val + 1) * -1
else
return val
}
Buffer.prototype.readInt16LE = function (offset, noAssert) {
return _readInt16(this, offset, true, noAssert)
}
Buffer.prototype.readInt16BE = function (offset, noAssert) {
return _readInt16(this, offset, false, noAssert)
}
function _readInt32 (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
var len = buf.length
if (offset >= len)
return
var val = _readUInt32(buf, offset, littleEndian, true)
var neg = val & 0x80000000
if (neg)
return (0xffffffff - val + 1) * -1
else
return val
}
Buffer.prototype.readInt32LE = function (offset, noAssert) {
return _readInt32(this, offset, true, noAssert)
}
Buffer.prototype.readInt32BE = function (offset, noAssert) {
return _readInt32(this, offset, false, noAssert)
}
function _readFloat (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
}
return ieee754.read(buf, offset, littleEndian, 23, 4)
}
Buffer.prototype.readFloatLE = function (offset, noAssert) {
return _readFloat(this, offset, true, noAssert)
}
Buffer.prototype.readFloatBE = function (offset, noAssert) {
return _readFloat(this, offset, false, noAssert)
}
function _readDouble (buf, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
}
return ieee754.read(buf, offset, littleEndian, 52, 8)
}
Buffer.prototype.readDoubleLE = function (offset, noAssert) {
return _readDouble(this, offset, true, noAssert)
}
Buffer.prototype.readDoubleBE = function (offset, noAssert) {
return _readDouble(this, offset, false, noAssert)
}
Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'trying to write beyond buffer length')
verifuint(value, 0xff)
}
if (offset >= this.length) return
this[offset] = value
}
function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
verifuint(value, 0xffff)
}
var len = buf.length
if (offset >= len)
return
for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
buf[offset + i] =
(value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
_writeUInt16(this, value, offset, true, noAssert)
}
Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
_writeUInt16(this, value, offset, false, noAssert)
}
function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
verifuint(value, 0xffffffff)
}
var len = buf.length
if (offset >= len)
return
for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
buf[offset + i] =
(value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
_writeUInt32(this, value, offset, true, noAssert)
}
Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
_writeUInt32(this, value, offset, false, noAssert)
}
Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < this.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7f, -0x80)
}
if (offset >= this.length)
return
if (value >= 0)
this.writeUInt8(value, offset, noAssert)
else
this.writeUInt8(0xff + value + 1, offset, noAssert)
}
function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7fff, -0x8000)
}
var len = buf.length
if (offset >= len)
return
if (value >= 0)
_writeUInt16(buf, value, offset, littleEndian, noAssert)
else
_writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
}
Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
_writeInt16(this, value, offset, true, noAssert)
}
Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
_writeInt16(this, value, offset, false, noAssert)
}
function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7fffffff, -0x80000000)
}
var len = buf.length
if (offset >= len)
return
if (value >= 0)
_writeUInt32(buf, value, offset, littleEndian, noAssert)
else
_writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
}
Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
_writeInt32(this, value, offset, true, noAssert)
}
Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
_writeInt32(this, value, offset, false, noAssert)
}
function _writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
var len = buf.length
if (offset >= len)
return
ieee754.write(buf, value, offset, littleEndian, 23, 4)
}
Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
_writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
_writeFloat(this, value, offset, false, noAssert)
}
function _writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset + 7 < buf.length,
'Trying to write beyond buffer length')
verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
var len = buf.length
if (offset >= len)
return
ieee754.write(buf, value, offset, littleEndian, 52, 8)
}
Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
_writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
_writeDouble(this, value, offset, false, noAssert)
}
Buffer.prototype.fill = function (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (typeof value === 'string') {
value = value.charCodeAt(0)
}
assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
assert(end >= start, 'end < start')
if (end === start) return
if (this.length === 0) return
assert(start >= 0 && start < this.length, 'start out of bounds')
assert(end >= 0 && end <= this.length, 'end out of bounds')
for (var i = start; i < end; i++) {
this[i] = value
}
}
Buffer.prototype.inspect = function () {
var out = []
var len = this.length
for (var i = 0; i < len; i++) {
out[i] = toHex(this[i])
if (i === exports.INSPECT_MAX_BYTES) {
out[i + 1] = '...'
break
}
}
return '<Buffer ' + out.join(' ') + '>'
}
Buffer.prototype.toArrayBuffer = function () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer._useTypedArrays) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1)
buf[i] = this[i]
return buf.buffer
}
} else {
throw new Error('Buffer.toArrayBuffer not supported in this browser')
}
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
var BP = Buffer.prototype
Buffer._augment = function (arr) {
arr._isBuffer = true
arr._get = arr.get
arr._set = arr.set
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
function clamp (index, len, defaultValue) {
if (typeof index !== 'number') return defaultValue
index = ~~index; // Coerce to integer.
if (index >= len) return len
if (index >= 0) return index
index += len
if (index >= 0) return index
return 0
}
function coerce (length) {
length = ~~Math.ceil(+length)
return length < 0 ? 0 : length
}
function isArray (subject) {
return (Array.isArray || function (subject) {
return Object.prototype.toString.call(subject) === '[object Array]'
})(subject)
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
var b = str.charCodeAt(i)
if (b <= 0x7F)
byteArray.push(str.charCodeAt(i))
else {
var start = i
if (b >= 0xD800 && b <= 0xDFFF) i++
var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
for (var j = 0; j < h.length; j++)
byteArray.push(parseInt(h[j], 16))
}
}
return byteArray
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(str)
}
function blitBuffer (src, dst, offset, length) {
var pos
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length))
break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
function verifuint (value, max) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value >= 0, 'specified a negative value for writing an unsigned value')
assert(value <= max, 'value is larger than maximum value for type')
assert(Math.floor(value) === value, 'value has a fractional component')
}
function verifsint (value, max, min) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value <= max, 'value larger than maximum allowed value')
assert(value >= min, 'value smaller than minimum allowed value')
assert(Math.floor(value) === value, 'value has a fractional component')
}
function verifIEEE754 (value, max, min) {
assert(typeof value === 'number', 'cannot write a non-number as a number')
assert(value <= max, 'value larger than maximum allowed value')
assert(value >= min, 'value smaller than minimum allowed value')
}
function assert (test, message) {
if (!test) throw new Error(message || 'Failed assertion')
}
},{"base64-js":48,"ieee754":49}],48:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
arr = new Arr(b64.length * 3 / 4 - placeHolders)
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],49:[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
}
},{}],50:[function(require,module,exports){
var Buffer = require('buffer').Buffer;
var intSize = 4;
var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
var chrsz = 8;
function toArray(buf, bigEndian) {
if ((buf.length % intSize) !== 0) {
var len = buf.length + (intSize - (buf.length % intSize));
buf = Buffer.concat([buf, zeroBuffer], len);
}
var arr = [];
var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
for (var i = 0; i < buf.length; i += intSize) {
arr.push(fn.call(buf, i));
}
return arr;
}
function toBuffer(arr, size, bigEndian) {
var buf = new Buffer(size);
var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
for (var i = 0; i < arr.length; i++) {
fn.call(buf, arr[i], i * 4, true);
}
return buf;
}
function hash(buf, fn, hashSize, bigEndian) {
if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
return toBuffer(arr, hashSize, bigEndian);
}
module.exports = { hash: hash };
},{"buffer":47}],51:[function(require,module,exports){
var Buffer = require('buffer').Buffer
var sha = require('./sha')
var sha256 = require('./sha256')
var rng = require('./rng')
var md5 = require('./md5')
var algorithms = {
sha1: sha,
sha256: sha256,
md5: md5
}
var blocksize = 64
var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
function hmac(fn, key, data) {
if(!Buffer.isBuffer(key)) key = new Buffer(key)
if(!Buffer.isBuffer(data)) data = new Buffer(data)
if(key.length > blocksize) {
key = fn(key)
} else if(key.length < blocksize) {
key = Buffer.concat([key, zeroBuffer], blocksize)
}
var ipad = new Buffer(blocksize), opad = new Buffer(blocksize)
for(var i = 0; i < blocksize; i++) {
ipad[i] = key[i] ^ 0x36
opad[i] = key[i] ^ 0x5C
}
var hash = fn(Buffer.concat([ipad, data]))
return fn(Buffer.concat([opad, hash]))
}
function hash(alg, key) {
alg = alg || 'sha1'
var fn = algorithms[alg]
var bufs = []
var length = 0
if(!fn) error('algorithm:', alg, 'is not yet supported')
return {
update: function (data) {
if(!Buffer.isBuffer(data)) data = new Buffer(data)
bufs.push(data)
length += data.length
return this
},
digest: function (enc) {
var buf = Buffer.concat(bufs)
var r = key ? hmac(fn, key, buf) : fn(buf)
bufs = null
return enc ? r.toString(enc) : r
}
}
}
function error () {
var m = [].slice.call(arguments).join(' ')
throw new Error([
m,
'we accept pull requests',
'http://github.com/dominictarr/crypto-browserify'
].join('\n'))
}
exports.createHash = function (alg) { return hash(alg) }
exports.createHmac = function (alg, key) { return hash(alg, key) }
exports.randomBytes = function(size, callback) {
if (callback && callback.call) {
try {
callback.call(this, undefined, new Buffer(rng(size)))
} catch (err) { callback(err) }
} else {
return new Buffer(rng(size))
}
}
function each(a, f) {
for(var i in a)
f(a[i], i)
}
each(['createCredentials'
, 'createCipher'
, 'createCipheriv'
, 'createDecipher'
, 'createDecipheriv'
, 'createSign'
, 'createVerify'
, 'createDiffieHellman'
, 'pbkdf2'], function (name) {
exports[name] = function () {
error('sorry,', name, 'is not implemented yet')
}
})
},{"./md5":52,"./rng":53,"./sha":54,"./sha256":55,"buffer":47}],52:[function(require,module,exports){
var helpers = require('./helpers');
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
function core_md5(x, len)
{
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 Array(a, b, c, d);
}
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);
}
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
module.exports = function md5(buf) {
return helpers.hash(buf, core_md5, 16);
};
},{"./helpers":50}],53:[function(require,module,exports){
(function() {
var _global = this;
var mathRNG, whatwgRNG;
mathRNG = function(size) {
var bytes = new Array(size);
var r;
for (var i = 0, r; i < size; i++) {
if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
bytes[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return bytes;
}
if (_global.crypto && crypto.getRandomValues) {
whatwgRNG = function(size) {
var bytes = new Uint8Array(size);
crypto.getRandomValues(bytes);
return bytes;
}
}
module.exports = whatwgRNG || mathRNG;
}())
},{}],54:[function(require,module,exports){
var helpers = require('./helpers');
function core_sha1(x, len)
{
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for(var j = 0; j < 80; j++)
{
if(j < 16) w[j] = x[i + j];
else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
function sha1_ft(t, b, c, d)
{
if(t < 20) return (b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
function sha1_kt(t)
{
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
module.exports = function sha1(buf) {
return helpers.hash(buf, core_sha1, 20, true);
};
},{"./helpers":50}],55:[function(require,module,exports){
var helpers = require('./helpers');
var safe_add = function(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
var S = function(X, n) {
return (X >>> n) | (X << (32 - n));
};
var R = function(X, n) {
return (X >>> n);
};
var Ch = function(x, y, z) {
return ((x & y) ^ ((~x) & z));
};
var Maj = function(x, y, z) {
return ((x & y) ^ (x & z) ^ (y & z));
};
var Sigma0256 = function(x) {
return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
};
var Sigma1256 = function(x) {
return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
};
var Gamma0256 = function(x) {
return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
};
var Gamma1256 = function(x) {
return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
};
var core_sha256 = function(m, l) {
var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,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 HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);
var W = new Array(64);
var a, b, c, d, e, f, g, h, i, j;
var T1, T2;
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >> 9) << 4) + 15] = l;
for (var i = 0; i < m.length; i += 16) {
a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
for (var j = 0; j < 64; j++) {
if (j < 16) {
W[j] = m[j + i];
} else {
W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
}
T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
T2 = safe_add(Sigma0256(a), Maj(a, b, c));
h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2);
}
HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]);
HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]);
}
return HASH;
};
module.exports = function sha256(buf) {
return helpers.hash(buf, core_sha256, 32, true);
};
},{"./helpers":50}],56:[function(require,module,exports){
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
EventEmitter.defaultMaxListeners = 10;
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
this._events[type] = listener;
else if (isObject(this._events[type]))
this._events[type].push(listener);
else
this._events[type] = [this._events[type], listener];
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],57:[function(require,module,exports){
if (typeof Object.create === 'function') {
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 {
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],58:[function(require,module,exports){
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
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');
};
},{}],59:[function(require,module,exports){
(function (global){
;(function(root) {
var freeExports = typeof exports == 'object' && exports;
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
var punycode,
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
regexPunycode = /^xn--/,
regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
key;
function error(type) {
throw RangeError(errors[type]);
}
function map(array, fn) {
var length = array.length;
while (length--) {
array[length] = fn(array[length]);
}
return array;
}
function mapDomain(string, fn) {
return map(string.split(regexSeparators), fn).join('.');
}
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) {
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
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('');
}
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;
}
function digitToBasic(digit, flag) {
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
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));
}
function decode(input) {
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
baseMinusT;
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
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);
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
inputLength,
handledCPCountPlusOne,
baseMinusT,
qMinusT;
input = ucs2decode(input);
inputLength = input.length;
n = initialN;
delta = 0;
bias = initialBias;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
if (basicLength) {
output.push(delimiter);
}
while (handledCPCount < inputLength) {
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
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) {
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('');
}
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
punycode = {
'version': '1.2.4',
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.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 self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],60:[function(require,module,exports){
'use strict';
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;
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]';
};
},{}],61:[function(require,module,exports){
'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 obj[k].map(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;
};
},{}],62:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":60,"./encode":61}],63:[function(require,module,exports){
var punycode = require('punycode');
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;
}
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
autoEscape = ['\''].concat(unwise),
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
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 && 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 (!isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
var rest = url;
rest = rest.trim();
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
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]))) {
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;
}
var auth, atSign;
if (hostEnd === -1) {
atSign = rest.lastIndexOf('@');
} else {
atSign = rest.lastIndexOf('@', hostEnd);
}
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
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 (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
this.parseHost();
this.hostname = this.hostname || '';
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
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) {
newpart += 'x';
} else {
newpart += part[j];
}
}
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 {
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
var domainArray = this.hostname.split('.');
var newOut = [];
for (var i = 0; i < domainArray.length; ++i) {
var s = domainArray[i];
newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
'xn--' + punycode.encode(s) : s);
}
this.hostname = newOut.join('.');
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
if (!unsafeProtocol[lowerProto]) {
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
var hash = rest.indexOf('#');
if (hash !== -1) {
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) {
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
this.href = this.format();
return this;
};
function urlFormat(obj) {
if (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 &&
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 += ':';
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 (isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
Object.keys(this).forEach(function(k) {
result[k] = this[k];
}, this);
result.hash = relative.hash;
if (relative.href === '') {
result.href = result.format();
return result;
}
if (relative.slashes && !relative.protocol) {
Object.keys(relative).forEach(function(k) {
if (k !== 'protocol')
result[k] = relative[k];
});
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 (!slashedProtocol[relative.protocol]) {
Object.keys(relative).forEach(function(k) {
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;
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 (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) {
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;
} else if (relPath.length) {
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!isNullOrUndefined(relative.search)) {
if (psychotic) {
result.hostname = result.host = srcPath.shift();
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;
if (!isNull(result.pathname) || !isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
result.pathname = null;
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host) && (last === '.' || last === '..') ||
last === '');
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 (!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) === '/');
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
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('/');
}
if (!isNull(result.pathname) || !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;
};
function isString(arg) {
return typeof arg === "string";
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isNull(arg) {
return arg === null;
}
function isNullOrUndefined(arg) {
return arg == null;
}
},{"punycode":59,"querystring":62}],64:[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';
}
},{}],65:[function(require,module,exports){
(function (process,global){
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;
};
exports.deprecate = function(fn, msg) {
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];
};
function inspect(obj, opts) {
var ctx = {
seen: [],
stylize: stylizeNoColor
};
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
ctx.showHidden = opts;
} else if (opts) {
exports._extend(ctx, opts);
}
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;
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]
};
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
'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) {
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
value.inspect !== exports.inspect &&
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
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 = ['{', '}'];
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
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');
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];
}
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'];
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(' ');
}
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
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("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":64,"FWaASH":58,"inherits":57}],66:[function(require,module,exports){
(function() {
var XMLAttribute, create;
create = require('lodash/object/create');
module.exports = XMLAttribute = (function() {
function XMLAttribute(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing attribute name of element " + parent.name);
}
if (value == null) {
throw new Error("Missing attribute value for attribute " + name + " of element " + parent.name);
}
this.name = this.stringify.attName(name);
this.value = this.stringify.attValue(value);
}
XMLAttribute.prototype.clone = function() {
return create(XMLAttribute.prototype, this);
};
XMLAttribute.prototype.toString = function(options, level) {
return ' ' + this.name + '="' + this.value + '"';
};
return XMLAttribute;
})();
}).call(this);
},{"lodash/object/create":125}],67:[function(require,module,exports){
(function() {
var XMLBuilder, XMLDeclaration, XMLDocType, XMLElement, XMLStringifier;
XMLStringifier = require('./XMLStringifier');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLElement = require('./XMLElement');
module.exports = XMLBuilder = (function() {
function XMLBuilder(name, options) {
var root, temp;
if (name == null) {
throw new Error("Root element needs a name");
}
if (options == null) {
options = {};
}
this.options = options;
this.stringify = new XMLStringifier(options);
temp = new XMLElement(this, 'doc');
root = temp.element(name);
root.isRoot = true;
root.documentObject = this;
this.rootObject = root;
if (!options.headless) {
root.declaration(options);
if ((options.pubID != null) || (options.sysID != null)) {
root.doctype(options);
}
}
}
XMLBuilder.prototype.root = function() {
return this.rootObject;
};
XMLBuilder.prototype.end = function(options) {
return this.toString(options);
};
XMLBuilder.prototype.toString = function(options) {
var indent, newline, offset, pretty, r, ref, ref1, ref2;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
r = '';
if (this.xmldec != null) {
r += this.xmldec.toString(options);
}
if (this.doctype != null) {
r += this.doctype.toString(options);
}
r += this.rootObject.toString(options);
if (pretty && r.slice(-newline.length) === newline) {
r = r.slice(0, -newline.length);
}
return r;
};
return XMLBuilder;
})();
}).call(this);
},{"./XMLDeclaration":74,"./XMLDocType":75,"./XMLElement":76,"./XMLStringifier":80}],68:[function(require,module,exports){
(function() {
var XMLCData, XMLNode, create,
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;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLCData = (function(superClass) {
extend(XMLCData, superClass);
function XMLCData(parent, text) {
XMLCData.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing CDATA text");
}
this.text = this.stringify.cdata(text);
}
XMLCData.prototype.clone = function() {
return create(XMLCData.prototype, this);
};
XMLCData.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<![CDATA[' + this.text + ']]>';
if (pretty) {
r += newline;
}
return r;
};
return XMLCData;
})(XMLNode);
}).call(this);
},{"./XMLNode":77,"lodash/object/create":125}],69:[function(require,module,exports){
(function() {
var XMLComment, XMLNode, create,
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;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLComment = (function(superClass) {
extend(XMLComment, superClass);
function XMLComment(parent, text) {
XMLComment.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing comment text");
}
this.text = this.stringify.comment(text);
}
XMLComment.prototype.clone = function() {
return create(XMLComment.prototype, this);
};
XMLComment.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!-- ' + this.text + ' -->';
if (pretty) {
r += newline;
}
return r;
};
return XMLComment;
})(XMLNode);
}).call(this);
},{"./XMLNode":77,"lodash/object/create":125}],70:[function(require,module,exports){
(function() {
var XMLDTDAttList, create;
create = require('lodash/object/create');
module.exports = XMLDTDAttList = (function() {
function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
this.stringify = parent.stringify;
if (elementName == null) {
throw new Error("Missing DTD element name");
}
if (attributeName == null) {
throw new Error("Missing DTD attribute name");
}
if (!attributeType) {
throw new Error("Missing DTD attribute type");
}
if (!defaultValueType) {
throw new Error("Missing DTD attribute default");
}
if (defaultValueType.indexOf('#') !== 0) {
defaultValueType = '#' + defaultValueType;
}
if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT");
}
if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
throw new Error("Default value only applies to #FIXED or #DEFAULT");
}
this.elementName = this.stringify.eleName(elementName);
this.attributeName = this.stringify.attName(attributeName);
this.attributeType = this.stringify.dtdAttType(attributeType);
this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
this.defaultValueType = defaultValueType;
}
XMLDTDAttList.prototype.clone = function() {
return create(XMLDTDAttList.prototype, this);
};
XMLDTDAttList.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ATTLIST ' + this.elementName + ' ' + this.attributeName + ' ' + this.attributeType;
if (this.defaultValueType !== '#DEFAULT') {
r += ' ' + this.defaultValueType;
}
if (this.defaultValue) {
r += ' "' + this.defaultValue + '"';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDAttList;
})();
}).call(this);
},{"lodash/object/create":125}],71:[function(require,module,exports){
(function() {
var XMLDTDElement, create, isArray;
create = require('lodash/object/create');
isArray = require('lodash/lang/isArray');
module.exports = XMLDTDElement = (function() {
function XMLDTDElement(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing DTD element name");
}
if (!value) {
value = '(#PCDATA)';
}
if (isArray(value)) {
value = '(' + value.join(',') + ')';
}
this.name = this.stringify.eleName(name);
this.value = this.stringify.dtdElementValue(value);
}
XMLDTDElement.prototype.clone = function() {
return create(XMLDTDElement.prototype, this);
};
XMLDTDElement.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ELEMENT ' + this.name + ' ' + this.value + '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDElement;
})();
}).call(this);
},{"lodash/lang/isArray":117,"lodash/object/create":125}],72:[function(require,module,exports){
(function() {
var XMLDTDEntity, create, isObject;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
module.exports = XMLDTDEntity = (function() {
function XMLDTDEntity(parent, pe, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing entity name");
}
if (value == null) {
throw new Error("Missing entity value");
}
this.pe = !!pe;
this.name = this.stringify.eleName(name);
if (!isObject(value)) {
this.value = this.stringify.dtdEntityValue(value);
} else {
if (!value.pubID && !value.sysID) {
throw new Error("Public and/or system identifiers are required for an external entity");
}
if (value.pubID && !value.sysID) {
throw new Error("System identifier is required for a public external entity");
}
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
if (value.nData != null) {
this.nData = this.stringify.dtdNData(value.nData);
}
if (this.pe && this.nData) {
throw new Error("Notation declaration is not allowed in a parameter entity");
}
}
}
XMLDTDEntity.prototype.clone = function() {
return create(XMLDTDEntity.prototype, this);
};
XMLDTDEntity.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ENTITY';
if (this.pe) {
r += ' %';
}
r += ' ' + this.name;
if (this.value) {
r += ' "' + this.value + '"';
} else {
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
if (this.nData) {
r += ' NDATA ' + this.nData;
}
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDEntity;
})();
}).call(this);
},{"lodash/lang/isObject":121,"lodash/object/create":125}],73:[function(require,module,exports){
(function() {
var XMLDTDNotation, create;
create = require('lodash/object/create');
module.exports = XMLDTDNotation = (function() {
function XMLDTDNotation(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing notation name");
}
if (!value.pubID && !value.sysID) {
throw new Error("Public or system identifiers are required for an external entity");
}
this.name = this.stringify.eleName(name);
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
}
XMLDTDNotation.prototype.clone = function() {
return create(XMLDTDNotation.prototype, this);
};
XMLDTDNotation.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!NOTATION ' + this.name;
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.pubID) {
r += ' PUBLIC "' + this.pubID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDNotation;
})();
}).call(this);
},{"lodash/object/create":125}],74:[function(require,module,exports){
(function() {
var XMLDeclaration, XMLNode, create, isObject,
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;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
XMLNode = require('./XMLNode');
module.exports = XMLDeclaration = (function(superClass) {
extend(XMLDeclaration, superClass);
function XMLDeclaration(parent, version, encoding, standalone) {
var ref;
XMLDeclaration.__super__.constructor.call(this, parent);
if (isObject(version)) {
ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
}
if (!version) {
version = '1.0';
}
if (version != null) {
this.version = this.stringify.xmlVersion(version);
}
if (encoding != null) {
this.encoding = this.stringify.xmlEncoding(encoding);
}
if (standalone != null) {
this.standalone = this.stringify.xmlStandalone(standalone);
}
}
XMLDeclaration.prototype.clone = function() {
return create(XMLDeclaration.prototype, this);
};
XMLDeclaration.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<?xml';
if (this.version != null) {
r += ' version="' + this.version + '"';
}
if (this.encoding != null) {
r += ' encoding="' + this.encoding + '"';
}
if (this.standalone != null) {
r += ' standalone="' + this.standalone + '"';
}
r += '?>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDeclaration;
})(XMLNode);
}).call(this);
},{"./XMLNode":77,"lodash/lang/isObject":121,"lodash/object/create":125}],75:[function(require,module,exports){
(function() {
var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLProcessingInstruction, create, isObject;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLDTDAttList = require('./XMLDTDAttList');
XMLDTDEntity = require('./XMLDTDEntity');
XMLDTDElement = require('./XMLDTDElement');
XMLDTDNotation = require('./XMLDTDNotation');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
module.exports = XMLDocType = (function() {
function XMLDocType(parent, pubID, sysID) {
var ref, ref1;
this.documentObject = parent;
this.stringify = this.documentObject.stringify;
this.children = [];
if (isObject(pubID)) {
ref = pubID, pubID = ref.pubID, sysID = ref.sysID;
}
if (sysID == null) {
ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1];
}
if (pubID != null) {
this.pubID = this.stringify.dtdPubID(pubID);
}
if (sysID != null) {
this.sysID = this.stringify.dtdSysID(sysID);
}
}
XMLDocType.prototype.clone = function() {
return create(XMLDocType.prototype, this);
};
XMLDocType.prototype.element = function(name, value) {
var child;
child = new XMLDTDElement(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
var child;
child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
this.children.push(child);
return this;
};
XMLDocType.prototype.entity = function(name, value) {
var child;
child = new XMLDTDEntity(this, false, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.pEntity = function(name, value) {
var child;
child = new XMLDTDEntity(this, true, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.notation = function(name, value) {
var child;
child = new XMLDTDNotation(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.cdata = function(value) {
var child;
child = new XMLCData(this, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.comment = function(value) {
var child;
child = new XMLComment(this, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.instruction = function(target, value) {
var child;
child = new XMLProcessingInstruction(this, target, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.root = function() {
return this.documentObject.root();
};
XMLDocType.prototype.document = function() {
return this.documentObject;
};
XMLDocType.prototype.toString = function(options, level) {
var child, i, indent, len, newline, offset, pretty, r, ref, ref1, ref2, ref3, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!DOCTYPE ' + this.root().name;
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
if (this.children.length > 0) {
r += ' [';
if (pretty) {
r += newline;
}
ref3 = this.children;
for (i = 0, len = ref3.length; i < len; i++) {
child = ref3[i];
r += child.toString(options, level + 1);
}
r += ']';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
XMLDocType.prototype.ele = function(name, value) {
return this.element(name, value);
};
XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
};
XMLDocType.prototype.ent = function(name, value) {
return this.entity(name, value);
};
XMLDocType.prototype.pent = function(name, value) {
return this.pEntity(name, value);
};
XMLDocType.prototype.not = function(name, value) {
return this.notation(name, value);
};
XMLDocType.prototype.dat = function(value) {
return this.cdata(value);
};
XMLDocType.prototype.com = function(value) {
return this.comment(value);
};
XMLDocType.prototype.ins = function(target, value) {
return this.instruction(target, value);
};
XMLDocType.prototype.up = function() {
return this.root();
};
XMLDocType.prototype.doc = function() {
return this.document();
};
return XMLDocType;
})();
}).call(this);
},{"./XMLCData":68,"./XMLComment":69,"./XMLDTDAttList":70,"./XMLDTDElement":71,"./XMLDTDEntity":72,"./XMLDTDNotation":73,"./XMLProcessingInstruction":78,"lodash/lang/isObject":121,"lodash/object/create":125}],76:[function(require,module,exports){
(function() {
var XMLAttribute, XMLElement, XMLNode, XMLProcessingInstruction, create, every, isArray, isFunction, isObject,
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;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
isArray = require('lodash/lang/isArray');
isFunction = require('lodash/lang/isFunction');
every = require('lodash/collection/every');
XMLNode = require('./XMLNode');
XMLAttribute = require('./XMLAttribute');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
module.exports = XMLElement = (function(superClass) {
extend(XMLElement, superClass);
function XMLElement(parent, name, attributes) {
XMLElement.__super__.constructor.call(this, parent);
if (name == null) {
throw new Error("Missing element name");
}
this.name = this.stringify.eleName(name);
this.children = [];
this.instructions = [];
this.attributes = {};
if (attributes != null) {
this.attribute(attributes);
}
}
XMLElement.prototype.clone = function() {
var att, attName, clonedSelf, i, len, pi, ref, ref1;
clonedSelf = create(XMLElement.prototype, this);
if (clonedSelf.isRoot) {
clonedSelf.documentObject = null;
}
clonedSelf.attributes = {};
ref = this.attributes;
for (attName in ref) {
if (!hasProp.call(ref, attName)) continue;
att = ref[attName];
clonedSelf.attributes[attName] = att.clone();
}
clonedSelf.instructions = [];
ref1 = this.instructions;
for (i = 0, len = ref1.length; i < len; i++) {
pi = ref1[i];
clonedSelf.instructions.push(pi.clone());
}
clonedSelf.children = [];
this.children.forEach(function(child) {
var clonedChild;
clonedChild = child.clone();
clonedChild.parent = clonedSelf;
return clonedSelf.children.push(clonedChild);
});
return clonedSelf;
};
XMLElement.prototype.attribute = function(name, value) {
var attName, attValue;
if (name != null) {
name = name.valueOf();
}
if (isObject(name)) {
for (attName in name) {
if (!hasProp.call(name, attName)) continue;
attValue = name[attName];
this.attribute(attName, attValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
if (!this.options.skipNullAttributes || (value != null)) {
this.attributes[name] = new XMLAttribute(this, name, value);
}
}
return this;
};
XMLElement.prototype.removeAttribute = function(name) {
var attName, i, len;
if (name == null) {
throw new Error("Missing attribute name");
}
name = name.valueOf();
if (isArray(name)) {
for (i = 0, len = name.length; i < len; i++) {
attName = name[i];
delete this.attributes[attName];
}
} else {
delete this.attributes[name];
}
return this;
};
XMLElement.prototype.instruction = function(target, value) {
var i, insTarget, insValue, instruction, len;
if (target != null) {
target = target.valueOf();
}
if (value != null) {
value = value.valueOf();
}
if (isArray(target)) {
for (i = 0, len = target.length; i < len; i++) {
insTarget = target[i];
this.instruction(insTarget);
}
} else if (isObject(target)) {
for (insTarget in target) {
if (!hasProp.call(target, insTarget)) continue;
insValue = target[insTarget];
this.instruction(insTarget, insValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
instruction = new XMLProcessingInstruction(this, target, value);
this.instructions.push(instruction);
}
return this;
};
XMLElement.prototype.toString = function(options, level) {
var att, child, i, indent, instruction, j, len, len1, name, newline, offset, pretty, r, ref, ref1, ref2, ref3, ref4, ref5, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
ref3 = this.instructions;
for (i = 0, len = ref3.length; i < len; i++) {
instruction = ref3[i];
r += instruction.toString(options, level + 1);
}
if (pretty) {
r += space;
}
r += '<' + this.name;
ref4 = this.attributes;
for (name in ref4) {
if (!hasProp.call(ref4, name)) continue;
att = ref4[name];
r += att.toString(options);
}
if (this.children.length === 0 || every(this.children, function(e) {
return e.value === '';
})) {
r += '/>';
if (pretty) {
r += newline;
}
} else if (pretty && this.children.length === 1 && (this.children[0].value != null)) {
r += '>';
r += this.children[0].value;
r += '</' + this.name + '>';
r += newline;
} else {
r += '>';
if (pretty) {
r += newline;
}
ref5 = this.children;
for (j = 0, len1 = ref5.length; j < len1; j++) {
child = ref5[j];
r += child.toString(options, level + 1);
}
if (pretty) {
r += space;
}
r += '</' + this.name + '>';
if (pretty) {
r += newline;
}
}
return r;
};
XMLElement.prototype.att = function(name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.ins = function(target, value) {
return this.instruction(target, value);
};
XMLElement.prototype.a = function(name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.i = function(target, value) {
return this.instruction(target, value);
};
return XMLElement;
})(XMLNode);
}).call(this);
},{"./XMLAttribute":66,"./XMLNode":77,"./XMLProcessingInstruction":78,"lodash/collection/every":83,"lodash/lang/isArray":117,"lodash/lang/isFunction":119,"lodash/lang/isObject":121,"lodash/object/create":125}],77:[function(require,module,exports){
(function() {
var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLRaw, XMLText, isArray, isEmpty, isFunction, isObject,
hasProp = {}.hasOwnProperty;
isObject = require('lodash/lang/isObject');
isArray = require('lodash/lang/isArray');
isFunction = require('lodash/lang/isFunction');
isEmpty = require('lodash/lang/isEmpty');
XMLElement = null;
XMLCData = null;
XMLComment = null;
XMLDeclaration = null;
XMLDocType = null;
XMLRaw = null;
XMLText = null;
module.exports = XMLNode = (function() {
function XMLNode(parent) {
this.parent = parent;
this.options = this.parent.options;
this.stringify = this.parent.stringify;
if (XMLElement === null) {
XMLElement = require('./XMLElement');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLRaw = require('./XMLRaw');
XMLText = require('./XMLText');
}
}
XMLNode.prototype.clone = function() {
throw new Error("Cannot clone generic XMLNode");
};
XMLNode.prototype.element = function(name, attributes, text) {
var item, j, key, lastChild, len, ref, val;
lastChild = null;
if (attributes == null) {
attributes = {};
}
attributes = attributes.valueOf();
if (!isObject(attributes)) {
ref = [attributes, text], text = ref[0], attributes = ref[1];
}
if (name != null) {
name = name.valueOf();
}
if (isArray(name)) {
for (j = 0, len = name.length; j < len; j++) {
item = name[j];
lastChild = this.element(item);
}
} else if (isFunction(name)) {
lastChild = this.element(name.apply());
} else if (isObject(name)) {
for (key in name) {
if (!hasProp.call(name, key)) continue;
val = name[key];
if (isFunction(val)) {
val = val.apply();
}
if ((isObject(val)) && (isEmpty(val))) {
val = null;
}
if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
} else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && key.indexOf(this.stringify.convertPIKey) === 0) {
lastChild = this.instruction(key.substr(this.stringify.convertPIKey.length), val);
} else if (isObject(val)) {
if (!this.options.ignoreDecorators && this.stringify.convertListKey && key.indexOf(this.stringify.convertListKey) === 0 && isArray(val)) {
lastChild = this.element(val);
} else {
lastChild = this.element(key);
lastChild.element(val);
}
} else {
lastChild = this.element(key, val);
}
}
} else {
if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
lastChild = this.text(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
lastChild = this.cdata(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
lastChild = this.comment(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
lastChild = this.raw(text);
} else {
lastChild = this.node(name, attributes, text);
}
}
if (lastChild == null) {
throw new Error("Could not create any elements with: " + name);
}
return lastChild;
};
XMLNode.prototype.insertBefore = function(name, attributes, text) {
var child, i, removed;
if (this.isRoot) {
throw new Error("Cannot insert elements at root level");
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
};
XMLNode.prototype.insertAfter = function(name, attributes, text) {
var child, i, removed;
if (this.isRoot) {
throw new Error("Cannot insert elements at root level");
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i + 1);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
};
XMLNode.prototype.remove = function() {
var i, ref;
if (this.isRoot) {
throw new Error("Cannot remove the root element");
}
i = this.parent.children.indexOf(this);
[].splice.apply(this.parent.children, [i, i - i + 1].concat(ref = [])), ref;
return this.parent;
};
XMLNode.prototype.node = function(name, attributes, text) {
var child, ref;
if (name != null) {
name = name.valueOf();
}
if (attributes == null) {
attributes = {};
}
attributes = attributes.valueOf();
if (!isObject(attributes)) {
ref = [attributes, text], text = ref[0], attributes = ref[1];
}
child = new XMLElement(this, name, attributes);
if (text != null) {
child.text(text);
}
this.children.push(child);
return child;
};
XMLNode.prototype.text = function(value) {
var child;
child = new XMLText(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.cdata = function(value) {
var child;
child = new XMLCData(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.comment = function(value) {
var child;
child = new XMLComment(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.raw = function(value) {
var child;
child = new XMLRaw(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.declaration = function(version, encoding, standalone) {
var doc, xmldec;
doc = this.document();
xmldec = new XMLDeclaration(doc, version, encoding, standalone);
doc.xmldec = xmldec;
return doc.root();
};
XMLNode.prototype.doctype = function(pubID, sysID) {
var doc, doctype;
doc = this.document();
doctype = new XMLDocType(doc, pubID, sysID);
doc.doctype = doctype;
return doctype;
};
XMLNode.prototype.up = function() {
if (this.isRoot) {
throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
}
return this.parent;
};
XMLNode.prototype.root = function() {
var child;
if (this.isRoot) {
return this;
}
child = this.parent;
while (!child.isRoot) {
child = child.parent;
}
return child;
};
XMLNode.prototype.document = function() {
return this.root().documentObject;
};
XMLNode.prototype.end = function(options) {
return this.document().toString(options);
};
XMLNode.prototype.prev = function() {
var i;
if (this.isRoot) {
throw new Error("Root node has no siblings");
}
i = this.parent.children.indexOf(this);
if (i < 1) {
throw new Error("Already at the first node");
}
return this.parent.children[i - 1];
};
XMLNode.prototype.next = function() {
var i;
if (this.isRoot) {
throw new Error("Root node has no siblings");
}
i = this.parent.children.indexOf(this);
if (i === -1 || i === this.parent.children.length - 1) {
throw new Error("Already at the last node");
}
return this.parent.children[i + 1];
};
XMLNode.prototype.importXMLBuilder = function(xmlbuilder) {
var clonedRoot;
clonedRoot = xmlbuilder.root().clone();
clonedRoot.parent = this;
clonedRoot.isRoot = false;
this.children.push(clonedRoot);
return this;
};
XMLNode.prototype.ele = function(name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.nod = function(name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.txt = function(value) {
return this.text(value);
};
XMLNode.prototype.dat = function(value) {
return this.cdata(value);
};
XMLNode.prototype.com = function(value) {
return this.comment(value);
};
XMLNode.prototype.doc = function() {
return this.document();
};
XMLNode.prototype.dec = function(version, encoding, standalone) {
return this.declaration(version, encoding, standalone);
};
XMLNode.prototype.dtd = function(pubID, sysID) {
return this.doctype(pubID, sysID);
};
XMLNode.prototype.e = function(name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.n = function(name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.t = function(value) {
return this.text(value);
};
XMLNode.prototype.d = function(value) {
return this.cdata(value);
};
XMLNode.prototype.c = function(value) {
return this.comment(value);
};
XMLNode.prototype.r = function(value) {
return this.raw(value);
};
XMLNode.prototype.u = function() {
return this.up();
};
return XMLNode;
})();
}).call(this);
},{"./XMLCData":68,"./XMLComment":69,"./XMLDeclaration":74,"./XMLDocType":75,"./XMLElement":76,"./XMLRaw":79,"./XMLText":81,"lodash/lang/isArray":117,"lodash/lang/isEmpty":118,"lodash/lang/isFunction":119,"lodash/lang/isObject":121}],78:[function(require,module,exports){
(function() {
var XMLProcessingInstruction, create;
create = require('lodash/object/create');
module.exports = XMLProcessingInstruction = (function() {
function XMLProcessingInstruction(parent, target, value) {
this.stringify = parent.stringify;
if (target == null) {
throw new Error("Missing instruction target");
}
this.target = this.stringify.insTarget(target);
if (value) {
this.value = this.stringify.insValue(value);
}
}
XMLProcessingInstruction.prototype.clone = function() {
return create(XMLProcessingInstruction.prototype, this);
};
XMLProcessingInstruction.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<?';
r += this.target;
if (this.value) {
r += ' ' + this.value;
}
r += '?>';
if (pretty) {
r += newline;
}
return r;
};
return XMLProcessingInstruction;
})();
}).call(this);
},{"lodash/object/create":125}],79:[function(require,module,exports){
(function() {
var XMLNode, XMLRaw, create,
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;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLRaw = (function(superClass) {
extend(XMLRaw, superClass);
function XMLRaw(parent, text) {
XMLRaw.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing raw text");
}
this.value = this.stringify.raw(text);
}
XMLRaw.prototype.clone = function() {
return create(XMLRaw.prototype, this);
};
XMLRaw.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += this.value;
if (pretty) {
r += newline;
}
return r;
};
return XMLRaw;
})(XMLNode);
}).call(this);
},{"./XMLNode":77,"lodash/object/create":125}],80:[function(require,module,exports){
(function() {
var XMLStringifier,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
hasProp = {}.hasOwnProperty;
module.exports = XMLStringifier = (function() {
function XMLStringifier(options) {
this.assertLegalChar = bind(this.assertLegalChar, this);
var key, ref, value;
this.allowSurrogateChars = options != null ? options.allowSurrogateChars : void 0;
ref = (options != null ? options.stringify : void 0) || {};
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this[key] = value;
}
}
XMLStringifier.prototype.eleName = function(val) {
val = '' + val || '';
return this.assertLegalChar(val);
};
XMLStringifier.prototype.eleText = function(val) {
val = '' + val || '';
return this.assertLegalChar(this.elEscape(val));
};
XMLStringifier.prototype.cdata = function(val) {
val = '' + val || '';
if (val.match(/]]>/)) {
throw new Error("Invalid CDATA text: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.comment = function(val) {
val = '' + val || '';
if (val.match(/--/)) {
throw new Error("Comment text cannot contain double-hypen: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.raw = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.attName = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.attValue = function(val) {
val = '' + val || '';
return this.attEscape(val);
};
XMLStringifier.prototype.insTarget = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.insValue = function(val) {
val = '' + val || '';
if (val.match(/\?>/)) {
throw new Error("Invalid processing instruction value: " + val);
}
return val;
};
XMLStringifier.prototype.xmlVersion = function(val) {
val = '' + val || '';
if (!val.match(/1\.[0-9]+/)) {
throw new Error("Invalid version number: " + val);
}
return val;
};
XMLStringifier.prototype.xmlEncoding = function(val) {
val = '' + val || '';
if (!val.match(/[A-Za-z](?:[A-Za-z0-9._-]|-)*/)) {
throw new Error("Invalid encoding: " + val);
}
return val;
};
XMLStringifier.prototype.xmlStandalone = function(val) {
if (val) {
return "yes";
} else {
return "no";
}
};
XMLStringifier.prototype.dtdPubID = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdSysID = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdElementValue = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdAttType = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdAttDefault = function(val) {
if (val != null) {
return '' + val || '';
} else {
return val;
}
};
XMLStringifier.prototype.dtdEntityValue = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdNData = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.convertAttKey = '@';
XMLStringifier.prototype.convertPIKey = '?';
XMLStringifier.prototype.convertTextKey = '#text';
XMLStringifier.prototype.convertCDataKey = '#cdata';
XMLStringifier.prototype.convertCommentKey = '#comment';
XMLStringifier.prototype.convertRawKey = '#raw';
XMLStringifier.prototype.convertListKey = '#list';
XMLStringifier.prototype.assertLegalChar = function(str) {
var chars, chr;
if (this.allowSurrogateChars) {
chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]/;
} else {
chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/;
}
chr = str.match(chars);
if (chr) {
throw new Error("Invalid character (" + chr + ") in string: " + str + " at index " + chr.index);
}
return str;
};
XMLStringifier.prototype.elEscape = function(str) {
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
};
XMLStringifier.prototype.attEscape = function(str) {
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
};
return XMLStringifier;
})();
}).call(this);
},{}],81:[function(require,module,exports){
(function() {
var XMLNode, XMLText, create,
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;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLText = (function(superClass) {
extend(XMLText, superClass);
function XMLText(parent, text) {
XMLText.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing element text");
}
this.value = this.stringify.eleText(text);
}
XMLText.prototype.clone = function() {
return create(XMLText.prototype, this);
};
XMLText.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += this.value;
if (pretty) {
r += newline;
}
return r;
};
return XMLText;
})(XMLNode);
}).call(this);
},{"./XMLNode":77,"lodash/object/create":125}],82:[function(require,module,exports){
(function() {
var XMLBuilder, assign;
assign = require('lodash/object/assign');
XMLBuilder = require('./XMLBuilder');
module.exports.create = function(name, xmldec, doctype, options) {
options = assign({}, xmldec, doctype, options);
return new XMLBuilder(name, options).root();
};
}).call(this);
},{"./XMLBuilder":67,"lodash/object/assign":124}],83:[function(require,module,exports){
var arrayEvery = require('../internal/arrayEvery'),
baseCallback = require('../internal/baseCallback'),
baseEvery = require('../internal/baseEvery'),
isArray = require('../lang/isArray');
function every(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
predicate = baseCallback(predicate, thisArg, 3);
}
return func(collection, predicate);
}
module.exports = every;
},{"../internal/arrayEvery":84,"../internal/baseCallback":86,"../internal/baseEvery":90,"../lang/isArray":117}],84:[function(require,module,exports){
function arrayEvery(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
module.exports = arrayEvery;
},{}],85:[function(require,module,exports){
var baseCopy = require('./baseCopy'),
keys = require('../object/keys');
function baseAssign(object, source, customizer) {
var props = keys(source);
if (!customizer) {
return baseCopy(source, object, props);
}
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index],
value = object[key],
result = customizer(value, source[key], key, object, source);
if ((result === result ? (result !== value) : (value === value)) ||
(typeof value == 'undefined' && !(key in object))) {
object[key] = result;
}
}
return object;
}
module.exports = baseAssign;
},{"../object/keys":126,"./baseCopy":87}],86:[function(require,module,exports){
var baseMatches = require('./baseMatches'),
baseMatchesProperty = require('./baseMatchesProperty'),
baseProperty = require('./baseProperty'),
bindCallback = require('./bindCallback'),
identity = require('../utility/identity'),
isBindable = require('./isBindable');
function baseCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function') {
return (typeof thisArg != 'undefined' && isBindable(func))
? bindCallback(func, thisArg, argCount)
: func;
}
if (func == null) {
return identity;
}
if (type == 'object') {
return baseMatches(func);
}
return typeof thisArg == 'undefined'
? baseProperty(func + '')
: baseMatchesProperty(func + '', thisArg);
}
module.exports = baseCallback;
},{"../utility/identity":130,"./baseMatches":97,"./baseMatchesProperty":98,"./baseProperty":99,"./bindCallback":102,"./isBindable":107}],87:[function(require,module,exports){
function baseCopy(source, object, props) {
if (!props) {
props = object;
object = {};
}
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],88:[function(require,module,exports){
(function (global){
var isObject = require('../lang/isObject');
var baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || global.Object();
};
}());
module.exports = baseCreate;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../lang/isObject":121}],89:[function(require,module,exports){
var baseForOwn = require('./baseForOwn'),
isLength = require('./isLength'),
toObject = require('./toObject');
function baseEach(collection, iteratee) {
var length = collection ? collection.length : 0;
if (!isLength(length)) {
return baseForOwn(collection, iteratee);
}
var index = -1,
iterable = toObject(collection);
while (++index < length) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
}
module.exports = baseEach;
},{"./baseForOwn":92,"./isLength":110,"./toObject":115}],90:[function(require,module,exports){
var baseEach = require('./baseEach');
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
module.exports = baseEvery;
},{"./baseEach":89}],91:[function(require,module,exports){
var toObject = require('./toObject');
function baseFor(object, iteratee, keysFunc) {
var index = -1,
iterable = toObject(object),
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
}
module.exports = baseFor;
},{"./toObject":115}],92:[function(require,module,exports){
var baseFor = require('./baseFor'),
keys = require('../object/keys');
function baseForOwn(object, iteratee) {
return baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
},{"../object/keys":126,"./baseFor":91}],93:[function(require,module,exports){
var baseIsEqualDeep = require('./baseIsEqualDeep');
function baseIsEqual(value, other, customizer, isWhere, stackA, stackB) {
if (value === other) {
return value !== 0 || (1 / value == 1 / other);
}
var valType = typeof value,
othType = typeof other;
if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') ||
value == null || other == null) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isWhere, stackA, stackB);
}
module.exports = baseIsEqual;
},{"./baseIsEqualDeep":94}],94:[function(require,module,exports){
var equalArrays = require('./equalArrays'),
equalByTag = require('./equalByTag'),
equalObjects = require('./equalObjects'),
isArray = require('../lang/isArray'),
isTypedArray = require('../lang/isTypedArray');
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
var objToString = objectProto.toString;
function baseIsEqualDeep(object, other, equalFunc, customizer, isWhere, stackA, stackB) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = objToString.call(object);
if (objTag == argsTag) {
objTag = objectTag;
} else if (objTag != objectTag) {
objIsArr = isTypedArray(object);
}
}
if (!othIsArr) {
othTag = objToString.call(other);
if (othTag == argsTag) {
othTag = objectTag;
} else if (othTag != objectTag) {
othIsArr = isTypedArray(other);
}
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
return equalByTag(object, other, objTag);
}
var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (valWrapped || othWrapped) {
return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isWhere, stackA, stackB);
}
if (!isSameTag) {
return false;
}
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == object) {
return stackB[length] == other;
}
}
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isWhere, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
module.exports = baseIsEqualDeep;
},{"../lang/isArray":117,"../lang/isTypedArray":123,"./equalArrays":104,"./equalByTag":105,"./equalObjects":106}],95:[function(require,module,exports){
function baseIsFunction(value) {
return typeof value == 'function' || false;
}
module.exports = baseIsFunction;
},{}],96:[function(require,module,exports){
var baseIsEqual = require('./baseIsEqual');
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function baseIsMatch(object, props, values, strictCompareFlags, customizer) {
var length = props.length;
if (object == null) {
return !length;
}
var index = -1,
noCustomizer = !customizer;
while (++index < length) {
if ((noCustomizer && strictCompareFlags[index])
? values[index] !== object[props[index]]
: !hasOwnProperty.call(object, props[index])
) {
return false;
}
}
index = -1;
while (++index < length) {
var key = props[index];
if (noCustomizer && strictCompareFlags[index]) {
var result = hasOwnProperty.call(object, key);
} else {
var objValue = object[key],
srcValue = values[index];
result = customizer ? customizer(objValue, srcValue, key) : undefined;
if (typeof result == 'undefined') {
result = baseIsEqual(srcValue, objValue, customizer, true);
}
}
if (!result) {
return false;
}
}
return true;
}
module.exports = baseIsMatch;
},{"./baseIsEqual":93}],97:[function(require,module,exports){
var baseIsMatch = require('./baseIsMatch'),
isStrictComparable = require('./isStrictComparable'),
keys = require('../object/keys');
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function baseMatches(source) {
var props = keys(source),
length = props.length;
if (length == 1) {
var key = props[0],
value = source[key];
if (isStrictComparable(value)) {
return function(object) {
return object != null && object[key] === value && hasOwnProperty.call(object, key);
};
}
}
var values = Array(length),
strictCompareFlags = Array(length);
while (length--) {
value = source[props[length]];
values[length] = value;
strictCompareFlags[length] = isStrictComparable(value);
}
return function(object) {
return baseIsMatch(object, props, values, strictCompareFlags);
};
}
module.exports = baseMatches;
},{"../object/keys":126,"./baseIsMatch":96,"./isStrictComparable":112}],98:[function(require,module,exports){
var baseIsEqual = require('./baseIsEqual'),
isStrictComparable = require('./isStrictComparable');
function baseMatchesProperty(key, value) {
if (isStrictComparable(value)) {
return function(object) {
return object != null && object[key] === value;
};
}
return function(object) {
return object != null && baseIsEqual(value, object[key], null, true);
};
}
module.exports = baseMatchesProperty;
},{"./baseIsEqual":93,"./isStrictComparable":112}],99:[function(require,module,exports){
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
},{}],100:[function(require,module,exports){
var identity = require('../utility/identity'),
metaMap = require('./metaMap');
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
},{"../utility/identity":130,"./metaMap":113}],101:[function(require,module,exports){
function baseToString(value) {
if (typeof value == 'string') {
return value;
}
return value == null ? '' : (value + '');
}
module.exports = baseToString;
},{}],102:[function(require,module,exports){
var identity = require('../utility/identity');
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (typeof thisArg == 'undefined') {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
module.exports = bindCallback;
},{"../utility/identity":130}],103:[function(require,module,exports){
var bindCallback = require('./bindCallback'),
isIterateeCall = require('./isIterateeCall');
function createAssigner(assigner) {
return function() {
var args = arguments,
length = args.length,
object = args[0];
if (length < 2 || object == null) {
return object;
}
var customizer = args[length - 2],
thisArg = args[length - 1],
guard = args[3];
if (length > 3 && typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = (length > 2 && typeof thisArg == 'function') ? thisArg : null;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(args[1], args[2], guard)) {
customizer = length == 3 ? null : customizer;
length = 2;
}
var index = 0;
while (++index < length) {
var source = args[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
};
}
module.exports = createAssigner;
},{"./bindCallback":102,"./isIterateeCall":109}],104:[function(require,module,exports){
function equalArrays(array, other, equalFunc, customizer, isWhere, stackA, stackB) {
var index = -1,
arrLength = array.length,
othLength = other.length,
result = true;
if (arrLength != othLength && !(isWhere && othLength > arrLength)) {
return false;
}
while (result && ++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
result = undefined;
if (customizer) {
result = isWhere
? customizer(othValue, arrValue, index)
: customizer(arrValue, othValue, index);
}
if (typeof result == 'undefined') {
if (isWhere) {
var othIndex = othLength;
while (othIndex--) {
othValue = other[othIndex];
result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB);
if (result) {
break;
}
}
} else {
result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB);
}
}
}
return !!result;
}
module.exports = equalArrays;
},{}],105:[function(require,module,exports){
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
return +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
return (object != +object)
? other != +other
: (object == 0 ? ((1 / object) == (1 / other)) : object == +other);
case regexpTag:
case stringTag:
return object == (other + '');
}
return false;
}
module.exports = equalByTag;
},{}],106:[function(require,module,exports){
var keys = require('../object/keys');
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function equalObjects(object, other, equalFunc, customizer, isWhere, stackA, stackB) {
var objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isWhere) {
return false;
}
var hasCtor,
index = -1;
while (++index < objLength) {
var key = objProps[index],
result = hasOwnProperty.call(other, key);
if (result) {
var objValue = object[key],
othValue = other[key];
result = undefined;
if (customizer) {
result = isWhere
? customizer(othValue, objValue, key)
: customizer(objValue, othValue, key);
}
if (typeof result == 'undefined') {
result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isWhere, stackA, stackB);
}
}
if (!result) {
return false;
}
hasCtor || (hasCtor = key == 'constructor');
}
if (!hasCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
return false;
}
}
return true;
}
module.exports = equalObjects;
},{"../object/keys":126}],107:[function(require,module,exports){
var baseSetData = require('./baseSetData'),
isNative = require('../lang/isNative'),
support = require('../support');
var reFuncName = /^\s*function[ \n\r\t]+\w/;
var reThis = /\bthis\b/;
var fnToString = Function.prototype.toString;
function isBindable(func) {
var result = !(support.funcNames ? func.name : support.funcDecomp);
if (!result) {
var source = fnToString.call(func);
if (!support.funcNames) {
result = !reFuncName.test(source);
}
if (!result) {
result = reThis.test(source) || isNative(func);
baseSetData(func, result);
}
}
return result;
}
module.exports = isBindable;
},{"../lang/isNative":120,"../support":129,"./baseSetData":100}],108:[function(require,module,exports){
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
function isIndex(value, length) {
value = +value;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = isIndex;
},{}],109:[function(require,module,exports){
var isIndex = require('./isIndex'),
isLength = require('./isLength'),
isObject = require('../lang/isObject');
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number') {
var length = object.length,
prereq = isLength(length) && isIndex(index, length);
} else {
prereq = type == 'string' && index in object;
}
if (prereq) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
module.exports = isIterateeCall;
},{"../lang/isObject":121,"./isIndex":108,"./isLength":110}],110:[function(require,module,exports){
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
},{}],111:[function(require,module,exports){
function isObjectLike(value) {
return (value && typeof value == 'object') || false;
}
module.exports = isObjectLike;
},{}],112:[function(require,module,exports){
var isObject = require('../lang/isObject');
function isStrictComparable(value) {
return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value));
}
module.exports = isStrictComparable;
},{"../lang/isObject":121}],113:[function(require,module,exports){
(function (global){
var isNative = require('../lang/isNative');
var WeakMap = isNative(WeakMap = global.WeakMap) && WeakMap;
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../lang/isNative":120}],114:[function(require,module,exports){
var isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isIndex = require('./isIndex'),
isLength = require('./isLength'),
keysIn = require('../object/keysIn'),
support = require('../support');
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = length && isLength(length) &&
(isArray(object) || (support.nonEnumArgs && isArguments(object)));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
module.exports = shimKeys;
},{"../lang/isArguments":116,"../lang/isArray":117,"../object/keysIn":127,"../support":129,"./isIndex":108,"./isLength":110}],115:[function(require,module,exports){
var isObject = require('../lang/isObject');
function toObject(value) {
return isObject(value) ? value : Object(value);
}
module.exports = toObject;
},{"../lang/isObject":121}],116:[function(require,module,exports){
var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
var argsTag = '[object Arguments]';
var objectProto = Object.prototype;
var objToString = objectProto.toString;
function isArguments(value) {
var length = isObjectLike(value) ? value.length : undefined;
return (isLength(length) && objToString.call(value) == argsTag) || false;
}
module.exports = isArguments;
},{"../internal/isLength":110,"../internal/isObjectLike":111}],117:[function(require,module,exports){
var isLength = require('../internal/isLength'),
isNative = require('./isNative'),
isObjectLike = require('../internal/isObjectLike');
var arrayTag = '[object Array]';
var objectProto = Object.prototype;
var objToString = objectProto.toString;
var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray;
var isArray = nativeIsArray || function(value) {
return (isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag) || false;
};
module.exports = isArray;
},{"../internal/isLength":110,"../internal/isObjectLike":111,"./isNative":120}],118:[function(require,module,exports){
var isArguments = require('./isArguments'),
isArray = require('./isArray'),
isFunction = require('./isFunction'),
isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike'),
isString = require('./isString'),
keys = require('../object/keys');
function isEmpty(value) {
if (value == null) {
return true;
}
var length = value.length;
if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) ||
(isObjectLike(value) && isFunction(value.splice)))) {
return !length;
}
return !keys(value).length;
}
module.exports = isEmpty;
},{"../internal/isLength":110,"../internal/isObjectLike":111,"../object/keys":126,"./isArguments":116,"./isArray":117,"./isFunction":119,"./isString":122}],119:[function(require,module,exports){
(function (global){
var baseIsFunction = require('../internal/baseIsFunction'),
isNative = require('./isNative');
var funcTag = '[object Function]';
var objectProto = Object.prototype;
var objToString = objectProto.toString;
var Uint8Array = isNative(Uint8Array = global.Uint8Array) && Uint8Array;
var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) {
return objToString.call(value) == funcTag;
};
module.exports = isFunction;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../internal/baseIsFunction":95,"./isNative":120}],120:[function(require,module,exports){
var escapeRegExp = require('../string/escapeRegExp'),
isObjectLike = require('../internal/isObjectLike');
var funcTag = '[object Function]';
var reHostCtor = /^\[object .+?Constructor\]$/;
var objectProto = Object.prototype;
var fnToString = Function.prototype.toString;
var objToString = objectProto.toString;
var reNative = RegExp('^' +
escapeRegExp(objToString)
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
function isNative(value) {
if (value == null) {
return false;
}
if (objToString.call(value) == funcTag) {
return reNative.test(fnToString.call(value));
}
return (isObjectLike(value) && reHostCtor.test(value)) || false;
}
module.exports = isNative;
},{"../internal/isObjectLike":111,"../string/escapeRegExp":128}],121:[function(require,module,exports){
function isObject(value) {
var type = typeof value;
return type == 'function' || (value && type == 'object') || false;
}
module.exports = isObject;
},{}],122:[function(require,module,exports){
var isObjectLike = require('../internal/isObjectLike');
var stringTag = '[object String]';
var objectProto = Object.prototype;
var objToString = objectProto.toString;
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag) || false;
}
module.exports = isString;
},{"../internal/isObjectLike":111}],123:[function(require,module,exports){
var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
var objectProto = Object.prototype;
var objToString = objectProto.toString;
function isTypedArray(value) {
return (isObjectLike(value) && isLength(value.length) && typedArrayTags[objToString.call(value)]) || false;
}
module.exports = isTypedArray;
},{"../internal/isLength":110,"../internal/isObjectLike":111}],124:[function(require,module,exports){
var baseAssign = require('../internal/baseAssign'),
createAssigner = require('../internal/createAssigner');
var assign = createAssigner(baseAssign);
module.exports = assign;
},{"../internal/baseAssign":85,"../internal/createAssigner":103}],125:[function(require,module,exports){
var baseCopy = require('../internal/baseCopy'),
baseCreate = require('../internal/baseCreate'),
isIterateeCall = require('../internal/isIterateeCall'),
keys = require('./keys');
function create(prototype, properties, guard) {
var result = baseCreate(prototype);
if (guard && isIterateeCall(prototype, properties, guard)) {
properties = null;
}
return properties ? baseCopy(properties, result, keys(properties)) : result;
}
module.exports = create;
},{"../internal/baseCopy":87,"../internal/baseCreate":88,"../internal/isIterateeCall":109,"./keys":126}],126:[function(require,module,exports){
var isLength = require('../internal/isLength'),
isNative = require('../lang/isNative'),
isObject = require('../lang/isObject'),
shimKeys = require('../internal/shimKeys');
var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys;
var keys = !nativeKeys ? shimKeys : function(object) {
if (object) {
var Ctor = object.constructor,
length = object.length;
}
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object != 'function' && (length && isLength(length)))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
module.exports = keys;
},{"../internal/isLength":110,"../internal/shimKeys":114,"../lang/isNative":120,"../lang/isObject":121}],127:[function(require,module,exports){
var isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isIndex = require('../internal/isIndex'),
isLength = require('../internal/isLength'),
isObject = require('../lang/isObject'),
support = require('../support');
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = keysIn;
},{"../internal/isIndex":108,"../internal/isLength":110,"../lang/isArguments":116,"../lang/isArray":117,"../lang/isObject":121,"../support":129}],128:[function(require,module,exports){
var baseToString = require('../internal/baseToString');
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
reHasRegExpChars = RegExp(reRegExpChars.source);
function escapeRegExp(string) {
string = baseToString(string);
return (string && reHasRegExpChars.test(string))
? string.replace(reRegExpChars, '\\$&')
: string;
}
module.exports = escapeRegExp;
},{"../internal/baseToString":101}],129:[function(require,module,exports){
(function (global){
var isNative = require('./lang/isNative');
var reThis = /\bthis\b/;
var objectProto = Object.prototype;
var document = (document = global.window) && document.document;
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
var support = {};
(function(x) {
support.funcDecomp = !isNative(global.WinRTError) && reThis.test(function() { return this; });
support.funcNames = typeof Function.name == 'string';
try {
support.dom = document.createDocumentFragment().nodeType === 11;
} catch(e) {
support.dom = false;
}
try {
support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1);
} catch(e) {
support.nonEnumArgs = true;
}
}(0, 0));
module.exports = support;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./lang/isNative":120}],130:[function(require,module,exports){
function identity(value) {
return value;
}
module.exports = identity;
},{}]},{},[1])
Something went wrong with that request. Please try again.
================================================ FILE: S3WebApp/S3/assets/js/constants.js ================================================ var MESSAGES_ENDPOINT = ""; ================================================ FILE: S3WebApp/S3/assets/js/jsbn.js ================================================ // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); } else this[this.t-1] |= x<= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); ================================================ FILE: S3WebApp/S3/assets/js/jsbn2.js ================================================ // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) ================================================ FILE: S3WebApp/S3/assets/js/sjcl.js ================================================ "use strict";function q(a){throw a;}var s=void 0,u=!1;var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}}; "undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define&&define([],function(){return sjcl}); sjcl.cipher.aes=function(a){this.l[0][0][0]||this.F();var b,c,d,e,g=this.l[0][4],f=this.l[1];b=a.length;var h=1;4!==b&&(6!==b&&8!==b)&&q(new sjcl.exception.invalid("invalid aes key size"));this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=g[c>>>24]<<24^g[c>>16&255]<<16^g[c>>8&255]<<8^g[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:f[0][g[c>>>24]]^f[1][g[c>>16&255]]^f[2][g[c>>8&255]]^f[3][g[c& 255]]}; sjcl.cipher.aes.prototype={encrypt:function(a){return w(this,a,0)},decrypt:function(a){return w(this,a,1)},l:[[[],[],[],[],[]],[[],[],[],[],[]]],F:function(){var a=this.l[0],b=this.l[1],c=a[4],d=b[4],e,g,f,h=[],l=[],k,n,m,p;for(e=0;0x100>e;e++)l[(h[e]=e<<1^283*(e>>7))^e]=e;for(g=f=0;!c[g];g^=k||1,f=l[f]||1){m=f^f<<1^f<<2^f<<3^f<<4;m=m>>8^m&255^99;c[g]=m;d[m]=g;n=h[e=h[k=h[g]]];p=0x1010101*n^0x10001*e^0x101*k^0x1010100*g;n=0x101*h[m]^0x1010100*m;for(e=0;4>e;e++)a[e][g]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8}for(e= 0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}}; function w(a,b,c){4!==b.length&&q(new sjcl.exception.invalid("invalid aes block size"));var d=a.b[c],e=b[0]^d[0],g=b[c?3:1]^d[1],f=b[2]^d[2];b=b[c?1:3]^d[3];var h,l,k,n=d.length/4-2,m,p=4,t=[0,0,0,0];h=a.l[c];a=h[0];var r=h[1],v=h[2],y=h[3],z=h[4];for(m=0;m>>24]^r[g>>16&255]^v[f>>8&255]^y[b&255]^d[p],l=a[g>>>24]^r[f>>16&255]^v[b>>8&255]^y[e&255]^d[p+1],k=a[f>>>24]^r[b>>16&255]^v[e>>8&255]^y[g&255]^d[p+2],b=a[b>>>24]^r[e>>16&255]^v[g>>8&255]^y[f&255]^d[p+3],p+=4,e=h,g=l,f=k;for(m=0;4> m;m++)t[c?3&-m:m]=z[e>>>24]<<24^z[g>>16&255]<<16^z[f>>8&255]<<8^z[b&255]^d[p++],h=e,e=g,g=f,f=b,b=h;return t} sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.Q(a.slice(b/32),32-(b&31)).slice(1);return c===s?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return u;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32>>24|c>>>8&0xff00|(c&0xff00)<<8|c<<24;return a}}; sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>24),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>e)>>>26),6>e?(f=a[c]<<6-e,e+=26,c++):(f<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,g=sjcl.codec.base64.K,f=0,h;b&&(g=g.substr(0,62)+"-_");for(d=0;dh&&q(new sjcl.exception.invalid("this isn't base64!")),26>>e),f=h<<32-e):(e+=6,f^=h<<32-e);e&56&&c.push(sjcl.bitArray.partial(e&56,f,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}}; sjcl.codec.bytes={fromBits:function(a){var b=[],c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>24),e<<=8;return b},toBits:function(a){var b=[],c,d=0;for(c=0;cb;c++){for(d=2;d*d<=c;d++)if(0===c%d)continue a;8>b&&(this.O[b]=a(Math.pow(c,0.5)));this.b[b]=a(Math.pow(c,1/3));b++}}}; function x(a,b){var c,d,e,g=b.slice(0),f=a.r,h=a.b,l=f[0],k=f[1],n=f[2],m=f[3],p=f[4],t=f[5],r=f[6],v=f[7];for(c=0;64>c;c++)16>c?d=g[c]:(d=g[c+1&15],e=g[c+14&15],d=g[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+g[c&15]+g[c+9&15]|0),d=d+v+(p>>>6^p>>>11^p>>>25^p<<26^p<<21^p<<7)+(r^p&(t^r))+h[c],v=r,r=t,t=p,p=m+d|0,m=n,n=k,k=l,l=d+(k&n^m&(k^n))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+l|0;f[1]=f[1]+k|0;f[2]=f[2]+n|0;f[3]=f[3]+m|0;f[4]=f[4]+p|0;f[5]=f[5]+t|0;f[6]= f[6]+r|0;f[7]=f[7]+v|0} sjcl.mode.ccm={name:"ccm",s:[],listenProgress:function(a){sjcl.mode.ccm.s.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.s.indexOf(a);-1l&&q(new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"));for(g=2;4>g&&k>>>8*g;g++);g<15-l&&(g=15-l);c=h.clamp(c,8*(15- g));b=sjcl.mode.ccm.M(a,b,c,d,e,g);f=sjcl.mode.ccm.p(a,f,c,b,e,g);return h.concat(f.data,f.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var g=sjcl.bitArray,f=g.bitLength(c)/8,h=g.bitLength(b),l=g.clamp(b,h-e),k=g.bitSlice(b,h-e),h=(h-e)/8;7>f&&q(new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"));for(b=2;4>b&&h>>>8*b;b++);b<15-f&&(b=15-f);c=g.clamp(c,8*(15-b));l=sjcl.mode.ccm.p(a,l,c,k,e,b);a=sjcl.mode.ccm.M(a,l.data,c,d,e,b);g.equal(l.tag,a)||q(new sjcl.exception.corrupt("ccm: tag doesn't match")); return l.data},da:function(a,b,c,d,e,g){var f=[],h=sjcl.bitArray,l=h.g;d=[h.partial(8,(b.length?64:0)|d-2<<2|g-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length){c=h.bitLength(b)/8;65279>=c?f=[h.partial(16,c)]:0xffffffff>=c&&(f=h.concat([h.partial(16,65534)],[c]));f=h.concat(f,b);for(b=0;be||16n&&(sjcl.mode.ccm.W(f/ l),n+=m),c[3]++,e=a.encrypt(c),b[f]^=e[0],b[f+1]^=e[1],b[f+2]^=e[2],b[f+3]^=e[3];return{tag:d,data:h.clamp(b,k)}}}; sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,g){128!==sjcl.bitArray.bitLength(c)&&q(new sjcl.exception.invalid("ocb iv must be 128 bits"));var f,h=sjcl.mode.ocb2.I,l=sjcl.bitArray,k=l.g,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(f=0;f+4e.bitLength(c)&&(h=g(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));f=g(f,c);return a.encrypt(g(d(g(h, d(h))),f))},I:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}}; sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var g=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.p(!0,a,g,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var g=b.slice(0),f=sjcl.bitArray,h=f.bitLength(g);e=e||128;d=d||[];e<=h?(b=f.bitSlice(g,h-e),g=f.bitSlice(g,0,h-e)):(b=g,g=[]);a=sjcl.mode.gcm.p(u,a,g,d,c,e);f.equal(a.tag,b)||q(new sjcl.exception.corrupt("gcm: tag doesn't match"));return a.data},aa:function(a,b){var c,d,e,g,f,h=sjcl.bitArray.g;e=[0,0,0,0];g= b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,g));f=0!==(g[3]&1);for(d=3;0>>1|(g[d-1]&1)<<31;g[0]>>>=1;f&&(g[0]^=-0x1f000000)}return e},h:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)&&q(sjcl.exception.invalid("invalid params to pbkdf2"));"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var g,f,h,l,k=[],n=sjcl.bitArray;for(l=1;32*k.length<(d||1);l++){e=g=a.encrypt(n.concat(b,[l]));for(f=1;ff;f++)e.push(0x100000000*Math.random()|0);for(f=0;f=1<this.k&&(this.k=g);this.G++; this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.B=new sjcl.cipher.aes(this.b);for(d=0;4>d&&!(this.f[d]=this.f[d]+1|0,this.f[d]);d++);}for(d=0;d>>=1;this.c[f].update([d,this.D++,2,b,g,a.length].concat(a))}break;case "string":b===s&&(b=a.length);this.c[f].update([d,this.D++,3,b,g,a.length]);this.c[f].update(a);break;default:l=1}l&&q(new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string"));this.j[f]+=b;this.d+=b;h===this.m&&(this.isReady()!==this.m&&C("seeded",Math.max(this.k,this.d)),C("progress",this.getProgress()))},isReady:function(a){a=this.J[a!==s?a:this.C];return this.k&&this.k>=a?this.j[0]>this.S&& (new Date).valueOf()>this.P?this.w|this.u:this.u:this.d>=a?this.w|this.m:this.m},getProgress:function(a){a=this.J[a?a:this.C];return this.k>=a?1:this.d>a?1:this.d/a},startCollectors:function(){this.q||(this.a={loadTimeCollector:D(this,this.ca),mouseCollector:D(this,this.ea),keyboardCollector:D(this,this.ba),accelerometerCollector:D(this,this.V),touchCollector:D(this,this.ga)},window.addEventListener?(window.addEventListener("load",this.a.loadTimeCollector,u),window.addEventListener("mousemove",this.a.mouseCollector, u),window.addEventListener("keypress",this.a.keyboardCollector,u),window.addEventListener("devicemotion",this.a.accelerometerCollector,u),window.addEventListener("touchmove",this.a.touchCollector,u)):document.attachEvent?(document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector)):q(new sjcl.exception.bug("can't attach event")),this.q=!0)},stopCollectors:function(){this.q&&(window.removeEventListener? (window.removeEventListener("load",this.a.loadTimeCollector,u),window.removeEventListener("mousemove",this.a.mouseCollector,u),window.removeEventListener("keypress",this.a.keyboardCollector,u),window.removeEventListener("devicemotion",this.a.accelerometerCollector,u),window.removeEventListener("touchmove",this.a.touchCollector,u)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress", this.a.keyboardCollector)),this.q=u)},addEventListener:function(a,b){this.A[a][this.X++]=b},removeEventListener:function(a,b){var c,d,e=this.A[a],g=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&g.push(d);for(c=0;cb&&!(a.f[b]=a.f[b]+1|0,a.f[b]);b++);return a.B.encrypt(a.f)}function D(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6); a:try{var F,G,H,I;if(I="undefined"!==typeof module){var J;if(J=module.exports){var K;try{K=require("crypto")}catch(L){K=null}J=(G=K)&&G.randomBytes}I=J}if(I)F=G.randomBytes(128),F=new Uint32Array((new Uint8Array(F)).buffer),sjcl.random.addEntropy(F,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){H=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(H);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(H); else break a;sjcl.random.addEntropy(H,1024,"crypto['getRandomValues']")}}catch(M){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(M))} sjcl.json={defaults:{v:1,iter:1E3,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},$:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,g=e.e({iv:sjcl.random.randomWords(4,0)},e.defaults),f;e.e(g,c);c=g.adata;"string"===typeof g.salt&&(g.salt=sjcl.codec.base64.toBits(g.salt));"string"===typeof g.iv&&(g.iv=sjcl.codec.base64.toBits(g.iv));(!sjcl.mode[g.mode]||!sjcl.cipher[g.cipher]||"string"===typeof a&&100>=g.iter||64!==g.ts&&96!==g.ts&&128!==g.ts||128!==g.ks&&192!==g.ks&&0x100!==g.ks||2>g.iv.length||4< g.iv.length)&&q(new sjcl.exception.invalid("json encrypt: invalid parameters"));"string"===typeof a?(f=sjcl.misc.cachedPbkdf2(a,g),a=f.key.slice(0,g.ks/32),g.salt=f.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&&(f=a.kem(),g.kemtag=f.tag,a=f.key.slice(0,g.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(g.adata=c=sjcl.codec.utf8String.toBits(c));f=new sjcl.cipher[g.cipher](a);e.e(d,g);d.key=a;g.ct="ccm"===g.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&& b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(f,b,g.iv,c,g.ts):sjcl.mode[g.mode].encrypt(f,b,g.iv,c,g.ts);return g},encrypt:function(a,b,c,d){var e=sjcl.json,g=e.$.apply(e,arguments);return e.encode(g)},Z:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.e(e.e(e.e({},e.defaults),b),c,!0);var g,f;g=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||"string"=== typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100!==b.ks||!b.iv||2>b.iv.length||4 Zombie Chat Application
================================================ FILE: S3WebApp/S3/lib/CryptoJS/components/enc-base64.js ================================================ /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); ================================================ FILE: S3WebApp/S3/lib/CryptoJS/components/hmac.js ================================================ /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); ================================================ FILE: S3WebApp/S3/lib/CryptoJS/rollups/hmac-sha256.js ================================================ /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ var CryptoJS=CryptoJS||function(h,s){var f={},g=f.lib={},q=function(){},m=g.Base={extend:function(a){q.prototype=this;var c=new q;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, r=g.WordArray=m.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=s?c:4*a.length},toString:function(a){return(a||k).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b, 2),16)<<24-4*(b%8);return new r.init(d,c/2)}},n=l.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new r.init(d,c)}},j=l.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}}, u=g.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var g=0;gn;){var j;a:{j=k;for(var u=h.sqrt(j),t=2;t<=u;t++)if(!(j%t)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=l(h.pow(k,0.5))),r[n]=l(h.pow(k,1/3)),n++);k++}var a=[],f=f.SHA256=q.extend({_doReset:function(){this._hash=new g.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],j=b[3],h=b[4],m=b[5],n=b[6],q=b[7],p=0;64>p;p++){if(16>p)a[p]= c[d+p]|0;else{var k=a[p-15],l=a[p-2];a[p]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+a[p-7]+((l<<15|l>>>17)^(l<<13|l>>>19)^l>>>10)+a[p-16]}k=q+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&m^~h&n)+r[p]+a[p];l=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);q=n;n=m;m=h;h=j+k|0;j=g;g=f;f=e;e=k+l|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+j|0;b[4]=b[4]+h|0;b[5]=b[5]+m|0;b[6]=b[6]+n|0;b[7]=b[7]+q|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=q._createHelper(f);s.HmacSHA256=q._createHmacHelper(f)})(Math); (function(){var h=CryptoJS,s=h.enc.Utf8;h.algo.HMAC=h.lib.Base.extend({init:function(f,g){f=this._hasher=new f.init;"string"==typeof g&&(g=s.parse(g));var h=f.blockSize,m=4*h;g.sigBytes>m&&(g=f.finalize(g));g.clamp();for(var r=this._oKey=g.clone(),l=this._iKey=g.clone(),k=r.words,n=l.words,j=0;j>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< 32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=j.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b, 2),16)<<24-4*(b%8);return new q.init(d,c/2)}},k=v.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new q.init(d,c)}},l=v.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}}, x=t.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=l.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var m=0;mk;){var l;a:{l=u;for(var x=h.sqrt(l),w=2;w<=x;w++)if(!(l%w)){l=!1;break a}l=!0}l&&(8>k&&(j[k]=v(h.pow(u,0.5))),q[k]=v(h.pow(u,1/3)),k++);u++}var a=[],f=f.SHA256=g.extend({_doReset:function(){this._hash=new t.init(j.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],m=b[2],h=b[3],p=b[4],j=b[5],k=b[6],l=b[7],n=0;64>n;n++){if(16>n)a[n]= c[d+n]|0;else{var r=a[n-15],g=a[n-2];a[n]=((r<<25|r>>>7)^(r<<14|r>>>18)^r>>>3)+a[n-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+a[n-16]}r=l+((p<<26|p>>>6)^(p<<21|p>>>11)^(p<<7|p>>>25))+(p&j^~p&k)+q[n]+a[n];g=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&m^f&m);l=k;k=j;j=p;p=h+r|0;h=m;m=f;f=e;e=r+g|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+m|0;b[3]=b[3]+h|0;b[4]=b[4]+p|0;b[5]=b[5]+j|0;b[6]=b[6]+k|0;b[7]=b[7]+l|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=g.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=g._createHelper(f);s.HmacSHA256=g._createHmacHelper(f)})(Math); ================================================ FILE: S3WebApp/S3/lib/apiGatewayCore/apiGatewayClient.js ================================================ /* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ var apiGateway = apiGateway || {}; apiGateway.core = apiGateway.core || {}; apiGateway.core.apiGatewayClientFactory = {}; apiGateway.core.apiGatewayClientFactory.newClient = function (simpleHttpClientConfig, sigV4ClientConfig) { var apiGatewayClient = { }; //Spin up 2 httpClients, one for simple requests, one for SigV4 var sigV4Client = apiGateway.core.sigV4ClientFactory.newClient(sigV4ClientConfig); var simpleHttpClient = apiGateway.core.simpleHttpClientFactory.newClient(simpleHttpClientConfig); apiGatewayClient.makeRequest = function (request, authType, additionalParams, apiKey) { //Default the request to use the simple http client var clientToUse = simpleHttpClient; //Attach the apiKey to the headers request if one was provided if (apiKey !== undefined && apiKey !== '' && apiKey !== null) { request.headers['x-api-key'] = apiKey; } if (request.body === undefined || request.body === '' || request.body === null || Object.keys(request.body).length === 0) { request.body = undefined; } // If the user specified any additional headers or query params that may not have been modeled // merge them into the appropriate request properties request.headers = apiGateway.core.utils.mergeInto(request.headers, additionalParams.headers); request.queryParams = apiGateway.core.utils.mergeInto(request.queryParams, additionalParams.queryParams); //If an auth type was specified inject the appropriate auth client if (authType === 'AWS_IAM') { clientToUse = sigV4Client; } //Call the selected http client to make the request, returning a promise once the request is sent return clientToUse.makeRequest(request); }; return apiGatewayClient; }; ================================================ FILE: S3WebApp/S3/lib/apiGatewayCore/sigV4Client.js ================================================ /* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ var apiGateway = apiGateway || {}; apiGateway.core = apiGateway.core || {}; apiGateway.core.sigV4ClientFactory = {}; apiGateway.core.sigV4ClientFactory.newClient = function (config) { var AWS_SHA_256 = 'AWS4-HMAC-SHA256'; var AWS4_REQUEST = 'aws4_request'; var AWS4 = 'AWS4'; var X_AMZ_DATE = 'x-amz-date'; var X_AMZ_SECURITY_TOKEN = 'x-amz-security-token'; var HOST = 'host'; var AUTHORIZATION = 'Authorization'; function hash(value) { return CryptoJS.SHA256(value); } function hexEncode(value) { return value.toString(CryptoJS.enc.Hex); } function hmac(secret, value) { return CryptoJS.HmacSHA256(value, secret, {asBytes: true}); } function buildCanonicalRequest(method, path, queryParams, headers, payload) { return method + '\n' + buildCanonicalUri(path) + '\n' + buildCanonicalQueryString(queryParams) + '\n' + buildCanonicalHeaders(headers) + '\n' + buildCanonicalSignedHeaders(headers) + '\n' + hexEncode(hash(payload)); } function hashCanonicalRequest(request) { return hexEncode(hash(request)); } function buildCanonicalUri(uri) { return encodeURI(uri); } function buildCanonicalQueryString(queryParams) { if (Object.keys(queryParams).length < 1) { return ''; } var sortedQueryParams = []; for (var property in queryParams) { if (queryParams.hasOwnProperty(property)) { sortedQueryParams.push(property); } } sortedQueryParams.sort(); var canonicalQueryString = ''; for (var i = 0; i < sortedQueryParams.length; i++) { canonicalQueryString += sortedQueryParams[i] + '=' + encodeURIComponent(queryParams[sortedQueryParams[i]]) + '&'; } return canonicalQueryString.substr(0, canonicalQueryString.length - 1); } function buildCanonicalHeaders(headers) { var canonicalHeaders = ''; var sortedKeys = []; for (var property in headers) { if (headers.hasOwnProperty(property)) { sortedKeys.push(property); } } sortedKeys.sort(); for (var i = 0; i < sortedKeys.length; i++) { canonicalHeaders += sortedKeys[i].toLowerCase() + ':' + headers[sortedKeys[i]] + '\n'; } return canonicalHeaders; } function buildCanonicalSignedHeaders(headers) { var sortedKeys = []; for (var property in headers) { if (headers.hasOwnProperty(property)) { sortedKeys.push(property.toLowerCase()); } } sortedKeys.sort(); return sortedKeys.join(';'); } function buildStringToSign(datetime, credentialScope, hashedCanonicalRequest) { return AWS_SHA_256 + '\n' + datetime + '\n' + credentialScope + '\n' + hashedCanonicalRequest; } function buildCredentialScope(datetime, region, service) { return datetime.substr(0, 8) + '/' + region + '/' + service + '/' + AWS4_REQUEST } function calculateSigningKey(secretKey, datetime, region, service) { return hmac(hmac(hmac(hmac(AWS4 + secretKey, datetime.substr(0, 8)), region), service), AWS4_REQUEST); } function calculateSignature(key, stringToSign) { return hexEncode(hmac(key, stringToSign)); } function buildAuthorizationHeader(accessKey, credentialScope, headers, signature) { return AWS_SHA_256 + ' Credential=' + accessKey + '/' + credentialScope + ', SignedHeaders=' + buildCanonicalSignedHeaders(headers) + ', Signature=' + signature; } var awsSigV4Client = { }; if(config.accessKey === undefined || config.secretKey === undefined) { return awsSigV4Client; } awsSigV4Client.accessKey = apiGateway.core.utils.assertDefined(config.accessKey, 'accessKey'); awsSigV4Client.secretKey = apiGateway.core.utils.assertDefined(config.secretKey, 'secretKey'); awsSigV4Client.sessionToken = config.sessionToken; awsSigV4Client.serviceName = apiGateway.core.utils.assertDefined(config.serviceName, 'serviceName'); awsSigV4Client.region = apiGateway.core.utils.assertDefined(config.region, 'region'); awsSigV4Client.endpoint = apiGateway.core.utils.assertDefined(config.endpoint, 'endpoint'); awsSigV4Client.makeRequest = function (request) { var verb = apiGateway.core.utils.assertDefined(request.verb, 'verb'); var path = apiGateway.core.utils.assertDefined(request.path, 'path'); var queryParams = apiGateway.core.utils.copy(request.queryParams); if (queryParams === undefined) { queryParams = {}; } var headers = apiGateway.core.utils.copy(request.headers); if (headers === undefined) { headers = {}; } //If the user has not specified an override for Content type the use default if(headers['Content-Type'] === undefined) { headers['Content-Type'] = config.defaultContentType; } //If the user has not specified an override for Accept type the use default if(headers['Accept'] === undefined) { headers['Accept'] = config.defaultAcceptType; } var body = apiGateway.core.utils.copy(request.body); if (body === undefined || verb === 'GET') { // override request body and set to empty when signing GET requests body = ''; } else { body = JSON.stringify(body); } //If there is no body remove the content-type header so it is not included in SigV4 calculation if(body === '' || body === undefined || body === null) { delete headers['Content-Type']; } var datetime = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z').replace(/[:\-]|\.\d{3}/g, ''); headers[X_AMZ_DATE] = datetime; var parser = document.createElement('a'); parser.href = awsSigV4Client.endpoint; headers[HOST] = parser.hostname; var canonicalRequest = buildCanonicalRequest(verb, path, queryParams, headers, body); var hashedCanonicalRequest = hashCanonicalRequest(canonicalRequest); var credentialScope = buildCredentialScope(datetime, awsSigV4Client.region, awsSigV4Client.serviceName); var stringToSign = buildStringToSign(datetime, credentialScope, hashedCanonicalRequest); var signingKey = calculateSigningKey(awsSigV4Client.secretKey, datetime, awsSigV4Client.region, awsSigV4Client.serviceName); var signature = calculateSignature(signingKey, stringToSign); headers[AUTHORIZATION] = buildAuthorizationHeader(awsSigV4Client.accessKey, credentialScope, headers, signature); if(awsSigV4Client.sessionToken !== undefined && awsSigV4Client.sessionToken !== '') { headers[X_AMZ_SECURITY_TOKEN] = awsSigV4Client.sessionToken; } delete headers[HOST]; var url = config.endpoint + path; var queryString = buildCanonicalQueryString(queryParams); if (queryString != '') { url += '?' + queryString; } //Need to re-attach Content-Type if it is not specified at this point if(headers['Content-Type'] === undefined) { headers['Content-Type'] = config.defaultContentType; } var signedRequest = { method: verb, url: url, headers: headers, data: body }; return axios(signedRequest); }; return awsSigV4Client; }; ================================================ FILE: S3WebApp/S3/lib/apiGatewayCore/simpleHttpClient.js ================================================ /* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ var apiGateway = apiGateway || {}; apiGateway.core = apiGateway.core || {}; apiGateway.core.simpleHttpClientFactory = {}; apiGateway.core.simpleHttpClientFactory.newClient = function (config) { function buildCanonicalQueryString(queryParams) { //Build a properly encoded query string from a QueryParam object if (Object.keys(queryParams).length < 1) { return ''; } var canonicalQueryString = ''; for (var property in queryParams) { if (queryParams.hasOwnProperty(property)) { canonicalQueryString += encodeURIComponent(property) + '=' + encodeURIComponent(queryParams[property]) + '&'; } } return canonicalQueryString.substr(0, canonicalQueryString.length - 1); } var simpleHttpClient = { }; simpleHttpClient.endpoint = apiGateway.core.utils.assertDefined(config.endpoint, 'endpoint'); simpleHttpClient.makeRequest = function (request) { var verb = apiGateway.core.utils.assertDefined(request.verb, 'verb'); var path = apiGateway.core.utils.assertDefined(request.path, 'path'); var queryParams = apiGateway.core.utils.copy(request.queryParams); if (queryParams === undefined) { queryParams = {}; } var headers = apiGateway.core.utils.copy(request.headers); if (headers === undefined) { headers = {}; } //If the user has not specified an override for Content type the use default if(headers['Content-Type'] === undefined) { headers['Content-Type'] = config.defaultContentType; } //If the user has not specified an override for Accept type the use default if(headers['Accept'] === undefined) { headers['Accept'] = config.defaultAcceptType; } var body = apiGateway.core.utils.copy(request.body); if (body === undefined) { body = ''; } var url = config.endpoint + path; var queryString = buildCanonicalQueryString(queryParams); if (queryString != '') { url += '?' + queryString; } var simpleHttpRequest = { method: verb, url: url, headers: headers, data: body }; return axios(simpleHttpRequest); }; return simpleHttpClient; }; ================================================ FILE: S3WebApp/S3/lib/apiGatewayCore/utils.js ================================================ /* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ var apiGateway = apiGateway || {}; apiGateway.core = apiGateway.core || {}; apiGateway.core.utils = { assertDefined: function (object, name) { if (object === undefined) { throw name + ' must be defined'; } else { return object; } }, assertParametersDefined: function (params, keys, ignore) { if (keys === undefined) { return; } if (keys.length > 0 && params === undefined) { params = {}; } for (var i = 0; i < keys.length; i++) { if(!apiGateway.core.utils.contains(ignore, keys[i])) { apiGateway.core.utils.assertDefined(params[keys[i]], keys[i]); } } }, parseParametersToObject: function (params, keys) { if (params === undefined) { return {}; } var object = { }; for (var i = 0; i < keys.length; i++) { object[keys[i]] = params[keys[i]]; } return object; }, contains: function(a, obj) { if(a === undefined) { return false;} var i = a.length; while (i--) { if (a[i] === obj) { return true; } } return false; }, copy: function (obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; }, mergeInto: function (baseObj, additionalProps) { if (null == baseObj || "object" != typeof baseObj) return baseObj; var merged = baseObj.constructor(); for (var attr in baseObj) { if (baseObj.hasOwnProperty(attr)) merged[attr] = baseObj[attr]; } if (null == additionalProps || "object" != typeof additionalProps) return baseObj; for (attr in additionalProps) { if (additionalProps.hasOwnProperty(attr)) merged[attr] = additionalProps[attr]; } return merged; } }; ================================================ FILE: S3WebApp/S3/lib/axios/dist/axios.standalone.js ================================================ /* axios v0.7.0 Copyright (c) 2014 Matt Zabriskie 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. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["axios"] = factory(); else root["axios"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var defaults = __webpack_require__(2); var utils = __webpack_require__(3); var dispatchRequest = __webpack_require__(4); var InterceptorManager = __webpack_require__(12); var axios = module.exports = function (config) { // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = utils.merge({ url: arguments[0] }, arguments[1]); } config = utils.merge({ method: 'get', headers: {}, timeout: defaults.timeout, transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }, config); // Don't allow overriding defaults.withCredentials config.withCredentials = config.withCredentials || defaults.withCredentials; // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); axios.interceptors.request.forEach(function (interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); axios.interceptors.response.forEach(function (interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; // Expose defaults axios.defaults = defaults; // Expose all/spread axios.all = function (promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(13); // Expose interceptors axios.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; // Provide aliases for supported request methods (function () { function createShortMethods() { utils.forEach(arguments, function (method) { axios[method] = function (url, config) { return axios(utils.merge(config || {}, { method: method, url: url })); }; }); } function createShortMethodsWithData() { utils.forEach(arguments, function (method) { axios[method] = function (url, data, config) { return axios(utils.merge(config || {}, { method: method, url: url, data: data })); }; }); } createShortMethods('delete', 'get', 'head'); createShortMethodsWithData('post', 'put', 'patch'); })(); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); var PROTECTION_PREFIX = /^\)\]\}',?\n/; var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/json' }; module.exports = { transformRequest: [function (data, headers) { if(utils.isFormData(data)) { return data; } if (utils.isArrayBuffer(data)) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isObject(data) && !utils.isFile(data) && !utils.isBlob(data)) { // Set application/json if no Content-Type has been specified if (!utils.isUndefined(headers)) { utils.forEach(headers, function (val, key) { if (key.toLowerCase() === 'content-type') { headers['Content-Type'] = val; } }); if (utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = 'application/json;charset=utf-8'; } } return JSON.stringify(data); } return data; }], transformResponse: [function (data) { if (typeof data === 'string') { data = data.replace(PROTECTION_PREFIX, ''); try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], headers: { common: { 'Accept': 'application/json, text/plain, */*' }, patch: utils.merge(DEFAULT_CONTENT_TYPE), post: utils.merge(DEFAULT_CONTENT_TYPE), put: utils.merge(DEFAULT_CONTENT_TYPE) }, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return toString.call(val) === '[object FormData]'; } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { return ArrayBuffer.isView(val); } else { return (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Determine if a value is an Arguments object * * @param {Object} val The value to test * @returns {boolean} True if value is an Arguments object, otherwise false */ function isArguments(val) { return toString.call(val) === '[object Arguments]'; } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * typeof document.createelement -> undefined */ function isStandardBrowserEnv() { return ( typeof window !== 'undefined' && typeof document !== 'undefined' && typeof document.createElement === 'function' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array or arguments callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Check if obj is array-like var isArrayLike = isArray(obj) || isArguments(obj); // Force an array if not already something iterable if (typeof obj !== 'object' && !isArrayLike) { obj = [obj]; } // Iterate over array values if (isArrayLike) { for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } // Iterate over object keys else { for (var key in obj) { if (obj.hasOwnProperty(key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/*obj1, obj2, obj3, ...*/) { var result = {}; forEach(arguments, function (obj) { forEach(obj, function (val, key) { result[key] = val; }); }); return result; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, trim: trim }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Dispatch a request to the server using whichever adapter * is supported by the current environment. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { return new Promise(function (resolve, reject) { try { // For browsers use XHR adapter if ((typeof XMLHttpRequest !== 'undefined') || (typeof ActiveXObject !== 'undefined')) { __webpack_require__(6)(resolve, reject, config); } // For node use HTTP adapter else if (typeof process !== 'undefined') { __webpack_require__(6)(resolve, reject, config); } } catch (e) { reject(e); } }); }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5))) /***/ }, /* 5 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(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; clearTimeout(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) { setTimeout(drainQueue, 0); } }; // 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.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; }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /*global ActiveXObject:true*/ var defaults = __webpack_require__(2); var utils = __webpack_require__(3); var buildUrl = __webpack_require__(7); var parseHeaders = __webpack_require__(8); var transformData = __webpack_require__(9); module.exports = function xhrAdapter(resolve, reject, config) { // Transform request data var data = transformData( config.data, config.headers, config.transformRequest ); // Merge headers var requestHeaders = utils.merge( defaults.headers.common, defaults.headers[config.method] || {}, config.headers || {} ); if (utils.isFormData(data)) { // Content-Type needs to be sent in all requests so the mapping template can be applied //delete requestHeaders['Content-Type']; // Let the browser set it } // Create the request var request = new (XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP'); request.open(config.method.toUpperCase(), buildUrl(config.url, config.params), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function () { if (request && request.readyState === 4) { // Prepare the response var responseHeaders = parseHeaders(request.getAllResponseHeaders()); var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response; var response = { data: transformData( responseData, responseHeaders, config.transformResponse ), status: request.status, statusText: request.statusText, headers: responseHeaders, config: config }; // Resolve or reject the Promise based on the status (request.status >= 200 && request.status < 300 ? resolve : reject)(response); // Clean up request request = null; } }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { var cookies = __webpack_require__(10); var urlIsSameOrigin = __webpack_require__(11); // Add xsrf header var xsrfValue = urlIsSameOrigin(config.url) ? cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue; } } // Add headers to the request utils.forEach(requestHeaders, function (val, key) { // Remove Content-Type if data is undefined if (!data && key.toLowerCase() === 'content-type') { delete requestHeaders[key]; } // Otherwise add header to the request else { request.setRequestHeader(key, val); } }); // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { if (request.responseType !== 'json') { throw e; } } } if (utils.isArrayBuffer(data)) { data = new DataView(data); } // Send the request request.send(data); }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); function encode(val) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildUrl(url, params) { if (!params) { return url; } var parts = []; utils.forEach(params, function (val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } if (!utils.isArray(val)) { val = [val]; } utils.forEach(val, function (v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); if (parts.length > 0) { url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&'); } return url; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } }); return parsed; }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { utils.forEach(fns, function (fn) { data = fn(data, headers); }); return data; }; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * WARNING: * This file makes references to objects that aren't safe in all environments. * Please see lib/utils.isStandardBrowserEnv before including this file. */ var utils = __webpack_require__(3); module.exports = { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * WARNING: * This file makes references to objects that aren't safe in all environments. * Please see lib/utils.isStandardBrowserEnv before including this file. */ var utils = __webpack_require__(3); var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originUrl; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function urlResolve(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originUrl = urlResolve(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestUrl The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ module.exports = function urlIsSameOrigin(requestUrl) { var parsed = (utils.isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function (fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function (id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `remove`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function (fn) { utils.forEach(this.handlers, function (h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }, /* 13 */ /***/ function(module, exports) { 'use strict'; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function (arr) { return callback.apply(null, arr); }; }; /***/ } /******/ ]) }); ; //# sourceMappingURL=axios.map ================================================ FILE: S3WebApp/S3/lib/url-template/url-template.js ================================================ /* UriTemplates Template Processor - Version: @VERSION - Dated: @DATE (c) marc.portier@gmail.com - 2011-2012 Licensed under APLv2 (http://opensource.org/licenses/Apache-2.0) */ ; var uritemplate = (function() { // Below are the functions we originally used from jQuery. // The implementations below are often more naive then what is inside jquery, but they suffice for our needs. function isFunction(fn) { return typeof fn == 'function'; } function isEmptyObject (obj) { for(var name in obj){ return false; } return true; } function extend(base, newprops) { for (var name in newprops) { base[name] = newprops[name]; } return base; } /** * Create a runtime cache around retrieved values from the context. * This allows for dynamic (function) results to be kept the same for multiple * occuring expansions within one template. * Note: Uses key-value tupples to be able to cache null values as well. */ //TODO move this into prep-processing function CachingContext(context) { this.raw = context; this.cache = {}; } CachingContext.prototype.get = function(key) { var val = this.lookupRaw(key); var result = val; if (isFunction(val)) { // check function-result-cache var tupple = this.cache[key]; if (tupple !== null && tupple !== undefined) { result = tupple.val; } else { result = val(this.raw); this.cache[key] = {key: key, val: result}; // NOTE: by storing tupples we make sure a null return is validly consistent too in expansions } } return result; }; CachingContext.prototype.lookupRaw = function(key) { return CachingContext.lookup(this, this.raw, key); }; CachingContext.lookup = function(me, context, key) { var result = context[key]; if (result !== undefined) { return result; } else { var keyparts = key.split('.'); var i = 0, keysplits = keyparts.length - 1; for (i = 0; i

{{chatuser.name}}

================================================ FILE: S3WebApp/S3/modules/chat/chat.js ================================================ angular.module('chatApp.chat', ['chatApp.utils']) .controller('ChatCtrl', function($rootScope, $scope, $state, $_) { $scope.chatState = "Start Chatting"; $rootScope.chatuser = { name: "", phone: "", email: "" }; var data = { UserPoolId : USER_POOL_ID, ClientId : CLIENT_ID }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); if (cognitoUser != null) { cognitoUser.getSession(function(err, session) { if (err) { $scope.signout(); return; } console.log('session validity: ' + session.isValid()); cognitoUser.getUserAttributes(function(err, result) { if (err) { console.log(err); return; } var nm = $_.where(result, { Name: "name" }); if (nm.length > 0) { $rootScope.chatuser.name = nm[0].Value; } var ph = $_.where(result, { Name: "phone_number" }); if (ph.length > 0) { $rootScope.chatuser.phone = ph[0].Value; } var em = $_.where(result, { Name: "email" }); if (em.length > 0) { $rootScope.chatuser.email = em[0].Value; } $scope.$apply(); }); }); } var login = function() { $rootScope.chatting = true; $rootScope.$emit('chatting'); $scope.chatState = "Stop Chatting"; }; var logoff = function() { $scope.chatState = "Start Chatting"; $rootScope.chatting = false; $rootScope.$emit('not chatting'); }; $scope.toggleChatting = function() { if($rootScope.chatting) { logoff(); } else { login(); } }; $scope.signout = function() { if (cognitoUser != null) { console.log("logging user out"); $scope.chatState = "Start Chatting"; $rootScope.chatting = false; $rootScope.$emit('not chatting'); cognitoUser.signOut(); AWS.config.credentials.clearCachedId(); $state.go('signin', { }); } }; }); ================================================ FILE: S3WebApp/S3/modules/chat/chatMessages.html ================================================
================================================ FILE: S3WebApp/S3/modules/chat/chatMessages.js ================================================ angular.module('chatApp.chatMessages', []) .controller('chatMessageCtrl', function($scope, $rootScope, $resource) { $scope.chatPlaceholder = "Save your brains, start chatting!"; $scope.chatMessage = null; $rootScope.$on("chatting", function() { $scope.chatPlaceholder = "Enter a message and save humanity"; }); $rootScope.$on("not chatting", function() { $scope.chatMessage = null; $scope.chatPlaceholder = "Save your brains, start chatting!"; }); $scope.lastTalking = new Date; $scope.chatMessageKeyPressed = function(keyEvent) { var apigClient = apigClientFactory.newClient({ region: AWS_REGION, // OPTIONAL: The region where the API is deployed, by default this parameter is set to us-east-1 accessKey: AWS.config.credentials.accessKeyId, secretKey: AWS.config.credentials.secretAccessKey, sessionToken: AWS.config.credentials.sessionToken }); if (keyEvent.which === 13) { $scope.posting = true; console.log('Sending Message: ' + $scope.chatMessage); var body = { channel: 'default', name: [$rootScope.chatuser.name, " (", $rootScope.chatuser.email, ")"].join(""), message: $scope.chatMessage }; var params = ''; var additionalParams = ''; apigClient.zombieMessagePost(params, body, additionalParams) .then(function(result){ //This is where you would put a success callback console.log('Message sent to database'); console.log ('user email is ' + $rootScope.chatuser.email); $scope.chatMessage = null; $scope.posting = false; $scope.chatPlaceholder = "Enter a message and save humanity"; }).catch( function(result){ console.log('there was an error POSTing'); }); } else { var diff = Date.now() - $scope.lastTalking; console.log(diff); // send talking update at max every .5 seconds if (diff < 500) { return; } var talkersBody = { channel: 'default', name: $rootScope.chatuser.name }; var talkersParams = ''; var talkersAdditionalParams = ''; apigClient.zombieTalkersPost(talkersParams, talkersBody, talkersAdditionalParams) .then(function(result){ console.log('Posting to talkers.'); $scope.lastTalking = new Date; }).catch( function(result){ }); } }; }); ================================================ FILE: S3WebApp/S3/modules/chat/chatPanel.html ================================================
{{ message.name }} {{message.timestamp | date:'yyyy-MM-dd HH:mm:ss Z'}} - {{message.message}}
================================================ FILE: S3WebApp/S3/modules/chat/chatPanel.js ================================================ angular.module('chatApp.chatPanel', ['chatApp.chatMessages']) .controller('chatPanelCtrl', function($scope, $rootScope, $resource, $timeout) { $rootScope.$on("chatting", function() { var Messages = $resource(MESSAGES_ENDPOINT); var poll = function() { $timeout(function() { if($rootScope.chatting) { console.log('Retrieving Messages from Server'); var apigClient = apigClientFactory.newClient({ region: AWS_REGION, // OPTIONAL: The region where the API is deployed, by default this parameter is set to us-east-1 accessKey: AWS.config.credentials.accessKeyId, secretKey: AWS.config.credentials.secretAccessKey, sessionToken: AWS.config.credentials.sessionToken }); var body = ''; var params = ''; var additionalParams = ''; apigClient.zombieMessageGet(params, body, additionalParams) .then(function(result){ if($rootScope.chatting) { //console.log('result: ' + result.data.messages); $scope.messages = result.data.messages; } else { $scope.messages = null; } }).catch(function(result){ console.log('error: ' + result); }); poll(); } }, 2000); }; poll(); }); $rootScope.$on("not chatting", function() { //clear our model, which will clear out the messages from the panel $scope.messages = null; }); }); ================================================ FILE: S3WebApp/S3/modules/chat/talkersPanel.html ================================================
Users Typing:
{{ talker }}
================================================ FILE: S3WebApp/S3/modules/chat/talkersPanel.js ================================================ angular.module('chatApp.talkersPanel', []) .controller('talkersPanelCtrl', function($scope, $rootScope, $resource, $timeout) { $rootScope.$on("chatting", function() { var poll = function() { $timeout(function() { if($rootScope.chatting) { console.log('Retrieving Talkers from Server'); var apigClient = apigClientFactory.newClient({ region: AWS_REGION, // OPTIONAL: The region where the API is deployed, by default this parameter is set to us-east-1 accessKey: AWS.config.credentials.accessKeyId, secretKey: AWS.config.credentials.secretAccessKey, sessionToken: AWS.config.credentials.sessionToken }); var body = ''; var params = ''; var additionalParams = ''; apigClient.zombieTalkersGet(params, body, additionalParams) .then(function(result){ if($rootScope.chatting) { console.log('talkers are: ' + result.data.Talkers); $scope.talkers = result.data.Talkers; } else { $scope.talkers = null; } }).catch(function(error){ console.log('error: ' + error.data); }); poll(); } }, 1000); }; poll(); }); $rootScope.$on("not chatting", function() { //clear our model, which will clear out the messages from the panel $scope.talkers = null; }); }); ================================================ FILE: S3WebApp/S3/modules/confirm/confirm.html ================================================
================================================ FILE: S3WebApp/S3/modules/confirm/confirm.js ================================================ angular.module('chatApp.confirm', []) .controller('ConfirmCtrl', function($scope, $state) { $scope.errormessage = ""; $scope.user = { email: "", confirmCode: "" }; $scope.confirmAccount = function(isValid) { console.log($scope.user); var _username = $scope.user.email; if (isValid) { console.log("Confirmation code " + $scope.user.confirmCode); var poolData = { UserPoolId : USER_POOL_ID, ClientId : CLIENT_ID }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username : _username, Pool : userPool }; var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); cognitoUser.confirmRegistration($scope.user.confirmCode, true, function(err, result) { if (err) { console.log(err); $scope.errormessage = "An unexpected error has occurred. Please try again. Error: " + err; $scope.$apply(); return; } console.log('call result: ' + result); $state.go('signin', { }); }); } else { $scope.errormessage = "There are still invalid fields."; console.log("There are still invalid fields"); } }; }); ================================================ FILE: S3WebApp/S3/modules/index.html ================================================ Zombie Chat Application

{{ message.name }} {{message.timestamp | date:'yyyy-MM-dd HH:mm:ss Z'}} - {{message.message}}
Users Typing:
{{ talker }}
================================================ FILE: S3WebApp/S3/modules/signin/signin.html ================================================
================================================ FILE: S3WebApp/S3/modules/signin/signin.js ================================================ angular.module('chatApp.signin', ['chatApp.utils']) .controller('SigninCtrl', function($scope, $state, $localstorage) { $scope.errormessage = ""; $scope.user = { email: "", password: "" }; $scope.signin = function(isValid) { //console.log($scope.user); if (isValid) { var authenticationData = { Username : $scope.user.email, Password : $scope.user.password, }; var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); var poolData = { UserPoolId : USER_POOL_ID, ClientId : CLIENT_ID }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username : $scope.user.email, Pool : userPool }; var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); try { cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { console.log(result); console.log('access token + ' + result.getAccessToken().getJwtToken()); console.log(cognitoUser); var login = 'cognito-idp.' + COGNITO_REGION + '.amazonaws.com/' + USER_POOL_ID; console.log('login string is: ' + login); AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId : IDENTITY_POOL_ID, // your identity pool id here IdentityId: AWS.config.credentials.identityId }); AWS.config.credentials.params.Logins = {}; AWS.config.credentials.params.Logins[login] = result.getIdToken().getJwtToken(); //console.log('aws config is: ' + AWS.config.credentials.params.Logins[login]); AWS.config.credentials.refresh(function (err) { // now using authenticated credentials if(err) { console.log('Error in authenticating to AWS '+ err); // Call error if we can't assume authenticated role. $scope.errormessage = "Unable to sign in user. There was an error authenticating to identity provider."; $scope.$apply(); } else { console.log('identityId is: ' + AWS.config.credentials.identityId); var awstoken = { expireTime: AWS.config.credentials.expireTime, accessKeyId: AWS.config.credentials.accessKeyId, sessionToken: AWS.config.credentials.sessionToken, secretAccessKey: AWS.config.credentials.secretAccessKey }; $localstorage.setObject('awstoken', awstoken); $state.go('chat', { }); // if all went well then log them in. } }); }, onFailure: function(err) { console.log(err); $scope.errormessage = "Unable to sign in user. Please check your username and password."; $scope.$apply(); } }); } catch(e) { console.log(e); } } else { $scope.errormessage = "There are still invalid fields."; console.log("There are still invalid fields"); } }; }); ================================================ FILE: S3WebApp/S3/modules/signup/signup.html ================================================
================================================ FILE: S3WebApp/S3/modules/signup/signup.js ================================================ angular.module('chatApp.signup', ['chatApp.utils']) .controller('SignupCtrl', function($scope, $state) { $scope.errormessage = ""; $scope.user = { name: "", email: "", phone: "", password: "", confirmPassword: "", camp: "", slackuser: "", slackteamdomain: "" }; $scope.register = function(isValid) { console.log($scope.user); var _username = $scope.user.email; console.log(_username); if (isValid) { console.log("Submitted " + $scope.user.name); var poolData = { UserPoolId : USER_POOL_ID, ClientId : CLIENT_ID }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var attributeList = []; var dataEmail = { Name : 'email', Value : $scope.user.email }; var dataPhoneNumber = { Name : 'phone_number', Value : '+1' + $scope.user.phone }; var dataName = { Name : 'name', Value : $scope.user.name }; var dataCamp = { Name : 'custom:camp', Value : $scope.user.camp ? $scope.user.camp : "null" }; var dataSlackuser = { Name : 'custom:slackuser', Value : $scope.user.slackuser ? $scope.user.slackuser : "null" }; var dataSlackteamdomain = { Name : 'custom:slackteamdomain', Value : $scope.user.slackteamdomain ? $scope.user.slackteamdomain : "null" }; var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail); var attributePhoneNumber = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber); var attributeName = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataName); var attributeCamp = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataCamp); var attributeSlackuser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataSlackuser); var attributeSlackteamdomain = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataSlackteamdomain); attributeList.push(attributeEmail); attributeList.push(attributePhoneNumber); attributeList.push(attributeName); attributeList.push(attributeCamp); attributeList.push(attributeSlackuser); attributeList.push(attributeSlackteamdomain); userPool.signUp(_username, $scope.user.password, attributeList, null, function(err, result){ if (err) { console.log(err); $scope.errormessage = "An unexpected error has occurred. Please try again. Error: " + err; $scope.$apply(); return; } else { cognitoUser = result.user; console.log('user name is ' + cognitoUser.getUsername()); $state.go('confirm', { }); } }); } else { $scope.errormessage = "There are still invalid fields."; console.log("There are still invalid fields"); } }; }); ================================================ FILE: Slack/SlackService.js ================================================ /* == Imports == */ var AWS = require('aws-sdk'); var qs = require('querystring'); var https = require('https'); /* == Globals == */ var API = { region: 'INSERT YOUR REGION HERE', // the region code where you launched the stack endpoint: 'INSERT YOUR API GATEWAY FQDN HERE INCLUDING THE HTTPS://' //i.e.: Something like ... https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com }; var table = 'YOUR DYNAMODB USERS TABLE'; // Find this in the outputs of CFN var index = 'YOUR slackindex DYNAMODB INDEX NAME'; // slackindex for Users table. Find this in outputs of CFN var token = "INSERT YOUR TOKEN FROM SLACK HERE"; // INSERT YOUR TOKEN FROM SLACK HERE. This is the token from your slack team channel when you created the Slack app integration. var endpoint = new AWS.Endpoint(API.endpoint); var creds = new AWS.EnvironmentCredentials('AWS'); var docClient = new AWS.DynamoDB.DocumentClient({ region: API.region }); exports.handler = function (event, context) { console.log('REQUEST RECEIVED:\n', JSON.stringify(event)); if (token) { processEvent(event, context); } else { context.fail("Token has not been set."); } }; var processEvent = function(event, context) { var body = event.body; var params = qs.parse(body); var requestToken = params.token; var slackUserAuthorized = false; // We need to explicitly authorize the username in the payload from Slack. if (requestToken != token) { console.error("Request token (" + requestToken + ") does not match exptected token for Slack"); context.fail("Invalid request token"); } else { var from = params.user_name; var command = params.command; var slackTeamDomain = params.team_domain; var message = params.text; var timestamp = "" + new Date().getTime(); // Now that we have the Slack message formatted correctly, we make a request to our Chat Service var post_data = JSON.stringify({ "message": message + " (Via Slack Slash Command)", "name": from, "channel": "default", "timestamp": timestamp }); /* == DynamoDB Users Index Params == */ var ddbParams = { TableName: table, IndexName: index, KeyConditionExpression: "slackuser = :slackuser and slackteamdomain = :slackteamdomain", ProjectionExpression: "slackuser, slackteamdomain", ExpressionAttributeValues: { ":slackuser": from, ":slackteamdomain": slackTeamDomain } }; /* == Query Users table to confirm that incoming Slack username exists and is tied to an authorized survivor == */ docClient.query(ddbParams, function(err, data) { if (err) { console.log('Error. Unable to send message from Slack. DynamoDB querying failed. RESULT: ' + JSON.stringify(err)); context.fail(new Error('DynamoDB Error: ' + err)); } else { /* == FOR TESTING == */ /* console.log('Query response is: ' + JSON.stringify(data)); console.log('count is: ' + data.Count); console.log('slack username incoming is: ' + from); console.log('slack team domain incoming is: ' + slackTeamDomain); */ // If no records returned then fail the message with not authorized message. if (data.Count < 1) { console.log('Unauthorized user. Invalid Slack username and team domain. No matching users found.'); context.done('The incoming Slack username and team do not match any existing registered survivors. Please sign up to the suvivor chat first, and make sure to register your Slack User name and team domain (name) at sign up.'); } else { // Parse result and get Slack username. data.Items.forEach(function(item) { console.log('Incoming message from: ' + item.slackuser + ' with team domain: ' + item.slackteamdomain); }); // If Slack user is authorized then call /message API endpoint with Slash command payload postToChatService(post_data, context); } } }); } } function postToChatService(post_data, context) { // Create signed AWS request to API endpoint var req = new AWS.HttpRequest(endpoint); req.method = 'POST'; req.port = '443'; req.path = '/ZombieWorkshopStage/zombie/message'; req.region = API.region; req.headers['presigned-expires'] = false; req.headers['Host'] = endpoint.host; req.body = post_data; console.log('host is ' + endpoint.host); var signer = new AWS.Signers.V4(req,'execute-api'); signer.addAuthorization(creds, new Date()); var send = new AWS.NodeHttpClient(); send.handleRequest(req, null, function(httpResp) { var respBody = ''; httpResp.on('data', function (chunk) { respBody += chunk; }); httpResp.on('end', function (chunk) { console.log('Response: ' + respBody); context.succeed("Your slack message was sent to survivors. Message sent was: " + JSON.parse(post_data).message); }); }, function(err) { console.log('Error: ' + err); context.fail('Lambda failed with error ' + err); }); } ================================================ FILE: Twilio/TwilioProcessing.js ================================================ // This function processes incoming data from Twilio, formats it and makes an HTTPS POST request to the the Chat Service API endpoint /* == Imports == */ var querystring = require('querystring'); var AWS = require('aws-sdk'); var path = require('path'); /* == Globals == */ var API = { region: 'INSERT YOUR REGION CODE HERE', //i.e 'us-east-1' endpoint: 'INSERT YOUR API GATEWAY URL HERE INCLUDING THE HTTPS://' // ie: 'https://xxxxxxx.execute-api.us-east-1.amazonaws.com' }; var table = "YOUR DYNAMODB USERS TABLE"; //INSERT THE NAME OF YOUR DYNAMODB USERS TABLE var index = "YOUR phoneindex DYNAMODB INDEX NAME"; //INSERT THE NAME OF YOUR phoneindex from DynamoDB. var endpoint = new AWS.Endpoint(API.endpoint); var creds = new AWS.EnvironmentCredentials('AWS'); var docClient = new AWS.DynamoDB.DocumentClient({ region: API.region }); exports.handler = function(event, context) { var params = querystring.parse(event.postBody); var from = params.From; var timestamp = "" + new Date().getTime(); var numMedia = params.NumMedia; var message; var mediaURL; /* == DynamoDB Params == */ var ddbParams = { TableName: table, IndexName: index, KeyConditionExpression: "phone = :from", ProjectionExpression: "userid, phone", ExpressionAttributeValues: { ":from": from } }; // If Message sent and Image sent, concat image url to message. if (params.Body !== null || params.Body !== 'null') { message = params.Body; // If picture was sent along, append to message string. if (numMedia > 0) { mediaURL = params.MediaUrl0; message = message + " [IMAGE SENT]: " + mediaURL; } } // If message was not sent but image URL was sent, then set message to image URL else if ((params.Body == null || params.Body == 'null') && numMedia > 0) { mediaURL = params.MediaUrl0; message = "Image sent: " + mediaURL; } // If no message or media sent, throw error. else { return context.fail("There was an error. Try again."); } // Now that we have the Twilio data formatted correctly, we make a request to our Chat Service var post_data = JSON.stringify({ "message": message, "name": from, "channel": "default", "timestamp": timestamp }); /* == Query Users table to confirm that incoming phone number exists and is tied to an authorized survivor == */ docClient.query(ddbParams, function(err, data) { if (err) { console.log('Error. Unable to insert text message. DynamoDB querying failed. RESULT: ' + JSON.stringify(err)); context.fail(new Error('DynamoDB Error: ' + err)); } else { // FOR TESTING //console.log('Query response is: ' + JSON.stringify(data)); //console.log('count is: ' + data.Count); // If no records returned then fail the message with not authorized message. if (data.Count < 1) { context.done('Your phone number is not authorized to send texts to survivors. There were no phone numbers matching yours. Please sign up first.'); console.log('Text from unauthorized number. No records matching that number'); } else { // Parse result and get phone. data.Items.forEach(function(item) { console.log('Incoming message from: ' + item.phone); }); postToChatService(post_data, context); } } }); } function postToChatService(post_data, context) { var req = new AWS.HttpRequest(endpoint); req.method = 'POST'; req.path = '/ZombieWorkshopStage/zombie/message'; req.port = '443'; req.region = API.region; req.headers['presigned-expires'] = false; req.headers['Host'] = endpoint.host; req.body = post_data; console.log('host is ' + endpoint.host); var signer = new AWS.Signers.V4(req,'execute-api'); // es: service code signer.addAuthorization(creds, new Date()); var send = new AWS.NodeHttpClient(); send.handleRequest(req, null, function(httpResp) { var respBody = ''; httpResp.on('data', function (chunk) { respBody += chunk; }); httpResp.on('end', function (chunk) { console.log('Response: ' + respBody); context.succeed('Text received in chat room. Survivors have been notified. Message sent was: ' + JSON.parse(post_data).message); }); }, function(err) { console.log('Error: ' + err); context.fail('Lambda failed with error ' + err); }); } ================================================ FILE: cognitoLambdaTrigger/index.js ================================================ "use strict"; console.log('Loading function'); var AWS = require('aws-sdk'); var moment = require('moment'); exports.handler = function(event, context, callback) { console.log(event); // set the appropriate region for AWS api calls const stackName = context.functionName.split('-CognitoLambdaTrigger')[0]; console.log('stackname is: ' + stackName); const region = context.functionName.split('-CognitoLambdaTrigger-')[1]; // The region containing the DDB table that should be queried. console.log('stack region is: ' + region); const dynamoConfig = { sessionToken: process.env.AWS_SESSION_TOKEN, region: region }; const docClient = new AWS.DynamoDB.DocumentClient(dynamoConfig); const ddbTable = stackName + '-users'; console.log('ddbtable is: ' + ddbTable); let params = {}; if (event.triggerSource === "PostConfirmation_ConfirmSignUp") { console.log(event.request.userAttributes['phone_number']); params = { TableName: ddbTable, Item: { userid: event.userName, phone: event.request.userAttributes['phone_number'] } }; docClient.put(params, function(err, data) { if (err) { console.log(err); return callback(err, null); } return callback(null, event); }); } else if (event.triggerSource === "PreAuthentication_Authentication") { params = { TableName: ddbTable, Key: { userid : event.userName }, UpdateExpression: 'set camp = :c, slackuser = :s, confirmed = :v, slackteamdomain = :t', ExpressionAttributeValues: { ':c' : event.request.userAttributes['custom:camp'], ':s' : event.request.userAttributes['custom:slackuser'] ? event.request.userAttributes['custom:slackuser'] : "null", ':t' : event.request.userAttributes['custom:slackteamdomain'], ':v' : event.request.userAttributes['email_verified'] }, ReturnValues:"UPDATED_NEW" }; docClient.update(params, function(err, data) { if (err) { console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); return callback(err, null); } else { console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); return callback(null, event); } }); } else { // not a valid trigger source return callback("Invalid trigger source.", null); } }; ================================================ FILE: zombieSensor/lambda/exampleSNSFunction.js ================================================ /* == Imports == */ var querystring = require('querystring'); var AWS = require('aws-sdk'); var path = require('path'); /* == Globals == */ var API = { region: 'INSERT YOUR REGION CODE HERE', //i.e 'us-east-1' endpoint: 'INSERT YOUR API GATEWAY URL HERE INCLUDING THE HTTPS://' }; var endpoint = new AWS.Endpoint(API.endpoint); var creds = new AWS.EnvironmentCredentials('AWS'); exports.handler = function(event, context) { var params = querystring.parse(event.postBody); var from = params.From; var timestamp = "" + new Date().getTime(); var numMedia = params.NumMedia; var message; var mediaURL; var phoneAuthorized = false; //will set to true when incoming phone is validated //console.log('Received event:', JSON.stringify(event, null, 2)); var snsData = JSON.parse(event.Records[0].Sns.Message); console.log('From SNS:', snsData); var message = snsData.message; var post_data = JSON.stringify({ "message": message, "name": "SYSTEM ALERT", "channel": "default" }); postToChatService(post_data, context); } function postToChatService(post_data, context) { var req = new AWS.HttpRequest(endpoint); req.method = 'POST'; req.path = '/ZombieWorkshopStage/zombie/message'; req.port = '443'; req.region = API.region; req.headers['presigned-expires'] = false; req.headers['Host'] = endpoint.host; req.body = post_data; console.log('host is ' + endpoint.host); var signer = new AWS.Signers.V4(req,'execute-api'); // es: service code signer.addAuthorization(creds, new Date()); var send = new AWS.NodeHttpClient(); send.handleRequest(req, null, function(httpResp) { var respBody = ''; httpResp.on('data', function (chunk) { respBody += chunk; }); httpResp.on('end', function (chunk) { console.log('Successfully processed HTTPS response'); context.succeed('Alert delivered: ' + JSON.parse(post_data).message); }); }, function(err) { console.log('Error: ' + err); context.fail('Lambda failed with error ' + err); }); } ================================================ FILE: zombieSensor/zombieIntelEdisonCode/main.js ================================================ var mraa = require('mraa'); //require mraa var AWS = require('aws-sdk'); //require AWS SDK // For variables that ask for region input, please use region code such as us-west-2 or us-east-1 AWS.config.update({accessKeyId: 'ENTER ACCESS KEY HERE', secretAccessKey: 'ENTER SECRET ACCESS KEY HERE', region: 'ENTER REGION HERE'}); //configure AWS credentials var sns = new AWS.SNS({region: 'ENTER REGION HERE'}); // establish the SNS connection var zombieSensor = new mraa.Gpio(6); //setup digital read on Digital pin #6 (D6) zombieSensor.dir(mraa.DIR_IN); //set the gpio direction to input var city = [ ["London",51.507351,-0.127758], ["Las Vegas",36.169941,-115.139830], ["New York",40.712784,-74.005941], ["Singapore",1.352083,103.819836], ["Sydney",-33.867487,151.206990], ["Paris",48.856614,2.352222], ["Seattle",47.606209,-122.332071], ["San Francisco",37.774929,-122.419416], ["Montreal",45.501689,-73.567256], ["Rio De Janeiro",-22.906847,-43.172896], ["Beijing",39.904211,116.407395], ["Moscow",55.755826,37.617300], ["Buenos Aires",-34.603684,-58.381559], ["New Dehli",28.613939,77.209021], ["Cape Town",-33.924869,18.424055], ["Lagos",6.524379,3.379206], ["Munich",48.135125,11.581981] ] periodicActivity(); //call the periodicActivity function //logic starts here. //Function to generate a randomNumber to be used for selecting random cities function roundedNumberFunc(callback) { var randomNumber = Math.random() * (15 - 0 + 1) + 0; var roundedNumber = Math.round(randomNumber) generateAlert(roundedNumber, city) //call the function to send the alert to SNS } // function to form the message with a random city and send it to SNS function generateAlert(roundedNumber, city) { var message = '{"message":"A Zombie has been detected in ' + city[roundedNumber][0] + '!", "value":"1", "city":"' + city[roundedNumber][0] + '", "longitude":"' + city[roundedNumber][2] + '", "latitude":"' + city[roundedNumber][1] + '"}' var params = { Message: message, /* required */ Subject: "Zombie Alert", TopicArn: "ENTER YOUR TOPIC ARN HERE" }; sns.publish(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data + " Message successfully sent to SNS"); // successful response }); console.log("Zombie Detected") } // Period function to run every second and read the sensor vlaue. function periodicActivity() { var sensorValue = zombieSensor.read(); //read the digital value of the Grove PIR Motion Sensor if (sensorValue == 1) { roundedNumberFunc() // Sensor value is 1 (motion detected), start function to generate random number and publish message to SNS } else { console.log("The Coast is Clear") //No motion detected }; setTimeout(periodicActivity,1000); //call the indicated function after 1 second (1000 milliseconds) } ================================================ FILE: zombieSensor/zombieIntelEdisonCode/package.json ================================================ { "name": "zombieSensor", "description": "Intel Edison device code to publish messages to SNS upon detection of motion", "version": "0.0.1", "main": "main.js", "engines": { "node": ">=0.10.0" }, "dependencies": { "mraa": "", "aws-sdk": "" } }