Commit e725d4b9 authored by xiabin's avatar xiabin

添加逻辑

parent 07553a50

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

...@@ -6,18 +6,23 @@ return [ ...@@ -6,18 +6,23 @@ return [
'bootstrap' => ['log'], 'bootstrap' => ['log'],
'components' => [ 'components' => [
'cache' => [ 'cache' => [
'class' => 'yii\caching\FileCache', 'class' => 'yii\redis\Cache',
'redis' => [
'hostname' => '192.168.1.185',
'port' => 6379,
'database' => 0,
]
], ],
'db' => [ 'db' => [
'class' => 'yii\db\Connection', 'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=zuiketang', 'dsn' => 'mysql:host=192.168.1.185;dbname=zuiketang',
'username' => 'root', 'username' => 'root',
'password' => 'mysql123', 'password' => 'mysql123',
'charset' => 'utf8', 'charset' => 'utf8',
], ],
'redis' => [ 'redis' => [
'class' => 'yii\redis\Connection', 'class' => 'yii\redis\Connection',
'hostname' => 'localhost', 'hostname' => '192.168.1.185',
'port' => 6379, 'port' => 6379,
'database' => 0, 'database' => 0,
], ],
......
<?php
/**
* Created by PhpStorm.
* User: xiabin
* Date: 2016/9/26
* Time: 下午6:18
*/
namespace common\libs;
class SendMsg
{
public function sendMsg($telephones,$content){
if(is_array($telephones)){
$telephones = implode(',',$telephones);
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: xiabin
* Date: 2016/9/26
* Time: 下午6:46
*/
namespace common\libs;
use yii\web\Response;
class Utils
{
/**
* 获取real IP
* @return string
*/
public static function getRealIP()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP']; elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
elseif (!empty($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];
else $ip = '';
preg_match('/[\d\.]{7,15}/', $ip, $ips);
return !empty($ips[0]) ? $ips[0] : '';
}
/**
* @param bool $status
* @param null $data
* @param null $messgae
*/
public static function ajaxResponse($status = TRUE, $messgae = NULL, $data = NULL)
{
$response = \Yii::$app->response;
$response->format = Response::FORMAT_JSON;
$response->data = [
'status' => $status,
'data' => $data,
'message' => $messgae
];
}
/**
* 生成4-6位随机数
* @param int $length
* @return int
*/
public function randomNumber($length = 6)
{
if ($length < 4 or $length > 6) {
$length = 6;
}
switch ($length) {
case 4:
$min = 1000;
$max = 9999;
break;
case 5:
$min = 10000;
$max = 99999;
break;
case 6:
$min = 100000;
$max = 999999;
break;
}
return mt_rand($min, $max);
}
}
\ No newline at end of file
...@@ -219,6 +219,12 @@ class User extends ActiveRecord implements IdentityInterface ...@@ -219,6 +219,12 @@ class User extends ActiveRecord implements IdentityInterface
return static::findOne(['telephone' => $telephone, 'status' => self::STATUS_ACTIVE]); return static::findOne(['telephone' => $telephone, 'status' => self::STATUS_ACTIVE]);
} }
public static function findByTelephone2($telephone){
// return static::findOne(['telephone' => $telephone, 'status' => self::STATUS_ACTIVE]);
return static::find()->select('id,username')->where(['telephone' => $telephone, 'status' => self::STATUS_ACTIVE])
->one();
}
/** /**
* Finds user by password reset token * Finds user by password reset token
* *
......
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"hash": "dba7e94921aaafa6965aaa45d8d75268", "hash": "bdf4a20720b1c71520c40efab351ceb5",
"content-hash": "0d1c4ec380e1693c4db3207fc8ac581d", "content-hash": "97de8c5fe3587d7d90b4efc2a281a190",
"packages": [ "packages": [
{ {
"name": "bower-asset/bootstrap", "name": "bower-asset/bootstrap",
...@@ -299,6 +299,227 @@ ...@@ -299,6 +299,227 @@
], ],
"time": "2016-07-16 12:58:58" "time": "2016-07-16 12:58:58"
}, },
{
"name": "guzzlehttp/guzzle",
"version": "6.2.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "3f808fba627f2c5b69e2501217bf31af349c1427"
},
"dist": {
"type": "zip",
"url": "https://packagist.phpcomposer.com/files/guzzle/guzzle/3f808fba627f2c5b69e2501217bf31af349c1427.zip",
"reference": "3f808fba627f2c5b69e2501217bf31af349c1427",
"shasum": ""
},
"require": {
"guzzlehttp/promises": "^1.0",
"guzzlehttp/psr7": "^1.3.1",
"php": ">=5.5"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.0",
"psr/log": "^1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "6.2-dev"
}
},
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle is a PHP HTTP client library",
"homepage": "http://guzzlephp.org/",
"keywords": [
"client",
"curl",
"framework",
"http",
"http client",
"rest",
"web service"
],
"time": "2016-07-15 17:22:37"
},
{
"name": "guzzlehttp/promises",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "c10d860e2a9595f8883527fa0021c7da9e65f579"
},
"dist": {
"type": "zip",
"url": "https://packagist.phpcomposer.com/files/guzzle/promises/c10d860e2a9595f8883527fa0021c7da9e65f579.zip",
"reference": "c10d860e2a9595f8883527fa0021c7da9e65f579",
"shasum": ""
},
"require": {
"php": ">=5.5.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle promises library",
"keywords": [
"promise"
],
"time": "2016-05-18 16:56:05"
},
{
"name": "guzzlehttp/psr7",
"version": "1.3.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "5c6447c9df362e8f8093bda8f5d8873fe5c7f65b"
},
"dist": {
"type": "zip",
"url": "https://packagist.phpcomposer.com/files/guzzle/psr7/5c6447c9df362e8f8093bda8f5d8873fe5c7f65b.zip",
"reference": "5c6447c9df362e8f8093bda8f5d8873fe5c7f65b",
"shasum": ""
},
"require": {
"php": ">=5.4.0",
"psr/http-message": "~1.0"
},
"provide": {
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.4-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "PSR-7 message implementation",
"keywords": [
"http",
"message",
"stream",
"uri"
],
"time": "2016-06-24 23:00:38"
},
{
"name": "psr/http-message",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
},
"dist": {
"type": "zip",
"url": "https://packagist.phpcomposer.com/files/php-fig/http-message/f6561bf28d520154e4b0ec72be95418abe6d9363.zip",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"time": "2016-08-06 14:39:51"
},
{ {
"name": "swiftmailer/swiftmailer", "name": "swiftmailer/swiftmailer",
"version": "v5.4.3", "version": "v5.4.3",
......
...@@ -19,8 +19,8 @@ class AppAsset extends AssetBundle ...@@ -19,8 +19,8 @@ class AppAsset extends AssetBundle
['common/common.js', 'position' => View::POS_BEGIN] ['common/common.js', 'position' => View::POS_BEGIN]
]; ];
public $depends = [ public $depends = [
'yii\web\YiiAsset', // 'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset', // 'yii\bootstrap\BootstrapAsset',
]; ];
//定义按需加载JS方法,注意加载顺序在最后 //定义按需加载JS方法,注意加载顺序在最后
......
...@@ -23,7 +23,7 @@ return [ ...@@ -23,7 +23,7 @@ return [
'name' => 'zuiektang-frontend', 'name' => 'zuiektang-frontend',
'class' => 'yii\redis\Session', 'class' => 'yii\redis\Session',
'redis' => [ 'redis' => [
'hostname' => 'localhost', 'hostname' => '192.168.1.185',
'port' => 6379, 'port' => 6379,
'database' => 0, 'database' => 0,
] ]
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace frontend\controllers; namespace frontend\controllers;
use common\libs\Geetest; use common\libs\Geetest;
use common\libs\Utils;
use common\models\User; use common\models\User;
use frontend\models\TokenInputForm; use frontend\models\TokenInputForm;
use Yii; use Yii;
...@@ -30,6 +31,9 @@ class SiteController extends Controller ...@@ -30,6 +31,9 @@ class SiteController extends Controller
const RESET_PASSWORD_THREE = 'rp_three'; const RESET_PASSWORD_THREE = 'rp_three';
const GT_SERVER = 'gt_server'; const GT_SERVER = 'gt_server';
const GT_USER_ID = 'gt_user_id'; const GT_USER_ID = 'gt_user_id';
const REDIS_SIGNUP_MSG_PREFIX = 'signup_msg';
const REDIS_SIGNUP_MSG_EXPIRE = 60;//second
const SIGNUP_TOKEN = 'sign_token';
/** /**
* @inheritdoc * @inheritdoc
...@@ -197,12 +201,24 @@ class SiteController extends Controller ...@@ -197,12 +201,24 @@ class SiteController extends Controller
* *
* @return mixed * @return mixed
*/ */
public public function actionRequestPasswordReset()
function actionRequestPasswordReset()
{ {
$model = new PasswordResetRequestForm(); $model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) { $request = Yii::$app->request;
if ($model->sendMsg()) { if ($model->load($request->post()) && $model->validate()) {
$geetestChallenge = $request->post('geetest_challenge');
$geetestSeccode = $request->post('geetest_seccode');
$geetestValidate = $request->post('geetest_validate');
$GtSdk = new Geetest(Yii::$app->params['captchaId'], Yii::$app->params['privateKey']);
$user_id = Yii::$app->session->get(self::GT_USER_ID);
if (Yii::$app->session->get(self::GT_SERVER) == 1) { //服务器正常
$gtResult = $GtSdk->success_validate($geetestChallenge, $geetestValidate, $geetestSeccode, $user_id);
} else { //服务器宕机,走failback模式
$gtResult = $GtSdk->fail_validate($geetestChallenge, $geetestValidate, $geetestSeccode);
}
if ($gtResult && $model->sendMsg()) {
Yii::$app->session->set(self::PASSWORD_RESET_KEY, $model->telephone); Yii::$app->session->set(self::PASSWORD_RESET_KEY, $model->telephone);
Yii::$app->session->set(self::RESET_PASSWORD_FIRST, TRUE); Yii::$app->session->set(self::RESET_PASSWORD_FIRST, TRUE);
return $this->redirect('token-input'); return $this->redirect('token-input');
...@@ -219,8 +235,7 @@ class SiteController extends Controller ...@@ -219,8 +235,7 @@ class SiteController extends Controller
/** /**
* @return mixed * @return mixed
*/ */
public public function actionTokenInput()
function actionTokenInput()
{ {
if (!Yii::$app->session->has(self::RESET_PASSWORD_FIRST)) { if (!Yii::$app->session->has(self::RESET_PASSWORD_FIRST)) {
$this->redirect('request-password-reset'); $this->redirect('request-password-reset');
...@@ -267,8 +282,7 @@ class SiteController extends Controller ...@@ -267,8 +282,7 @@ class SiteController extends Controller
* 密码设置成功 * 密码设置成功
* @return string * @return string
*/ */
public public function actionResetPasswordSuccess()
function actionResetPasswordSuccess()
{ {
if (!Yii::$app->session->has(self::RESET_PASSWORD_THREE)) { if (!Yii::$app->session->has(self::RESET_PASSWORD_THREE)) {
$this->redirect('request-password-reset'); $this->redirect('request-password-reset');
...@@ -300,4 +314,30 @@ class SiteController extends Controller ...@@ -300,4 +314,30 @@ class SiteController extends Controller
throw new \yii\web\ForbiddenHttpException('非法请求'); throw new \yii\web\ForbiddenHttpException('非法请求');
} }
} }
/**
* 发送注册短信
* ajax
* @throws \yii\web\ForbiddenHttpException
*/
public function actionSendSignupMsg()
{
if (TRUE || Yii::$app->request->isAjax) {
$key = self::REDIS_SIGNUP_MSG_PREFIX . '::' . Utils::getRealIP();
$redis = Yii::$app->redis;
$value = $redis->get($key);
if ($value === NULL) {
//sendMsg
$redis->setex($key, self::REDIS_SIGNUP_MSG_EXPIRE, 1);
$result = TRUE;
$msg = "";
} else {
$result = FALSE;
$msg = '一分钟只有一次';
}
Utils::ajaxResponse($result, $msg);
} else {
throw new \yii\web\ForbiddenHttpException('非法请求');
}
}
} }
...@@ -10,6 +10,7 @@ namespace frontend\controllers; ...@@ -10,6 +10,7 @@ namespace frontend\controllers;
use common\libs\Test; use common\libs\Test;
use common\models\User;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use yii\web\Controller; use yii\web\Controller;
use Yii; use Yii;
...@@ -29,7 +30,7 @@ class UserCenterController extends Controller ...@@ -29,7 +30,7 @@ class UserCenterController extends Controller
'rules' => [ 'rules' => [
[ [
'allow' => TRUE, 'allow' => TRUE,
'roles' => ['?'], 'roles' => ['@'],
], ],
], ],
], ],
...@@ -45,6 +46,8 @@ class UserCenterController extends Controller ...@@ -45,6 +46,8 @@ class UserCenterController extends Controller
public function actionIndex() public function actionIndex()
{ {
echo 'index'; echo 'index';
$user = User::findByTelephone2('15395081586');
print_r($user);
// echo Yii::$app->user->identity->role; // echo Yii::$app->user->identity->role;
} }
......
<?php <?php
namespace frontend\models; namespace frontend\models;
use common\libs\Utils;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use common\models\User; use common\models\User;
...@@ -46,7 +47,7 @@ class LoginForm extends Model ...@@ -46,7 +47,7 @@ class LoginForm extends Model
public function validatePassword($attribute, $params) public function validatePassword($attribute, $params)
{ {
$redis = Yii::$app->redis; $redis = Yii::$app->redis;
$key = self::REDIS_KEY_PREFIX . '::' . Yii::$app->request->getUserIP(); $key = self::REDIS_KEY_PREFIX . '::' . Utils::getRealIP();
$value = $redis->get($key); $value = $redis->get($key);
if ($value === NULL) { if ($value === NULL) {
$redis->setex($key, self::LOGIN_CYCLE, self::MAX_LOGIN_NUM); $redis->setex($key, self::LOGIN_CYCLE, self::MAX_LOGIN_NUM);
......
<?php <?php
namespace frontend\models; namespace frontend\models;
use common\libs\SendMsg;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use common\models\User; use common\models\User;
...@@ -53,6 +54,17 @@ class PasswordResetRequestForm extends Model ...@@ -53,6 +54,17 @@ class PasswordResetRequestForm extends Model
} }
//存储发送的手机号码 //存储发送的手机号码
//send_msg //send_msg
return TRUE; return TRUE;
} }
/**
* @return string
*/
public function formName()
{
return '';
}
} }
<?php <?php
namespace frontend\models; namespace frontend\models;
use common\libs\Utils;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use common\models\User; use common\models\User;
...@@ -57,7 +58,7 @@ class SignupForm extends Model ...@@ -57,7 +58,7 @@ class SignupForm extends Model
$user->generateAuthKey(); $user->generateAuthKey();
$user->logged_at = time(); $user->logged_at = time();
$user->avatar = ''; $user->avatar = '';
$user->ip = Yii::$app->request->getUserIP(); $user->ip = Utils::getRealIP();
if (!$user->save()) { if (!$user->save()) {
Yii::getLogger()->log($user->getErrors(), Logger::LEVEL_ERROR); Yii::getLogger()->log($user->getErrors(), Logger::LEVEL_ERROR);
$user = NULL; $user = NULL;
......
...@@ -9,6 +9,9 @@ use yii\bootstrap\ActiveForm; ...@@ -9,6 +9,9 @@ use yii\bootstrap\ActiveForm;
$this->title = 'Request password reset'; $this->title = 'Request password reset';
$this->params['breadcrumbs'][] = $this->title; $this->params['breadcrumbs'][] = $this->title;
\frontend\assets\AppAsset::addScript($this, '@web/assets/request_password_reset.js');
$this->registerJsFile('http://static.geetest.com/static/tools/gt.js');
?> ?>
<div class="site-request-password-reset"> <div class="site-request-password-reset">
<h1><?= Html::encode($this->title) ?></h1> <h1><?= Html::encode($this->title) ?></h1>
...@@ -21,6 +24,11 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -21,6 +24,11 @@ $this->params['breadcrumbs'][] = $this->title;
<?= $form->field($model, 'telephone')->textInput(['autofocus' => TRUE]) ?> <?= $form->field($model, 'telephone')->textInput(['autofocus' => TRUE]) ?>
<div style="margin-top: 20px;margin-bottom: 20px">
<div id="embed-captcha"></div>
<p id="wait" class="show">正在加载验证码......</p>
<p id="notice" class="hide">请先拖动验证码到相应位置</p>
</div>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton('Send', ['class' => 'btn btn-primary']) ?> <?= Html::submitButton('Send', ['class' => 'btn btn-primary']) ?>
</div> </div>
......
...@@ -29,9 +29,18 @@ $this->registerJsFile('http://static.geetest.com/static/tools/gt.js'); ...@@ -29,9 +29,18 @@ $this->registerJsFile('http://static.geetest.com/static/tools/gt.js');
<?= $form->field($model, 'rePassword')->passwordInput() ?> <?= $form->field($model, 'rePassword')->passwordInput() ?>
<label class="control-label" for="token">Token</label>
<input type="text" class="form-control" id="token">
<button class=""> send msg</button>
<div style="margin-top: 20px;margin-bottom: 20px">
<div id="embed-captcha"></div> <div id="embed-captcha"></div>
<p id="wait" class="show">正在加载验证码......</p> <p id="wait" class="show">正在加载验证码......</p>
<p id="notice" class="hide">请先拖动验证码到相应位置</p> <p id="notice" class="hide">请先拖动验证码到相应位置</p>
</div>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'id' => 'signup-button']) ?> <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'id' => 'signup-button']) ?>
......
This diff is collapsed.
webpackJsonp([2],[
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(3);
/***/ },
/* 1 */,
/* 2 */,
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function($) {var handlerEmbed = function (captchaObj) {
$("#signup-button").click(function (e) {
var validate = captchaObj.getValidate();
if (!validate) {
$("#notice")[0].className = "show";
setTimeout(function () {
$("#notice")[0].className = "hide";
}, 2000);
e.preventDefault();
}
});
// 将验证码加到id为captcha的元素里,同时会有三个input的值:geetest_challenge, geetest_validate, geetest_seccode
captchaObj.appendTo("#embed-captcha");
captchaObj.onReady(function () {
$("#wait")[0].className = "hide";
});
// 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
$.ajax({
// 获取id,challenge,success(是否启用failback)
url: ("http://dev.zuiketang.com/") + "site/start-captcha?type=pc&t=" + (new Date()).getTime(), // 加随机数防止缓存
type: "get",
dataType: "json",
success: function (data) {
// 使用initGeetest接口
// 参数1:配置参数
// 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
initGeetest({
gt: data.gt,
challenge: data.challenge,
product: "embed", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
// 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerEmbed);
}
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
/***/ }
]);
\ No newline at end of file
/**
* Created by xiabin on 2016/9/26.
*/
var handlerEmbed = function (captchaObj) {
$("#signup-button").click(function (e) {
var validate = captchaObj.getValidate();
if (!validate) {
$("#notice")[0].className = "show";
setTimeout(function () {
$("#notice")[0].className = "hide";
}, 2000);
e.preventDefault();
}
});
// 将验证码加到id为captcha的元素里,同时会有三个input的值:geetest_challenge, geetest_validate, geetest_seccode
captchaObj.appendTo("#embed-captcha");
captchaObj.onReady(function () {
$("#wait")[0].className = "hide";
});
// 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
$.ajax({
// 获取id,challenge,success(是否启用failback)
url: __BASE_URL__ + "site/start-captcha?type=pc&t=" + (new Date()).getTime(), // 加随机数防止缓存
type: "get",
dataType: "json",
success: function (data) {
// 使用initGeetest接口
// 参数1:配置参数
// 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
initGeetest({
gt: data.gt,
challenge: data.challenge,
product: "embed", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
// 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerEmbed);
}
});
var handlerEmbed = function (captchaObj) {
$("#signup-button").click(function (e) {
var validate = captchaObj.getValidate();
if (!validate) {
$("#notice")[0].className = "show";
setTimeout(function () {
$("#notice")[0].className = "hide";
}, 2000);
e.preventDefault();
}
});
// 将验证码加到id为captcha的元素里,同时会有三个input的值:geetest_challenge, geetest_validate, geetest_seccode
captchaObj.appendTo("#embed-captcha");
captchaObj.onReady(function () {
$("#wait")[0].className = "hide";
});
// 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
$.ajax({
// 获取id,challenge,success(是否启用failback)
url: __BASE_URL__ + "site/start-captcha?type=pc&t=" + (new Date()).getTime(), // 加随机数防止缓存
type: "get",
dataType: "json",
success: function (data) {
// 使用initGeetest接口
// 参数1:配置参数
// 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
initGeetest({
gt: data.gt,
challenge: data.challenge,
product: "embed", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
// 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerEmbed);
}
});
\ No newline at end of file
../.npminstall/cross-env/1.0.8/cross-env/bin/cross-env.js
\ No newline at end of file
../.npminstall/webpack/1.13.2/webpack/bin/webpack.js
\ No newline at end of file
Mon Sep 26 2016 10:33:26 GMT+0800 (CST)
\ No newline at end of file
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.11"
install: make setup
script: make test
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (c) 2011..2012 David Chambers <dc@hashify.me>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
ISTANBUL = node_modules/.bin/istanbul
UGLIFYJS = node_modules/.bin/uglifyjs
XYZ = node_modules/.bin/xyz --message X.Y.Z --tag X.Y.Z
SRC = base64.js
MIN = $(patsubst %.js,%.min.js,$(SRC))
.PHONY: all
all: $(MIN)
%.min.js: %.js
$(UGLIFYJS) $< --compress --mangle > $@
.PHONY: bytes
bytes: base64.min.js
gzip --best --stdout $< | wc -c | tr -d ' '
.PHONY: clean
clean:
rm -f -- $(MIN)
.PHONY: release-major release-minor release-patch
release-major:
$(XYZ) --increment major
release-minor:
$(XYZ) --increment minor
release-patch:
$(XYZ) --increment patch
.PHONY: setup
setup:
npm install
.PHONY: test
test:
$(ISTANBUL) cover node_modules/.bin/_mocha -- --compilers coffee:coffee-script/register
# Base64.js
≈ 500 byte* polyfill for browsers which don't provide [`window.btoa`][1] and
[`window.atob`][2].
Although the script does no harm in browsers which do provide these functions,
a conditional script loader such as [yepnope][3] can prevent unnecessary HTTP
requests.
```javascript
yepnope({
test: window.btoa && window.atob,
nope: 'base64.js',
callback: function () {
// `btoa` and `atob` are now safe to use
}
})
```
Base64.js stems from a [gist][4] by [yahiko][5].
### Running the test suite
make setup
make test
\* Minified and gzipped. Run `make bytes` to verify.
[1]: https://developer.mozilla.org/en/DOM/window.btoa
[2]: https://developer.mozilla.org/en/DOM/window.atob
[3]: http://yepnopejs.com/
[4]: https://gist.github.com/229984
[5]: https://github.com/yahiko
;(function () {
var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
// encoder
// [https://gist.github.com/999166] by [https://github.com/nignag]
object.btoa || (
object.btoa = function (input) {
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next input index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
input.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = input.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
});
// decoder
// [https://gist.github.com/1020396] by [https://github.com/atk]
object.atob || (
object.atob = function (input) {
input = input.replace(/=+$/, '');
if (input.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = input.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
});
}());
!function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=new Error,t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-a%1*8)){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),e.length%4==1)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(-2*a&6)):0)n=r.indexOf(n);return c})}();
\ No newline at end of file
{
"name": "Base64",
"version": "0.2.1",
"description": "Base64 encoding and decoding",
"author": "David Chambers <dc@davidchambers.me>",
"main": "./base64.js",
"licenses": [
{
"type": "WTFPL",
"url": "https://raw.github.com/davidchambers/Base64.js/master/LICENSE"
}
],
"repository": {
"type": "git",
"url": "git://github.com/davidchambers/Base64.js.git"
},
"devDependencies": {
"coffee-script": "1.7.x",
"istanbul": "0.2.x",
"mocha": "1.18.x",
"uglify-js": "2.4.x",
"xyz": "0.1.x"
},
"_from": "Base64@0.2.1",
"_resolved": "http://registry.npm.taobao.org/Base64/download/Base64-0.2.1.tgz"
}
\ No newline at end of file
assert = require 'assert'
{btoa, atob} = require '..'
describe 'Base64.js', ->
it 'can encode ASCII input', ->
assert.strictEqual btoa(''), ''
assert.strictEqual btoa('f'), 'Zg=='
assert.strictEqual btoa('fo'), 'Zm8='
assert.strictEqual btoa('foo'), 'Zm9v'
assert.strictEqual btoa('quux'), 'cXV1eA=='
assert.strictEqual btoa('!"#$%'), 'ISIjJCU='
assert.strictEqual btoa("&'()*+"), 'JicoKSor'
assert.strictEqual btoa(',-./012'), 'LC0uLzAxMg=='
assert.strictEqual btoa('3456789:'), 'MzQ1Njc4OTo='
assert.strictEqual btoa(';<=>?@ABC'), 'Ozw9Pj9AQUJD'
assert.strictEqual btoa('DEFGHIJKLM'), 'REVGR0hJSktMTQ=='
assert.strictEqual btoa('NOPQRSTUVWX'), 'Tk9QUVJTVFVWV1g='
assert.strictEqual btoa('YZ[\\]^_`abc'), 'WVpbXF1eX2BhYmM='
assert.strictEqual btoa('defghijklmnop'), 'ZGVmZ2hpamtsbW5vcA=='
assert.strictEqual btoa('qrstuvwxyz{|}~'), 'cXJzdHV2d3h5ent8fX4='
it 'cannot encode non-ASCII input', ->
assert.throws (-> btoa '✈'), (err) ->
err instanceof Error and
err.name is 'InvalidCharacterError' and
err.message is "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."
it 'can decode Base64-encoded input', ->
assert.strictEqual atob(''), ''
assert.strictEqual atob('Zg=='), 'f'
assert.strictEqual atob('Zm8='), 'fo'
assert.strictEqual atob('Zm9v'), 'foo'
assert.strictEqual atob('cXV1eA=='), 'quux'
assert.strictEqual atob('ISIjJCU='), '!"#$%'
assert.strictEqual atob('JicoKSor'), "&'()*+"
assert.strictEqual atob('LC0uLzAxMg=='), ',-./012'
assert.strictEqual atob('MzQ1Njc4OTo='), '3456789:'
assert.strictEqual atob('Ozw9Pj9AQUJD'), ';<=>?@ABC'
assert.strictEqual atob('REVGR0hJSktMTQ=='), 'DEFGHIJKLM'
assert.strictEqual atob('Tk9QUVJTVFVWV1g='), 'NOPQRSTUVWX'
assert.strictEqual atob('WVpbXF1eX2BhYmM='), 'YZ[\\]^_`abc'
assert.strictEqual atob('ZGVmZ2hpamtsbW5vcA=='), 'defghijklmnop'
assert.strictEqual atob('cXJzdHV2d3h5ent8fX4='), 'qrstuvwxyz{|}~'
it 'cannot decode invalid input', ->
assert.throws (-> atob 'a'), (err) ->
err instanceof Error and
err.name is 'InvalidCharacterError' and
err.message is "'atob' failed: The string to be decoded is not correctly encoded."
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
Mon Sep 26 2016 10:33:23 GMT+0800 (CST)
\ No newline at end of file
List of Acorn contributors. Updated before every release.
Adrian Rakovsky
Alistair Braidwood
Andres Suarez
Aparajita Fishman
Arian Stolwijk
Artem Govorov
Brandon Mills
Charles Hughes
Conrad Irwin
David Bonnet
Forbes Lindesay
Gilad Peleg
impinball
Ingvar Stepanyan
Jiaxing Wang
Johannes Herr
Jürg Lehni
keeyipchan
krator
Marijn Haverbeke
Martin Carlberg
Mathias Bynens
Mathieu 'p01' Henri
Max Schaefer
Max Zerzouri
Mihai Bazon
Mike Rennie
Nick Fitzgerald
Oskar Schöldström
Paul Harper
Peter Rust
PlNG
r-e-d
Rich Harris
Sebastian McKenzie
zsjforcn
Copyright (C) 2012-2014 by various contributors (see AUTHORS)
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.
#!/usr/bin/env node
var path = require("path");
var fs = require("fs");
var acorn = require("../dist/acorn.js");
var infile, parsed, tokens, options = {}, silent = false, compact = false, tokenize = false;
function help(status) {
var print = (status == 0) ? console.log : console.error;
print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6]");
print(" [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--help] [--] infile");
process.exit(status);
}
for (var i = 2; i < process.argv.length; ++i) {
var arg = process.argv[i];
if (arg[0] != "-" && !infile) infile = arg;
else if (arg == "--" && !infile && i + 2 == process.argv.length) infile = process.argv[++i];
else if (arg == "--ecma3") options.ecmaVersion = 3;
else if (arg == "--ecma5") options.ecmaVersion = 5;
else if (arg == "--ecma6") options.ecmaVersion = 6;
else if (arg == "--ecma7") options.ecmaVersion = 7;
else if (arg == "--locations") options.locations = true;
else if (arg == "--allow-hash-bang") options.allowHashBang = true;
else if (arg == "--silent") silent = true;
else if (arg == "--compact") compact = true;
else if (arg == "--help") help(0);
else if (arg == "--tokenize") tokenize = true;
else help(1);
}
try {
var code = fs.readFileSync(infile, "utf8");
if (!tokenize)
parsed = acorn.parse(code, options);
else {
var get = acorn.tokenize(code, options);
tokens = [];
while (true) {
var token = get();
tokens.push(token);
if (token.type.type == "eof")
break;
}
}
} catch(e) {
console.log(e.message);
process.exit(1);
}
if (!silent)
console.log(JSON.stringify(tokenize ? tokens : parsed, null, compact ? null : 2));
var fs = require("fs"), path = require("path")
var stream = require("stream")
var browserify = require("browserify")
var babelify = require("babelify").configure({loose: "all"})
process.chdir(path.resolve(__dirname, ".."))
browserify({standalone: "acorn"})
.plugin(require('browserify-derequire'))
.transform(babelify)
.require("./src/index.js", {entry: true})
.bundle()
.on("error", function (err) { console.log("Error: " + err.message) })
.pipe(fs.createWriteStream("dist/acorn.js"))
function acornShim(file) {
var tr = new stream.Transform
if (file == path.resolve(__dirname, "../src/index.js")) {
var sent = false
tr._transform = function(chunk, _, callback) {
if (!sent) {
sent = true
callback(null, "module.exports = typeof acorn != 'undefined' ? acorn : _dereq_(\"./acorn\")")
} else {
callback()
}
}
} else {
tr._transform = function(chunk, _, callback) { callback(null, chunk) }
}
return tr
}
browserify({standalone: "acorn.loose"})
.plugin(require('browserify-derequire'))
.transform(acornShim)
.transform(babelify)
.require("./src/loose/index.js", {entry: true})
.bundle()
.on("error", function (err) { console.log("Error: " + err.message) })
.pipe(fs.createWriteStream("dist/acorn_loose.js"))
browserify({standalone: "acorn.walk"})
.plugin(require('browserify-derequire'))
.transform(acornShim)
.transform(babelify)
.require("./src/walk/index.js", {entry: true})
.bundle()
.on("error", function (err) { console.log("Error: " + err.message) })
.pipe(fs.createWriteStream("dist/walk.js"))
// Note: run `npm install unicode-7.0.0` first.
// Which Unicode version should be used?
var version = '7.0.0';
var start = require('unicode-' + version + '/properties/ID_Start/code-points')
.filter(function(ch) { return ch > 127; });
var cont = [0x200c, 0x200d].concat(require('unicode-' + version + '/properties/ID_Continue/code-points')
.filter(function(ch) { return ch > 127 && start.indexOf(ch) == -1; }));
function pad(str, width) {
while (str.length < width) str = "0" + str;
return str;
}
function esc(code) {
var hex = code.toString(16);
if (hex.length <= 2) return "\\x" + pad(hex, 2);
else return "\\u" + pad(hex, 4);
}
function generate(chars) {
var astral = [], re = "";
for (var i = 0, at = 0x10000; i < chars.length; i++) {
var from = chars[i], to = from;
while (i < chars.length - 1 && chars[i + 1] == to + 1) {
i++;
to++;
}
if (to <= 0xffff) {
if (from == to) re += esc(from);
else if (from + 1 == to) re += esc(from) + esc(to);
else re += esc(from) + "-" + esc(to);
} else {
astral.push(from - at, to - from);
at = to;
}
}
return {nonASCII: re, astral: astral};
}
var startData = generate(start), contData = generate(cont);
console.log(" var nonASCIIidentifierStartChars = \"" + startData.nonASCII + "\";");
console.log(" var nonASCIIidentifierChars = \"" + contData.nonASCII + "\";");
console.log(" var astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";");
console.log(" var astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";");
node bin/build-acorn.js
node bin/without_eval > dist/acorn_csp.js
# Combine existing list of authors with everyone known in git, sort, add header.
tail --lines=+3 AUTHORS > AUTHORS.tmp
git log --format='%aN' | grep -v abraidwood >> AUTHORS.tmp
echo -e "List of Acorn contributors. Updated before every release.\n" > AUTHORS
sort -u AUTHORS.tmp >> AUTHORS
rm -f AUTHORS.tmp
#!/usr/bin/env node
var fs = require("fs")
var acornSrc = fs.readFileSync(require.resolve("../dist/acorn"), "utf8")
var acorn = require("../dist/acorn"), walk = require("../dist/walk")
var ast = acorn.parse(acornSrc)
var touchups = [], uses = []
var makePred
walk.simple(ast, {
FunctionDeclaration: function(node) {
if (node.id.name == "makePredicate") {
makePred = node
touchups.push({text: "// Removed to create an eval-free library", from: node.start, to: node.end})
}
},
ObjectExpression: function(node) {
node.properties.forEach(function(prop) {
if (prop.value.type == "CallExpression" &&
prop.value.callee.name == "makePredicate")
uses.push(prop.value)
})
}
})
var results = []
var dryRun = acornSrc.slice(0, makePred.end) + "; makePredicate = (function(mp) {" +
"return function(words) { var r = mp(words); predicates.push(r); return r }})(makePredicate);" +
acornSrc.slice(makePred.end)
;(new Function("predicates", dryRun))(results)
uses.forEach(function (node, i) {
touchups.push({text: results[i].toString(), from: node.start, to: node.end})
})
var result = "", pos = 0
touchups.sort(function(a, b) { return a.from - b.from })
touchups.forEach(function(touchup) {
result += acornSrc.slice(pos, touchup.from)
result += touchup.text
pos = touchup.to
})
result += acornSrc.slice(pos)
process.stdout.write(result)
{
"name": "acorn",
"description": "ECMAScript parser",
"homepage": "https://github.com/marijnh/acorn",
"main": "dist/acorn.js",
"version": "1.2.2",
"engines": {
"node": ">=0.4.0"
},
"maintainers": [
{
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"web": "http://marijnhaverbeke.nl"
},
{
"name": "Ingvar Stepanyan",
"email": "me@rreverser.com",
"web": "http://rreverser.com/"
}
],
"repository": {
"type": "git",
"url": "https://github.com/marijnh/acorn.git"
},
"license": "MIT",
"scripts": {
"test": "node test/run.js",
"prepublish": "bin/prepublish.sh"
},
"bin": {
"acorn": "./bin/acorn"
},
"devDependencies": {
"babelify": "^5.0.4",
"browserify": "^9.0.3",
"browserify-derequire": "^0.9.4",
"unicode-7.0.0": "~0.1.5"
},
"_from": "acorn@1.2.2",
"_resolved": "http://registry.npm.taobao.org/acorn/download/acorn-1.2.2.tgz"
}
\ No newline at end of file
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/marijnh/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/marijnh/acorn/issues
//
// This file defines the main parser interface. The library also comes
// with a [error-tolerant parser][dammit] and an
// [abstract syntax tree walker][walk], defined in other files.
//
// [dammit]: acorn_loose.js
// [walk]: util/walk.js
import {Parser} from "./state"
import {getOptions} from "./options"
import "./parseutil"
import "./statement"
import "./lval"
import "./expression"
export {Parser, plugins} from "./state"
export {defaultOptions} from "./options"
export {SourceLocation} from "./location"
export {getLineInfo} from "./location"
export {Node} from "./node"
export {TokenType, types as tokTypes} from "./tokentype"
export {TokContext, types as tokContexts} from "./tokencontext"
export {isIdentifierChar, isIdentifierStart} from "./identifier"
export {Token} from "./tokenize"
export {isNewLine, lineBreak, lineBreakG} from "./whitespace"
export const version = "1.2.2"
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
export function parse(input, options) {
let p = parser(options, input)
let startPos = p.pos, startLoc = p.options.locations && p.curPosition()
p.nextToken()
return p.parseTopLevel(p.options.program || p.startNodeAt(startPos, startLoc))
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
export function parseExpressionAt(input, pos, options) {
let p = parser(options, input, pos)
p.nextToken()
return p.parseExpression()
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenize` export provides an interface to the tokenizer.
export function tokenizer(input, options) {
return parser(options, input)
}
function parser(options, input) {
return new Parser(getOptions(options), String(input))
}
import {Parser} from "./state"
import {lineBreakG} from "./whitespace"
import {deprecate} from "util"
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
export class Position {
constructor(line, col) {
this.line = line
this.column = col
}
offset(n) {
return new Position(this.line, this.column + n)
}
}
export class SourceLocation {
constructor(p, start, end) {
this.start = start
this.end = end
if (p.sourceFile !== null) this.source = p.sourceFile
}
}
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
export function getLineInfo(input, offset) {
for (let line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur
let match = lineBreakG.exec(input)
if (match && match.index < offset) {
++line
cur = match.index + match[0].length
} else {
return new Position(line, offset - cur)
}
}
}
const pp = Parser.prototype
// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.
pp.raise = function(pos, message) {
let loc = getLineInfo(this.input, pos)
message += " (" + loc.line + ":" + loc.column + ")"
let err = new SyntaxError(message)
err.pos = pos; err.loc = loc; err.raisedAt = this.pos
throw err
}
pp.curPosition = function() {
return new Position(this.curLine, this.pos - this.lineStart)
}
pp.markPosition = function() {
return this.options.locations ? [this.start, this.startLoc] : this.start
}
// Acorn: Loose parser
//
// This module provides an alternative parser (`parse_dammit`) that
// exposes that same interface as `parse`, but will try to parse
// anything as JavaScript, repairing syntax error the best it can.
// There are circumstances in which it will raise an error and give
// up, but they are very rare. The resulting AST will be a mostly
// valid JavaScript AST (as per the [Mozilla parser API][api], except
// that:
//
// - Return outside functions is allowed
//
// - Label consistency (no conflicts, break only to existing labels)
// is not enforced.
//
// - Bogus Identifier nodes with a name of `"✖"` are inserted whenever
// the parser got too confused to return anything meaningful.
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
//
// The expected use for this is to *first* try `acorn.parse`, and only
// if that fails switch to `parse_dammit`. The loose parser might
// parse badly indented code incorrectly, so **don't** use it as
// your default parser.
//
// Quite a lot of acorn.js is duplicated here. The alternative was to
// add a *lot* of extra cruft to that file, making it less readable
// and slower. Copying and editing the code allowed me to make
// invasive changes and simplifications without creating a complicated
// tangle.
import * as acorn from ".."
import {LooseParser} from "./state"
import "./tokenize"
import "./parseutil"
import "./statement"
import "./expression"
export {LooseParser} from "./state"
acorn.defaultOptions.tabSize = 4
export function parse_dammit(input, options) {
let p = new LooseParser(input, options)
p.next()
return p.parseTopLevel()
}
acorn.parse_dammit = parse_dammit
acorn.LooseParser = LooseParser
import {LooseParser} from "./state"
import {Node, SourceLocation, lineBreak, isNewLine, tokTypes as tt} from ".."
const lp = LooseParser.prototype
lp.startNode = function() {
let node = new Node
node.start = this.tok.start
if (this.options.locations)
node.loc = new SourceLocation(this.toks, this.tok.loc.start)
if (this.options.directSourceFile)
node.sourceFile = this.options.directSourceFile
if (this.options.ranges)
node.range = [this.tok.start, 0]
return node
}
lp.storeCurrentPos = function() {
return this.options.locations ? [this.tok.start, this.tok.loc.start] : this.tok.start
}
lp.startNodeAt = function(pos) {
let node = new Node
if (this.options.locations) {
node.start = pos[0]
node.loc = new SourceLocation(this.toks, pos[1])
pos = pos[0]
} else {
node.start = pos
}
if (this.options.directSourceFile)
node.sourceFile = this.options.directSourceFile
if (this.options.ranges)
node.range = [pos, 0]
return node
}
lp.finishNode = function(node, type) {
node.type = type
node.end = this.last.end
if (this.options.locations)
node.loc.end = this.last.loc.end
if (this.options.ranges)
node.range[1] = this.last.end
return node
}
lp.dummyIdent = function() {
let dummy = this.startNode()
dummy.name = "✖"
return this.finishNode(dummy, "Identifier")
}
export function isDummy(node) { return node.name == "✖" }
lp.eat = function(type) {
if (this.tok.type === type) {
this.next()
return true
} else {
return false
}
}
lp.isContextual = function(name) {
return this.tok.type === tt.name && this.tok.value === name
}
lp.eatContextual = function(name) {
return this.tok.value === name && this.eat(tt.name)
}
lp.canInsertSemicolon = function() {
return this.tok.type === tt.eof || this.tok.type === tt.braceR ||
lineBreak.test(this.input.slice(this.last.end, this.tok.start))
}
lp.semicolon = function() {
return this.eat(tt.semi)
}
lp.expect = function(type) {
if (this.eat(type)) return true
for (let i = 1; i <= 2; i++) {
if (this.lookAhead(i).type == type) {
for (let j = 0; j < i; j++) this.next()
return true
}
}
}
lp.pushCx = function() {
this.context.push(this.curIndent)
}
lp.popCx = function() {
this.curIndent = this.context.pop()
}
lp.lineEnd = function(pos) {
while (pos < this.input.length && !isNewLine(this.input.charCodeAt(pos))) ++pos
return pos
}
lp.indentationAfter = function(pos) {
for (let count = 0;; ++pos) {
let ch = this.input.charCodeAt(pos)
if (ch === 32) ++count
else if (ch === 9) count += this.options.tabSize
else return count
}
}
lp.closes = function(closeTok, indent, line, blockHeuristic) {
if (this.tok.type === closeTok || this.tok.type === tt.eof) return true
return line != this.curLineStart && this.curIndent < indent && this.tokenStartsLine() &&
(!blockHeuristic || this.nextLineStart >= this.input.length ||
this.indentationAfter(this.nextLineStart) < indent)
}
lp.tokenStartsLine = function() {
for (let p = this.tok.start - 1; p >= this.curLineStart; --p) {
let ch = this.input.charCodeAt(p)
if (ch !== 9 && ch !== 32) return false
}
return true
}
import {tokenizer, SourceLocation, tokTypes as tt} from ".."
export function LooseParser(input, options) {
this.toks = tokenizer(input, options)
this.options = this.toks.options
this.input = this.toks.input
this.tok = this.last = {type: tt.eof, start: 0, end: 0}
if (this.options.locations) {
let here = this.toks.curPosition()
this.tok.loc = new SourceLocation(this.toks, here, here)
}
this.ahead = []; // Tokens ahead
this.context = []; // Indentation contexted
this.curIndent = 0
this.curLineStart = 0
this.nextLineStart = this.lineEnd(this.curLineStart) + 1
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment