├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.cjs ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE └── workflows │ └── ci.yml ├── .gitignore ├── .husky ├── commit-msg └── pre-commit ├── .lintstagedrc.cjs ├── .nycrc ├── .prettierignore ├── .prettierrc.json ├── .vscode ├── extensions.json └── settings.json ├── CHANGELOG.md ├── LICENSE ├── README-zh_CN.md ├── README.md ├── TODO.md ├── commitlint.config.js ├── config ├── rollup.cjs ├── rollup.config.aio.cjs ├── rollup.config.cjs └── rollup.config.esm.cjs ├── demo ├── demo-amd.html ├── demo-global.html ├── demo-node.js └── js │ └── require.js ├── doc └── api.md ├── index.d.ts ├── jslib.json ├── package-lock.json ├── package.json ├── src └── index.js └── test ├── browser └── index.html └── test.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "targets": { 7 | "browsers": "last 2 versions, > 1%, ie >= 11, Android >= 4.1, iOS >= 10.3", 8 | "node": "14" 9 | }, 10 | "modules": "commonjs", 11 | "loose": false 12 | } 13 | ] 14 | ], 15 | "plugins": [ 16 | // [ 17 | // "@babel/plugin-transform-runtime", 18 | // { 19 | // "corejs": 3, 20 | // "versions": "^7.22.15", 21 | // "helpers": true, 22 | // "regenerator": false 23 | // } 24 | // ] 25 | ], 26 | "env": { 27 | "test": { 28 | "plugins": ["istanbul"] 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # 根目录的配置 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | indent_style = space 9 | indent_size = 4 10 | 11 | [*.html] 12 | indent_size = 2 13 | 14 | [*.{css,less,scss}] 15 | indent_size = 2 16 | 17 | [*.{js,mjs,cjs,ts,cts,mts}] 18 | indent_size = 2 19 | 20 | [*.{json,yml,yaml}] 21 | indent_size = 2 22 | 23 | [*.{sh}] 24 | indent_size = 2 25 | 26 | [*.{md,makrdown}] 27 | indent_size = 2 28 | 29 | [*rc] 30 | indent_size = 2 31 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | require.js 3 | *.ts 4 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@babel/eslint-parser', 3 | env: { 4 | browser: true, 5 | es2021: true, 6 | node: true, 7 | mocha: true, 8 | }, 9 | parserOptions: { 10 | ecmaVersion: 'latest', 11 | sourceType: 'module', 12 | // 即使没有 babelrc 配置文件,也使用 babel-eslint 来解析 13 | requireConfigFile: false, 14 | }, 15 | extends: [ 16 | 'eslint:recommended', 17 | 'plugin:prettier/recommended', 18 | 'plugin:import/recommended', 19 | ], 20 | rules: { 21 | 'no-unused-vars': [ 22 | 2, 23 | { 24 | vars: 'local', 25 | args: 'after-used', 26 | ignoreRestSiblings: true, 27 | varsIgnorePattern: '^_', 28 | argsIgnorePattern: '^_', 29 | }, 30 | ], 31 | eqeqeq: [2], 32 | 'import/no-unresolved': [1], 33 | }, 34 | }; 35 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | custom: ['https://yanhaijing.com/mywallet/'] 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE: -------------------------------------------------------------------------------- 1 | ### 问题是什么 2 | 问题的具体描述,尽量详细 3 | 4 | ### 环境 5 | - 手机: 小米6 6 | - 系统:安卓7.1.1 7 | - 浏览器:chrome 61 8 | - 使用的版本:0.2.0 9 | - 其他版本信息 10 | 11 | ### 在线例子 12 | 如果有请提供在线例子 13 | 14 | ### 其他 15 | 其他信息 16 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs 3 | 4 | name: CI 5 | 6 | on: 7 | push: 8 | branches: ['master'] 9 | pull_request: 10 | branches: ['master'] 11 | 12 | jobs: 13 | commitlint: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v3 17 | with: 18 | fetch-depth: 0 19 | - uses: wagoid/commitlint-github-action@v4 20 | 21 | lint: 22 | needs: commitlint 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v3 26 | - name: Use Node.js 18.x 27 | uses: actions/setup-node@v3 28 | with: 29 | node-version: '18.x' 30 | cache: 'npm' 31 | - run: npm ci 32 | - run: npm run lint 33 | 34 | test: 35 | needs: lint 36 | runs-on: ubuntu-latest 37 | strategy: 38 | matrix: 39 | node-version: [14.x, 16.x, 18.x, 20.x] 40 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 41 | steps: 42 | - uses: actions/checkout@v3 43 | - name: Use Node.js ${{ matrix.node-version }} 44 | uses: actions/setup-node@v3 45 | with: 46 | node-version: ${{ matrix.node-version }} 47 | cache: 'npm' 48 | - run: npm i 49 | - run: npm test 50 | # - run: npm run coveralls --if-present 51 | - run: npm run build --if-present 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | coverage 2 | node_modules 3 | dist 4 | .eslintcache 5 | .nyc_output -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx --no -- commitlint --edit "$1" 5 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx lint-staged 5 | -------------------------------------------------------------------------------- /.lintstagedrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | '**/*.{js,mjs,cjs,ts,cts,mts}': ['prettier --write', 'eslint --cache'], 3 | }; 4 | -------------------------------------------------------------------------------- /.nycrc: -------------------------------------------------------------------------------- 1 | { 2 | "check-coverage": true, 3 | "lines": 75, 4 | "statements": 75, 5 | "functions": 0, 6 | "branches": 50, 7 | "reporter": ["lcov", "text"], 8 | "require": ["@babel/register"], 9 | "sourceMap": false, 10 | "instrument": false 11 | } 12 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | coverage 3 | package-lock.json 4 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.defaultFormatter": "esbenp.prettier-vscode" 4 | } 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 变更日志 2 | 3 | ## 0.4.0 / 2023-11-19 4 | 5 | - 升级 jslib-base 2.3.2 6 | - 支持 sourceMap 7 | - fix: 支持 node >=14.0.0 8 | 9 | ## 0.3.0 / 2023-9-24 10 | 11 | - 升级最新版 jslib-base 12 | - 支持 Node.js ESM 13 | - 升级 @jsmini/is 14 | - 升级 @jsmini/event 15 | 16 | ## 0.2.3 / 2019-10-10 17 | 18 | - fix: 修复丢失d.ts的问题 19 | 20 | ## 0.2.1 / 2019-3-4 21 | 22 | - fix: 修复依赖不自动更新的问题 23 | 24 | ## 0.2.0 / 2019-3-2 25 | 26 | - 增加.d.ts文件,支持ts调用 27 | 28 | ## 0.1.0 / 2018-10-18 29 | 30 | - 添加 `PubSub` 31 | - 添加 `subscribe` 32 | - 添加 `unsubscribe` 33 | - 添加 `publish` 34 | - 添加 `sub` 35 | - 添加 `unsub` 36 | - 添加 `pub` 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2017-2023 yanhaijing 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | -------------------------------------------------------------------------------- /README-zh_CN.md: -------------------------------------------------------------------------------- 1 | # [pubsub](https://github.com/jsmini/pubsub) 2 | 3 | [![](https://img.shields.io/badge/Powered%20by-jslib%20pubsub-brightgreen.svg)](https://github.com/yanhaijing/jslib-pubsub) 4 | [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jsmini/pubsub/blob/master/LICENSE) 5 | [![CI](https://github.com/jsmini/pubsub/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/jsmini/pubsub/actions/workflows/ci.yml) 6 | [![npm](https://img.shields.io/badge/npm-0.4.0-orange.svg)](https://www.npmjs.com/package/@jsmini/pubsub) 7 | [![NPM downloads](http://img.shields.io/npm/dm/@jsmini/pubsub.svg?style=flat-square)](http://www.npmtrends.com/@jsmini/pubsub) 8 | [![Percentage of issues still open](http://isitmaintained.com/badge/open/jsmini/pubsub.svg)](http://isitmaintained.com/project/jsmini/pubsub 'Percentage of issues still open') 9 | 10 | 小而美的pubsub库,发布订阅者模式 11 | 12 | [English](./README.md) | 简体中文 13 | 14 | ## 兼容性 15 | 16 | 单元测试保证支持如下环境: 17 | 18 | | IE | CH | FF | SF | OP | IOS | 安卓 | Node | 19 | | --- | --- | --- | --- | --- | --- | ---- | ----- | 20 | | 6+ | 23+ | 4+ | 6+ | 10+ | 5+ | 2.3+ | 0.10+ | 21 | 22 | **注意:编译代码依赖ES5环境,对于ie6-8需要引入[es5-shim](http://github.com/es-shims/es5-shim/)才可以兼容,可以查看[demo/demo-global.html](./demo/demo-global.html)中的例子** 23 | 24 | ## 目录介绍 25 | 26 | ``` 27 | . 28 | ├── demo 使用demo 29 | ├── dist 编译产出代码 30 | ├── doc 项目文档 31 | ├── src 源代码目录 32 | ├── test 单元测试 33 | ├── CHANGELOG.md 变更日志 34 | └── TODO.md 计划功能 35 | ``` 36 | 37 | ## 如何使用 38 | 39 | 通过npm下载安装代码 40 | 41 | ```bash 42 | $ npm install --save @jsmini/pubsub 43 | ``` 44 | 45 | 如果你是node环境 46 | 47 | ```js 48 | var name = require('@jsmini/pubsub').name; 49 | ``` 50 | 51 | 如果你是webpack等环境 52 | 53 | ```js 54 | import { name } from '@jsmini/pubsub'; 55 | ``` 56 | 57 | 如果你是requirejs环境 58 | 59 | ```js 60 | requirejs( 61 | ['node_modules/@jsmini/pubsub/dist/index.aio.js'], 62 | function (jsmini_pubsub) { 63 | var name = jsmini_pubsub.name; 64 | }, 65 | ); 66 | ``` 67 | 68 | 如果你是浏览器环境 69 | 70 | ```html 71 | 72 | 73 | 76 | ``` 77 | 78 | ## 文档 79 | 80 | [API](https://github.com/jsmini/pubsub/blob/master/doc/api.md) 81 | 82 | ## 贡献指南 ![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) 83 | 84 | 首次运行需要先安装依赖 85 | 86 | ```bash 87 | $ npm install 88 | ``` 89 | 90 | 一键打包生成生产代码 91 | 92 | ```bash 93 | $ npm run build 94 | ``` 95 | 96 | 运行单元测试,浏览器环境需要手动测试,位于`test/browser` 97 | 98 | ```bash 99 | $ npm test 100 | ``` 101 | 102 | 修改package.json中的版本号,修改README.md中的版本号,修改CHANGELOG.md,然后发布新版 103 | 104 | ```bash 105 | $ npm run release 106 | ``` 107 | 108 | 将新版本发布到npm 109 | 110 | ```bash 111 | $ npm publish --access=public 112 | ``` 113 | 114 | 重命名项目名称,首次初始化项目是需要修改名字,或者后面项目要改名时使用,需要修改`rename.js`中的`fromName`和`toName`,会自动重命名下面文件中的名字 115 | 116 | - README.md 中的信息 117 | - package.json 中的信息 118 | - config/rollup.js 中的信息 119 | - test/browser/index.html 中的仓库名称 120 | 121 | ```bash 122 | $ npm run rename # 重命名命令 123 | ``` 124 | 125 | ## 贡献者列表 126 | 127 | [contributors](https://github.com/jsmini/pubsub/graphs/contributors) 128 | 129 | ## 更新日志 130 | 131 | [CHANGELOG.md](https://github.com/jsmini/pubsub/blob/master/CHANGELOG.md) 132 | 133 | ## 计划列表 134 | 135 | [TODO.md](https://github.com/jsmini/pubsub/blob/master/TODO.md) 136 | 137 | ## 谁在使用 138 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [pubsub](https://github.com/jsmini/pubsub) 2 | 3 | [![](https://img.shields.io/badge/Powered%20by-jslib%20pubsub-brightgreen.svg)](https://github.com/yanhaijing/jslib-pubsub) 4 | [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jsmini/pubsub/blob/master/LICENSE) 5 | [![CI](https://github.com/jsmini/pubsub/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/jsmini/pubsub/actions/workflows/ci.yml) 6 | [![npm](https://img.shields.io/badge/npm-0.4.0-orange.svg)](https://www.npmjs.com/package/@jsmini/pubsub) 7 | [![NPM downloads](http://img.shields.io/npm/dm/@jsmini/pubsub.svg?style=flat-square)](http://www.npmtrends.com/@jsmini/pubsub) 8 | [![Percentage of issues still open](http://isitmaintained.com/badge/open/jsmini/pubsub.svg)](http://isitmaintained.com/project/jsmini/pubsub 'Percentage of issues still open') 9 | 10 | A small yet beautiful PubSub library, implementing the Publisher-Subscriber pattern. 11 | 12 | English | [简体中文](./README-zh_CN.md) 13 | 14 | ## Environment Support 15 | 16 | unit test ensure it supports the following environments. 17 | 18 | | IE/Edge | Chrome | Firefox | Safari | Opera | IOS | Android | Node | 19 | | ------- | ------ | ------- | ------ | ----- | --- | ------- | ----- | 20 | | 6+ | 23+ | 4+ | 6+ | 10+ | 5+ | 2.3+ | 0.10+ | 21 | 22 | **Notice: builds depends on ES5. In order to support IE6-8, you should import [es5-shim](http://github.com/es-shims/es5-shim/) . See example in [demo/demo-global.html](./demo/demo-global.html)** 23 | 24 | ## Directory 25 | 26 | ``` 27 | . 28 | ├── demo 29 | ├── dist # production code 30 | ├── doc # document 31 | ├── src # source code 32 | ├── test # unit test 33 | ├── CHANGELOG.md 34 | └── TODO.md 35 | ``` 36 | 37 | ## Usage 38 | 39 | npm installation 40 | 41 | ```bash 42 | $ npm install --save @jsmini/pubsub 43 | ``` 44 | 45 | Node.js 46 | 47 | ```js 48 | var name = require('@jsmini/pubsub').name; 49 | ``` 50 | 51 | webpack 52 | 53 | ```js 54 | import { name } from '@jsmini/pubsub'; 55 | ``` 56 | 57 | Require.js 58 | 59 | ```js 60 | requirejs( 61 | ['node_modules/@jsmini/pubsub/dist/index.aio.js'], 62 | function (jsmini_pubsub) { 63 | var name = jsmini_pubsub.name; 64 | }, 65 | ); 66 | ``` 67 | 68 | Browser 69 | 70 | ```html 71 | 72 | 73 | 76 | ``` 77 | 78 | ## Document 79 | 80 | [API](https://github.com/jsmini/pubsub/blob/master/doc/api.md) 81 | 82 | ## Contributing Guide ![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) 83 | 84 | when initialize, install dependencies 85 | 86 | ```bash 87 | $ npm install 88 | ``` 89 | 90 | builds your code for production to `build` folder 91 | 92 | ```bash 93 | $ npm run build 94 | ``` 95 | 96 | run unit test. notice: borwser enviroment need to test manually. test file is in `test/browser` 97 | 98 | ```bash 99 | $ npm test 100 | ``` 101 | 102 | change the version in package.json and README.md, add your description in CHANGELOG.md, and then release it happily. 103 | 104 | ```bash 105 | $ npm run release 106 | ``` 107 | 108 | publish the new package to npm 109 | 110 | ```bash 111 | $ npm publish --access=public 112 | ``` 113 | 114 | rename project. you need to edit project name when initialize project or anytime you want to rename the project . you need to rename `formName` and `toname` in file `rename.js`,which will automatically rename project name in the following files 115 | 116 | - README.md 117 | - package.json 118 | - config/rollup.js 119 | - test/browser/index.html 120 | 121 | ```bash 122 | $ npm run rename # rename command 123 | ``` 124 | 125 | ## Contributors 126 | 127 | [contributors](https://github.com/jsmini/pubsub/graphs/contributors) 128 | 129 | ## CHANGELOG 130 | 131 | [CHANGELOG.md](https://github.com/jsmini/pubsub/blob/master/CHANGELOG.md) 132 | 133 | ## TODO 134 | 135 | [TODO.md](https://github.com/jsmini/pubsub/blob/master/TODO.md) 136 | 137 | ## who is using 138 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # 计划列表 2 | 3 | 这里列出会在未来添加的新功能,和已经完成的功能 4 | 5 | - [x] 已完成 6 | - [ ] 未完成 7 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['@commitlint/config-conventional'], 3 | }; 4 | -------------------------------------------------------------------------------- /config/rollup.cjs: -------------------------------------------------------------------------------- 1 | var babel = require('@rollup/plugin-babel'); 2 | 3 | var pkg = require('../package.json'); 4 | 5 | var version = pkg.version; 6 | 7 | var banner = `/*! 8 | * ${pkg.name} ${version} (https://github.com/jsmini/pubsub) 9 | * API https://github.com/jsmini/pubsub/blob/master/doc/api.md 10 | * Copyright 2017-${new Date().getFullYear()} jsmini. All Rights Reserved 11 | * Licensed under MIT (https://github.com/jsmini/pubsub/blob/master/LICENSE) 12 | */ 13 | `; 14 | 15 | function getCompiler() { 16 | return babel({ 17 | babelrc: false, 18 | presets: [ 19 | [ 20 | '@babel/preset-env', 21 | { 22 | targets: { 23 | browsers: 24 | 'last 2 versions, > 1%, ie >= 11, Android >= 4.1, iOS >= 10.3', 25 | node: '14', 26 | }, 27 | modules: false, 28 | loose: false, 29 | }, 30 | ], 31 | ], 32 | plugins: [ 33 | // [ 34 | // '@babel/plugin-transform-runtime', 35 | // { 36 | // corejs: 3, 37 | // versions: '^7.22.15', 38 | // helpers: true, 39 | // regenerator: false, 40 | // }, 41 | // ], 42 | ], 43 | babelHelpers: 'bundled', 44 | exclude: 'node_modules/**', 45 | }); 46 | } 47 | 48 | exports.name = 'jsmini_pubsub'; 49 | exports.banner = banner; 50 | exports.getCompiler = getCompiler; 51 | -------------------------------------------------------------------------------- /config/rollup.config.aio.cjs: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | // umd 3 | var nodeResolve = require('@rollup/plugin-node-resolve'); 4 | var commonjs = require('@rollup/plugin-commonjs'); 5 | var terser = require('@rollup/plugin-terser'); 6 | 7 | var common = require('./rollup.cjs'); 8 | 9 | module.exports = { 10 | input: 'src/index.js', 11 | output: [ 12 | { 13 | file: 'dist/index.aio.js', 14 | format: 'umd', 15 | // When export and export default are not used at the same time, set legacy to true. 16 | // legacy: true, 17 | name: common.name, 18 | banner: common.banner, 19 | }, 20 | { 21 | file: 'dist/index.aio.min.js', 22 | format: 'umd', 23 | // legacy: true, 24 | name: common.name, 25 | banner: common.banner, 26 | plugins: [terser()], 27 | }, 28 | ], 29 | plugins: [nodeResolve({}), commonjs({}), common.getCompiler()], 30 | }; 31 | -------------------------------------------------------------------------------- /config/rollup.config.cjs: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | // commonjs 3 | var common = require('./rollup.cjs'); 4 | 5 | module.exports = { 6 | input: 'src/index.js', 7 | output: [ 8 | { 9 | file: 'dist/index.js', 10 | format: 'cjs', 11 | // When export and export default are not used at the same time, set legacy to true. 12 | // legacy: true, 13 | banner: common.banner, 14 | sourcemap: true, 15 | }, 16 | ], 17 | plugins: [common.getCompiler()], 18 | }; 19 | -------------------------------------------------------------------------------- /config/rollup.config.esm.cjs: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | // ES output 3 | var common = require('./rollup.cjs'); 4 | 5 | module.exports = { 6 | input: 'src/index.js', 7 | output: [ 8 | { 9 | file: 'dist/index.esm.js', 10 | format: 'es', 11 | // When export and export default are not used at the same time, set legacy to true. 12 | // legacy: true, 13 | banner: common.banner, 14 | sourcemap: true, 15 | }, 16 | { 17 | file: 'dist/index.mjs', 18 | format: 'es', 19 | // legacy: true, 20 | banner: common.banner, 21 | sourcemap: true, 22 | }, 23 | ], 24 | plugins: [common.getCompiler()], 25 | }; 26 | -------------------------------------------------------------------------------- /demo/demo-amd.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /demo/demo-global.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 11 | 12 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /demo/demo-node.js: -------------------------------------------------------------------------------- 1 | var base = require('../dist/index.js'); 2 | console.log(base.name); 3 | -------------------------------------------------------------------------------- /demo/js/require.js: -------------------------------------------------------------------------------- 1 | /** vim: et:ts=4:sw=4:sts=4 2 | * @license RequireJS 2.3.5 Copyright jQuery Foundation and other contributors. 3 | * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE 4 | */ 5 | //Not using strict: uneven strict support in browsers, #392, and causes 6 | //problems with requirejs.exec()/transpiler plugins that may not be strict. 7 | /*jslint regexp: true, nomen: true, sloppy: true */ 8 | /*global window, navigator, document, importScripts, setTimeout, opera */ 9 | 10 | var requirejs, require, define; 11 | (function (global, setTimeout) { 12 | var req, 13 | s, 14 | head, 15 | baseElement, 16 | dataMain, 17 | src, 18 | interactiveScript, 19 | currentlyAddingScript, 20 | mainScript, 21 | subPath, 22 | version = '2.3.5', 23 | commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/gm, 24 | cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, 25 | jsSuffixRegExp = /\.js$/, 26 | currDirRegExp = /^\.\//, 27 | op = Object.prototype, 28 | ostring = op.toString, 29 | hasOwn = op.hasOwnProperty, 30 | isBrowser = !!( 31 | typeof window !== 'undefined' && 32 | typeof navigator !== 'undefined' && 33 | window.document 34 | ), 35 | isWebWorker = !isBrowser && typeof importScripts !== 'undefined', 36 | //PS3 indicates loaded and complete, but need to wait for complete 37 | //specifically. Sequence is 'loading', 'loaded', execution, 38 | // then 'complete'. The UA check is unfortunate, but not sure how 39 | //to feature test w/o causing perf issues. 40 | readyRegExp = 41 | isBrowser && navigator.platform === 'PLAYSTATION 3' 42 | ? /^complete$/ 43 | : /^(complete|loaded)$/, 44 | defContextName = '_', 45 | //Oh the tragedy, detecting opera. See the usage of isOpera for reason. 46 | isOpera = 47 | typeof opera !== 'undefined' && opera.toString() === '[object Opera]', 48 | contexts = {}, 49 | cfg = {}, 50 | globalDefQueue = [], 51 | useInteractive = false; 52 | 53 | //Could match something like ')//comment', do not lose the prefix to comment. 54 | function commentReplace(match, singlePrefix) { 55 | return singlePrefix || ''; 56 | } 57 | 58 | function isFunction(it) { 59 | return ostring.call(it) === '[object Function]'; 60 | } 61 | 62 | function isArray(it) { 63 | return ostring.call(it) === '[object Array]'; 64 | } 65 | 66 | /** 67 | * Helper function for iterating over an array. If the func returns 68 | * a true value, it will break out of the loop. 69 | */ 70 | function each(ary, func) { 71 | if (ary) { 72 | var i; 73 | for (i = 0; i < ary.length; i += 1) { 74 | if (ary[i] && func(ary[i], i, ary)) { 75 | break; 76 | } 77 | } 78 | } 79 | } 80 | 81 | /** 82 | * Helper function for iterating over an array backwards. If the func 83 | * returns a true value, it will break out of the loop. 84 | */ 85 | function eachReverse(ary, func) { 86 | if (ary) { 87 | var i; 88 | for (i = ary.length - 1; i > -1; i -= 1) { 89 | if (ary[i] && func(ary[i], i, ary)) { 90 | break; 91 | } 92 | } 93 | } 94 | } 95 | 96 | function hasProp(obj, prop) { 97 | return hasOwn.call(obj, prop); 98 | } 99 | 100 | function getOwn(obj, prop) { 101 | return hasProp(obj, prop) && obj[prop]; 102 | } 103 | 104 | /** 105 | * Cycles over properties in an object and calls a function for each 106 | * property value. If the function returns a truthy value, then the 107 | * iteration is stopped. 108 | */ 109 | function eachProp(obj, func) { 110 | var prop; 111 | for (prop in obj) { 112 | if (hasProp(obj, prop)) { 113 | if (func(obj[prop], prop)) { 114 | break; 115 | } 116 | } 117 | } 118 | } 119 | 120 | /** 121 | * Simple function to mix in properties from source into target, 122 | * but only if target does not already have a property of the same name. 123 | */ 124 | function mixin(target, source, force, deepStringMixin) { 125 | if (source) { 126 | eachProp(source, function (value, prop) { 127 | if (force || !hasProp(target, prop)) { 128 | if ( 129 | deepStringMixin && 130 | typeof value === 'object' && 131 | value && 132 | !isArray(value) && 133 | !isFunction(value) && 134 | !(value instanceof RegExp) 135 | ) { 136 | if (!target[prop]) { 137 | target[prop] = {}; 138 | } 139 | mixin(target[prop], value, force, deepStringMixin); 140 | } else { 141 | target[prop] = value; 142 | } 143 | } 144 | }); 145 | } 146 | return target; 147 | } 148 | 149 | //Similar to Function.prototype.bind, but the 'this' object is specified 150 | //first, since it is easier to read/figure out what 'this' will be. 151 | function bind(obj, fn) { 152 | return function () { 153 | return fn.apply(obj, arguments); 154 | }; 155 | } 156 | 157 | function scripts() { 158 | return document.getElementsByTagName('script'); 159 | } 160 | 161 | function defaultOnError(err) { 162 | throw err; 163 | } 164 | 165 | //Allow getting a global that is expressed in 166 | //dot notation, like 'a.b.c'. 167 | function getGlobal(value) { 168 | if (!value) { 169 | return value; 170 | } 171 | var g = global; 172 | each(value.split('.'), function (part) { 173 | g = g[part]; 174 | }); 175 | return g; 176 | } 177 | 178 | /** 179 | * Constructs an error with a pointer to an URL with more information. 180 | * @param {String} id the error ID that maps to an ID on a web page. 181 | * @param {String} message human readable error. 182 | * @param {Error} [err] the original error, if there is one. 183 | * 184 | * @returns {Error} 185 | */ 186 | function makeError(id, msg, err, requireModules) { 187 | var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); 188 | e.requireType = id; 189 | e.requireModules = requireModules; 190 | if (err) { 191 | e.originalError = err; 192 | } 193 | return e; 194 | } 195 | 196 | if (typeof define !== 'undefined') { 197 | //If a define is already in play via another AMD loader, 198 | //do not overwrite. 199 | return; 200 | } 201 | 202 | if (typeof requirejs !== 'undefined') { 203 | if (isFunction(requirejs)) { 204 | //Do not overwrite an existing requirejs instance. 205 | return; 206 | } 207 | cfg = requirejs; 208 | requirejs = undefined; 209 | } 210 | 211 | //Allow for a require config object 212 | if (typeof require !== 'undefined' && !isFunction(require)) { 213 | //assume it is a config object. 214 | cfg = require; 215 | require = undefined; 216 | } 217 | 218 | function newContext(contextName) { 219 | var inCheckLoaded, 220 | Module, 221 | context, 222 | handlers, 223 | checkLoadedTimeoutId, 224 | config = { 225 | //Defaults. Do not set a default for map 226 | //config to speed up normalize(), which 227 | //will run faster if there is no default. 228 | waitSeconds: 7, 229 | baseUrl: './', 230 | paths: {}, 231 | bundles: {}, 232 | pkgs: {}, 233 | shim: {}, 234 | config: {}, 235 | }, 236 | registry = {}, 237 | //registry of just enabled modules, to speed 238 | //cycle breaking code when lots of modules 239 | //are registered, but not activated. 240 | enabledRegistry = {}, 241 | undefEvents = {}, 242 | defQueue = [], 243 | defined = {}, 244 | urlFetched = {}, 245 | bundlesMap = {}, 246 | requireCounter = 1, 247 | unnormalizedCounter = 1; 248 | 249 | /** 250 | * Trims the . and .. from an array of path segments. 251 | * It will keep a leading path segment if a .. will become 252 | * the first path segment, to help with module name lookups, 253 | * which act like paths, but can be remapped. But the end result, 254 | * all paths that use this function should look normalized. 255 | * NOTE: this method MODIFIES the input array. 256 | * @param {Array} ary the array of path segments. 257 | */ 258 | function trimDots(ary) { 259 | var i, part; 260 | for (i = 0; i < ary.length; i++) { 261 | part = ary[i]; 262 | if (part === '.') { 263 | ary.splice(i, 1); 264 | i -= 1; 265 | } else if (part === '..') { 266 | // If at the start, or previous value is still .., 267 | // keep them so that when converted to a path it may 268 | // still work when converted to a path, even though 269 | // as an ID it is less than ideal. In larger point 270 | // releases, may be better to just kick out an error. 271 | if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { 272 | continue; 273 | } else if (i > 0) { 274 | ary.splice(i - 1, 2); 275 | i -= 2; 276 | } 277 | } 278 | } 279 | } 280 | 281 | /** 282 | * Given a relative module name, like ./something, normalize it to 283 | * a real name that can be mapped to a path. 284 | * @param {String} name the relative name 285 | * @param {String} baseName a real name that the name arg is relative 286 | * to. 287 | * @param {Boolean} applyMap apply the map config to the value. Should 288 | * only be done if this normalization is for a dependency ID. 289 | * @returns {String} normalized name 290 | */ 291 | function normalize(name, baseName, applyMap) { 292 | var pkgMain, 293 | mapValue, 294 | nameParts, 295 | i, 296 | j, 297 | nameSegment, 298 | lastIndex, 299 | foundMap, 300 | foundI, 301 | foundStarMap, 302 | starI, 303 | normalizedBaseParts, 304 | baseParts = baseName && baseName.split('/'), 305 | map = config.map, 306 | starMap = map && map['*']; 307 | 308 | //Adjust any relative paths. 309 | if (name) { 310 | name = name.split('/'); 311 | lastIndex = name.length - 1; 312 | 313 | // If wanting node ID compatibility, strip .js from end 314 | // of IDs. Have to do this here, and not in nameToUrl 315 | // because node allows either .js or non .js to map 316 | // to same file. 317 | if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { 318 | name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); 319 | } 320 | 321 | // Starts with a '.' so need the baseName 322 | if (name[0].charAt(0) === '.' && baseParts) { 323 | //Convert baseName to array, and lop off the last part, 324 | //so that . matches that 'directory' and not name of the baseName's 325 | //module. For instance, baseName of 'one/two/three', maps to 326 | //'one/two/three.js', but we want the directory, 'one/two' for 327 | //this normalization. 328 | normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); 329 | name = normalizedBaseParts.concat(name); 330 | } 331 | 332 | trimDots(name); 333 | name = name.join('/'); 334 | } 335 | 336 | //Apply map config if available. 337 | if (applyMap && map && (baseParts || starMap)) { 338 | nameParts = name.split('/'); 339 | 340 | outerLoop: for (i = nameParts.length; i > 0; i -= 1) { 341 | nameSegment = nameParts.slice(0, i).join('/'); 342 | 343 | if (baseParts) { 344 | //Find the longest baseName segment match in the config. 345 | //So, do joins on the biggest to smallest lengths of baseParts. 346 | for (j = baseParts.length; j > 0; j -= 1) { 347 | mapValue = getOwn(map, baseParts.slice(0, j).join('/')); 348 | 349 | //baseName segment has config, find if it has one for 350 | //this name. 351 | if (mapValue) { 352 | mapValue = getOwn(mapValue, nameSegment); 353 | if (mapValue) { 354 | //Match, update name to the new value. 355 | foundMap = mapValue; 356 | foundI = i; 357 | break outerLoop; 358 | } 359 | } 360 | } 361 | } 362 | 363 | //Check for a star map match, but just hold on to it, 364 | //if there is a shorter segment match later in a matching 365 | //config, then favor over this star map. 366 | if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { 367 | foundStarMap = getOwn(starMap, nameSegment); 368 | starI = i; 369 | } 370 | } 371 | 372 | if (!foundMap && foundStarMap) { 373 | foundMap = foundStarMap; 374 | foundI = starI; 375 | } 376 | 377 | if (foundMap) { 378 | nameParts.splice(0, foundI, foundMap); 379 | name = nameParts.join('/'); 380 | } 381 | } 382 | 383 | // If the name points to a package's name, use 384 | // the package main instead. 385 | pkgMain = getOwn(config.pkgs, name); 386 | 387 | return pkgMain ? pkgMain : name; 388 | } 389 | 390 | function removeScript(name) { 391 | if (isBrowser) { 392 | each(scripts(), function (scriptNode) { 393 | if ( 394 | scriptNode.getAttribute('data-requiremodule') === name && 395 | scriptNode.getAttribute('data-requirecontext') === 396 | context.contextName 397 | ) { 398 | scriptNode.parentNode.removeChild(scriptNode); 399 | return true; 400 | } 401 | }); 402 | } 403 | } 404 | 405 | function hasPathFallback(id) { 406 | var pathConfig = getOwn(config.paths, id); 407 | if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { 408 | //Pop off the first array value, since it failed, and 409 | //retry 410 | pathConfig.shift(); 411 | context.require.undef(id); 412 | 413 | //Custom require that does not do map translation, since 414 | //ID is "absolute", already mapped/resolved. 415 | context.makeRequire(null, { 416 | skipMap: true, 417 | })([id]); 418 | 419 | return true; 420 | } 421 | } 422 | 423 | //Turns a plugin!resource to [plugin, resource] 424 | //with the plugin being undefined if the name 425 | //did not have a plugin prefix. 426 | function splitPrefix(name) { 427 | var prefix, 428 | index = name ? name.indexOf('!') : -1; 429 | if (index > -1) { 430 | prefix = name.substring(0, index); 431 | name = name.substring(index + 1, name.length); 432 | } 433 | return [prefix, name]; 434 | } 435 | 436 | /** 437 | * Creates a module mapping that includes plugin prefix, module 438 | * name, and path. If parentModuleMap is provided it will 439 | * also normalize the name via require.normalize() 440 | * 441 | * @param {String} name the module name 442 | * @param {String} [parentModuleMap] parent module map 443 | * for the module name, used to resolve relative names. 444 | * @param {Boolean} isNormalized: is the ID already normalized. 445 | * This is true if this call is done for a define() module ID. 446 | * @param {Boolean} applyMap: apply the map config to the ID. 447 | * Should only be true if this map is for a dependency. 448 | * 449 | * @returns {Object} 450 | */ 451 | function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { 452 | var url, 453 | pluginModule, 454 | suffix, 455 | nameParts, 456 | prefix = null, 457 | parentName = parentModuleMap ? parentModuleMap.name : null, 458 | originalName = name, 459 | isDefine = true, 460 | normalizedName = ''; 461 | 462 | //If no name, then it means it is a require call, generate an 463 | //internal name. 464 | if (!name) { 465 | isDefine = false; 466 | name = '_@r' + (requireCounter += 1); 467 | } 468 | 469 | nameParts = splitPrefix(name); 470 | prefix = nameParts[0]; 471 | name = nameParts[1]; 472 | 473 | if (prefix) { 474 | prefix = normalize(prefix, parentName, applyMap); 475 | pluginModule = getOwn(defined, prefix); 476 | } 477 | 478 | //Account for relative paths if there is a base name. 479 | if (name) { 480 | if (prefix) { 481 | if (isNormalized) { 482 | normalizedName = name; 483 | } else if (pluginModule && pluginModule.normalize) { 484 | //Plugin is loaded, use its normalize method. 485 | normalizedName = pluginModule.normalize(name, function (name) { 486 | return normalize(name, parentName, applyMap); 487 | }); 488 | } else { 489 | // If nested plugin references, then do not try to 490 | // normalize, as it will not normalize correctly. This 491 | // places a restriction on resourceIds, and the longer 492 | // term solution is not to normalize until plugins are 493 | // loaded and all normalizations to allow for async 494 | // loading of a loader plugin. But for now, fixes the 495 | // common uses. Details in #1131 496 | normalizedName = 497 | name.indexOf('!') === -1 498 | ? normalize(name, parentName, applyMap) 499 | : name; 500 | } 501 | } else { 502 | //A regular module. 503 | normalizedName = normalize(name, parentName, applyMap); 504 | 505 | //Normalized name may be a plugin ID due to map config 506 | //application in normalize. The map config values must 507 | //already be normalized, so do not need to redo that part. 508 | nameParts = splitPrefix(normalizedName); 509 | prefix = nameParts[0]; 510 | normalizedName = nameParts[1]; 511 | isNormalized = true; 512 | 513 | url = context.nameToUrl(normalizedName); 514 | } 515 | } 516 | 517 | //If the id is a plugin id that cannot be determined if it needs 518 | //normalization, stamp it with a unique ID so two matching relative 519 | //ids that may conflict can be separate. 520 | suffix = 521 | prefix && !pluginModule && !isNormalized 522 | ? '_unnormalized' + (unnormalizedCounter += 1) 523 | : ''; 524 | 525 | return { 526 | prefix: prefix, 527 | name: normalizedName, 528 | parentMap: parentModuleMap, 529 | unnormalized: !!suffix, 530 | url: url, 531 | originalName: originalName, 532 | isDefine: isDefine, 533 | id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix, 534 | }; 535 | } 536 | 537 | function getModule(depMap) { 538 | var id = depMap.id, 539 | mod = getOwn(registry, id); 540 | 541 | if (!mod) { 542 | mod = registry[id] = new context.Module(depMap); 543 | } 544 | 545 | return mod; 546 | } 547 | 548 | function on(depMap, name, fn) { 549 | var id = depMap.id, 550 | mod = getOwn(registry, id); 551 | 552 | if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { 553 | if (name === 'defined') { 554 | fn(defined[id]); 555 | } 556 | } else { 557 | mod = getModule(depMap); 558 | if (mod.error && name === 'error') { 559 | fn(mod.error); 560 | } else { 561 | mod.on(name, fn); 562 | } 563 | } 564 | } 565 | 566 | function onError(err, errback) { 567 | var ids = err.requireModules, 568 | notified = false; 569 | 570 | if (errback) { 571 | errback(err); 572 | } else { 573 | each(ids, function (id) { 574 | var mod = getOwn(registry, id); 575 | if (mod) { 576 | //Set error on module, so it skips timeout checks. 577 | mod.error = err; 578 | if (mod.events.error) { 579 | notified = true; 580 | mod.emit('error', err); 581 | } 582 | } 583 | }); 584 | 585 | if (!notified) { 586 | req.onError(err); 587 | } 588 | } 589 | } 590 | 591 | /** 592 | * Internal method to transfer globalQueue items to this context's 593 | * defQueue. 594 | */ 595 | function takeGlobalQueue() { 596 | //Push all the globalDefQueue items into the context's defQueue 597 | if (globalDefQueue.length) { 598 | each(globalDefQueue, function (queueItem) { 599 | var id = queueItem[0]; 600 | if (typeof id === 'string') { 601 | context.defQueueMap[id] = true; 602 | } 603 | defQueue.push(queueItem); 604 | }); 605 | globalDefQueue = []; 606 | } 607 | } 608 | 609 | handlers = { 610 | require: function (mod) { 611 | if (mod.require) { 612 | return mod.require; 613 | } else { 614 | return (mod.require = context.makeRequire(mod.map)); 615 | } 616 | }, 617 | exports: function (mod) { 618 | mod.usingExports = true; 619 | if (mod.map.isDefine) { 620 | if (mod.exports) { 621 | return (defined[mod.map.id] = mod.exports); 622 | } else { 623 | return (mod.exports = defined[mod.map.id] = {}); 624 | } 625 | } 626 | }, 627 | module: function (mod) { 628 | if (mod.module) { 629 | return mod.module; 630 | } else { 631 | return (mod.module = { 632 | id: mod.map.id, 633 | uri: mod.map.url, 634 | config: function () { 635 | return getOwn(config.config, mod.map.id) || {}; 636 | }, 637 | exports: mod.exports || (mod.exports = {}), 638 | }); 639 | } 640 | }, 641 | }; 642 | 643 | function cleanRegistry(id) { 644 | //Clean up machinery used for waiting modules. 645 | delete registry[id]; 646 | delete enabledRegistry[id]; 647 | } 648 | 649 | function breakCycle(mod, traced, processed) { 650 | var id = mod.map.id; 651 | 652 | if (mod.error) { 653 | mod.emit('error', mod.error); 654 | } else { 655 | traced[id] = true; 656 | each(mod.depMaps, function (depMap, i) { 657 | var depId = depMap.id, 658 | dep = getOwn(registry, depId); 659 | 660 | //Only force things that have not completed 661 | //being defined, so still in the registry, 662 | //and only if it has not been matched up 663 | //in the module already. 664 | if (dep && !mod.depMatched[i] && !processed[depId]) { 665 | if (getOwn(traced, depId)) { 666 | mod.defineDep(i, defined[depId]); 667 | mod.check(); //pass false? 668 | } else { 669 | breakCycle(dep, traced, processed); 670 | } 671 | } 672 | }); 673 | processed[id] = true; 674 | } 675 | } 676 | 677 | function checkLoaded() { 678 | var err, 679 | usingPathFallback, 680 | waitInterval = config.waitSeconds * 1000, 681 | //It is possible to disable the wait interval by using waitSeconds of 0. 682 | expired = 683 | waitInterval && 684 | context.startTime + waitInterval < new Date().getTime(), 685 | noLoads = [], 686 | reqCalls = [], 687 | stillLoading = false, 688 | needCycleCheck = true; 689 | 690 | //Do not bother if this call was a result of a cycle break. 691 | if (inCheckLoaded) { 692 | return; 693 | } 694 | 695 | inCheckLoaded = true; 696 | 697 | //Figure out the state of all the modules. 698 | eachProp(enabledRegistry, function (mod) { 699 | var map = mod.map, 700 | modId = map.id; 701 | 702 | //Skip things that are not enabled or in error state. 703 | if (!mod.enabled) { 704 | return; 705 | } 706 | 707 | if (!map.isDefine) { 708 | reqCalls.push(mod); 709 | } 710 | 711 | if (!mod.error) { 712 | //If the module should be executed, and it has not 713 | //been inited and time is up, remember it. 714 | if (!mod.inited && expired) { 715 | if (hasPathFallback(modId)) { 716 | usingPathFallback = true; 717 | stillLoading = true; 718 | } else { 719 | noLoads.push(modId); 720 | removeScript(modId); 721 | } 722 | } else if (!mod.inited && mod.fetched && map.isDefine) { 723 | stillLoading = true; 724 | if (!map.prefix) { 725 | //No reason to keep looking for unfinished 726 | //loading. If the only stillLoading is a 727 | //plugin resource though, keep going, 728 | //because it may be that a plugin resource 729 | //is waiting on a non-plugin cycle. 730 | return (needCycleCheck = false); 731 | } 732 | } 733 | } 734 | }); 735 | 736 | if (expired && noLoads.length) { 737 | //If wait time expired, throw error of unloaded modules. 738 | err = makeError( 739 | 'timeout', 740 | 'Load timeout for modules: ' + noLoads, 741 | null, 742 | noLoads, 743 | ); 744 | err.contextName = context.contextName; 745 | return onError(err); 746 | } 747 | 748 | //Not expired, check for a cycle. 749 | if (needCycleCheck) { 750 | each(reqCalls, function (mod) { 751 | breakCycle(mod, {}, {}); 752 | }); 753 | } 754 | 755 | //If still waiting on loads, and the waiting load is something 756 | //other than a plugin resource, or there are still outstanding 757 | //scripts, then just try back later. 758 | if ((!expired || usingPathFallback) && stillLoading) { 759 | //Something is still waiting to load. Wait for it, but only 760 | //if a timeout is not already in effect. 761 | if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { 762 | checkLoadedTimeoutId = setTimeout(function () { 763 | checkLoadedTimeoutId = 0; 764 | checkLoaded(); 765 | }, 50); 766 | } 767 | } 768 | 769 | inCheckLoaded = false; 770 | } 771 | 772 | Module = function (map) { 773 | this.events = getOwn(undefEvents, map.id) || {}; 774 | this.map = map; 775 | this.shim = getOwn(config.shim, map.id); 776 | this.depExports = []; 777 | this.depMaps = []; 778 | this.depMatched = []; 779 | this.pluginMaps = {}; 780 | this.depCount = 0; 781 | 782 | /* this.exports this.factory 783 | this.depMaps = [], 784 | this.enabled, this.fetched 785 | */ 786 | }; 787 | 788 | Module.prototype = { 789 | init: function (depMaps, factory, errback, options) { 790 | options = options || {}; 791 | 792 | //Do not do more inits if already done. Can happen if there 793 | //are multiple define calls for the same module. That is not 794 | //a normal, common case, but it is also not unexpected. 795 | if (this.inited) { 796 | return; 797 | } 798 | 799 | this.factory = factory; 800 | 801 | if (errback) { 802 | //Register for errors on this module. 803 | this.on('error', errback); 804 | } else if (this.events.error) { 805 | //If no errback already, but there are error listeners 806 | //on this module, set up an errback to pass to the deps. 807 | errback = bind(this, function (err) { 808 | this.emit('error', err); 809 | }); 810 | } 811 | 812 | //Do a copy of the dependency array, so that 813 | //source inputs are not modified. For example 814 | //"shim" deps are passed in here directly, and 815 | //doing a direct modification of the depMaps array 816 | //would affect that config. 817 | this.depMaps = depMaps && depMaps.slice(0); 818 | 819 | this.errback = errback; 820 | 821 | //Indicate this module has be initialized 822 | this.inited = true; 823 | 824 | this.ignore = options.ignore; 825 | 826 | //Could have option to init this module in enabled mode, 827 | //or could have been previously marked as enabled. However, 828 | //the dependencies are not known until init is called. So 829 | //if enabled previously, now trigger dependencies as enabled. 830 | if (options.enabled || this.enabled) { 831 | //Enable this module and dependencies. 832 | //Will call this.check() 833 | this.enable(); 834 | } else { 835 | this.check(); 836 | } 837 | }, 838 | 839 | defineDep: function (i, depExports) { 840 | //Because of cycles, defined callback for a given 841 | //export can be called more than once. 842 | if (!this.depMatched[i]) { 843 | this.depMatched[i] = true; 844 | this.depCount -= 1; 845 | this.depExports[i] = depExports; 846 | } 847 | }, 848 | 849 | fetch: function () { 850 | if (this.fetched) { 851 | return; 852 | } 853 | this.fetched = true; 854 | 855 | context.startTime = new Date().getTime(); 856 | 857 | var map = this.map; 858 | 859 | //If the manager is for a plugin managed resource, 860 | //ask the plugin to load it now. 861 | if (this.shim) { 862 | context.makeRequire(this.map, { 863 | enableBuildCallback: true, 864 | })( 865 | this.shim.deps || [], 866 | bind(this, function () { 867 | return map.prefix ? this.callPlugin() : this.load(); 868 | }), 869 | ); 870 | } else { 871 | //Regular dependency. 872 | return map.prefix ? this.callPlugin() : this.load(); 873 | } 874 | }, 875 | 876 | load: function () { 877 | var url = this.map.url; 878 | 879 | //Regular dependency. 880 | if (!urlFetched[url]) { 881 | urlFetched[url] = true; 882 | context.load(this.map.id, url); 883 | } 884 | }, 885 | 886 | /** 887 | * Checks if the module is ready to define itself, and if so, 888 | * define it. 889 | */ 890 | check: function () { 891 | if (!this.enabled || this.enabling) { 892 | return; 893 | } 894 | 895 | var err, 896 | cjsModule, 897 | id = this.map.id, 898 | depExports = this.depExports, 899 | exports = this.exports, 900 | factory = this.factory; 901 | 902 | if (!this.inited) { 903 | // Only fetch if not already in the defQueue. 904 | if (!hasProp(context.defQueueMap, id)) { 905 | this.fetch(); 906 | } 907 | } else if (this.error) { 908 | this.emit('error', this.error); 909 | } else if (!this.defining) { 910 | //The factory could trigger another require call 911 | //that would result in checking this module to 912 | //define itself again. If already in the process 913 | //of doing that, skip this work. 914 | this.defining = true; 915 | 916 | if (this.depCount < 1 && !this.defined) { 917 | if (isFunction(factory)) { 918 | //If there is an error listener, favor passing 919 | //to that instead of throwing an error. However, 920 | //only do it for define()'d modules. require 921 | //errbacks should not be called for failures in 922 | //their callbacks (#699). However if a global 923 | //onError is set, use that. 924 | if ( 925 | (this.events.error && this.map.isDefine) || 926 | req.onError !== defaultOnError 927 | ) { 928 | try { 929 | exports = context.execCb(id, factory, depExports, exports); 930 | } catch (e) { 931 | err = e; 932 | } 933 | } else { 934 | exports = context.execCb(id, factory, depExports, exports); 935 | } 936 | 937 | // Favor return value over exports. If node/cjs in play, 938 | // then will not have a return value anyway. Favor 939 | // module.exports assignment over exports object. 940 | if (this.map.isDefine && exports === undefined) { 941 | cjsModule = this.module; 942 | if (cjsModule) { 943 | exports = cjsModule.exports; 944 | } else if (this.usingExports) { 945 | //exports already set the defined value. 946 | exports = this.exports; 947 | } 948 | } 949 | 950 | if (err) { 951 | err.requireMap = this.map; 952 | err.requireModules = this.map.isDefine ? [this.map.id] : null; 953 | err.requireType = this.map.isDefine ? 'define' : 'require'; 954 | return onError((this.error = err)); 955 | } 956 | } else { 957 | //Just a literal value 958 | exports = factory; 959 | } 960 | 961 | this.exports = exports; 962 | 963 | if (this.map.isDefine && !this.ignore) { 964 | defined[id] = exports; 965 | 966 | if (req.onResourceLoad) { 967 | var resLoadMaps = []; 968 | each(this.depMaps, function (depMap) { 969 | resLoadMaps.push(depMap.normalizedMap || depMap); 970 | }); 971 | req.onResourceLoad(context, this.map, resLoadMaps); 972 | } 973 | } 974 | 975 | //Clean up 976 | cleanRegistry(id); 977 | 978 | this.defined = true; 979 | } 980 | 981 | //Finished the define stage. Allow calling check again 982 | //to allow define notifications below in the case of a 983 | //cycle. 984 | this.defining = false; 985 | 986 | if (this.defined && !this.defineEmitted) { 987 | this.defineEmitted = true; 988 | this.emit('defined', this.exports); 989 | this.defineEmitComplete = true; 990 | } 991 | } 992 | }, 993 | 994 | callPlugin: function () { 995 | var map = this.map, 996 | id = map.id, 997 | //Map already normalized the prefix. 998 | pluginMap = makeModuleMap(map.prefix); 999 | 1000 | //Mark this as a dependency for this plugin, so it 1001 | //can be traced for cycles. 1002 | this.depMaps.push(pluginMap); 1003 | 1004 | on( 1005 | pluginMap, 1006 | 'defined', 1007 | bind(this, function (plugin) { 1008 | var load, 1009 | normalizedMap, 1010 | normalizedMod, 1011 | bundleId = getOwn(bundlesMap, this.map.id), 1012 | name = this.map.name, 1013 | parentName = this.map.parentMap ? this.map.parentMap.name : null, 1014 | localRequire = context.makeRequire(map.parentMap, { 1015 | enableBuildCallback: true, 1016 | }); 1017 | 1018 | //If current map is not normalized, wait for that 1019 | //normalized name to load instead of continuing. 1020 | if (this.map.unnormalized) { 1021 | //Normalize the ID if the plugin allows it. 1022 | if (plugin.normalize) { 1023 | name = 1024 | plugin.normalize(name, function (name) { 1025 | return normalize(name, parentName, true); 1026 | }) || ''; 1027 | } 1028 | 1029 | //prefix and name should already be normalized, no need 1030 | //for applying map config again either. 1031 | normalizedMap = makeModuleMap( 1032 | map.prefix + '!' + name, 1033 | this.map.parentMap, 1034 | true, 1035 | ); 1036 | on( 1037 | normalizedMap, 1038 | 'defined', 1039 | bind(this, function (value) { 1040 | this.map.normalizedMap = normalizedMap; 1041 | this.init( 1042 | [], 1043 | function () { 1044 | return value; 1045 | }, 1046 | null, 1047 | { 1048 | enabled: true, 1049 | ignore: true, 1050 | }, 1051 | ); 1052 | }), 1053 | ); 1054 | 1055 | normalizedMod = getOwn(registry, normalizedMap.id); 1056 | if (normalizedMod) { 1057 | //Mark this as a dependency for this plugin, so it 1058 | //can be traced for cycles. 1059 | this.depMaps.push(normalizedMap); 1060 | 1061 | if (this.events.error) { 1062 | normalizedMod.on( 1063 | 'error', 1064 | bind(this, function (err) { 1065 | this.emit('error', err); 1066 | }), 1067 | ); 1068 | } 1069 | normalizedMod.enable(); 1070 | } 1071 | 1072 | return; 1073 | } 1074 | 1075 | //If a paths config, then just load that file instead to 1076 | //resolve the plugin, as it is built into that paths layer. 1077 | if (bundleId) { 1078 | this.map.url = context.nameToUrl(bundleId); 1079 | this.load(); 1080 | return; 1081 | } 1082 | 1083 | load = bind(this, function (value) { 1084 | this.init( 1085 | [], 1086 | function () { 1087 | return value; 1088 | }, 1089 | null, 1090 | { 1091 | enabled: true, 1092 | }, 1093 | ); 1094 | }); 1095 | 1096 | load.error = bind(this, function (err) { 1097 | this.inited = true; 1098 | this.error = err; 1099 | err.requireModules = [id]; 1100 | 1101 | //Remove temp unnormalized modules for this module, 1102 | //since they will never be resolved otherwise now. 1103 | eachProp(registry, function (mod) { 1104 | if (mod.map.id.indexOf(id + '_unnormalized') === 0) { 1105 | cleanRegistry(mod.map.id); 1106 | } 1107 | }); 1108 | 1109 | onError(err); 1110 | }); 1111 | 1112 | //Allow plugins to load other code without having to know the 1113 | //context or how to 'complete' the load. 1114 | load.fromText = bind(this, function (text, textAlt) { 1115 | /*jslint evil: true */ 1116 | var moduleName = map.name, 1117 | moduleMap = makeModuleMap(moduleName), 1118 | hasInteractive = useInteractive; 1119 | 1120 | //As of 2.1.0, support just passing the text, to reinforce 1121 | //fromText only being called once per resource. Still 1122 | //support old style of passing moduleName but discard 1123 | //that moduleName in favor of the internal ref. 1124 | if (textAlt) { 1125 | text = textAlt; 1126 | } 1127 | 1128 | //Turn off interactive script matching for IE for any define 1129 | //calls in the text, then turn it back on at the end. 1130 | if (hasInteractive) { 1131 | useInteractive = false; 1132 | } 1133 | 1134 | //Prime the system by creating a module instance for 1135 | //it. 1136 | getModule(moduleMap); 1137 | 1138 | //Transfer any config to this other module. 1139 | if (hasProp(config.config, id)) { 1140 | config.config[moduleName] = config.config[id]; 1141 | } 1142 | 1143 | try { 1144 | req.exec(text); 1145 | } catch (e) { 1146 | return onError( 1147 | makeError( 1148 | 'fromtexteval', 1149 | 'fromText eval for ' + id + ' failed: ' + e, 1150 | e, 1151 | [id], 1152 | ), 1153 | ); 1154 | } 1155 | 1156 | if (hasInteractive) { 1157 | useInteractive = true; 1158 | } 1159 | 1160 | //Mark this as a dependency for the plugin 1161 | //resource 1162 | this.depMaps.push(moduleMap); 1163 | 1164 | //Support anonymous modules. 1165 | context.completeLoad(moduleName); 1166 | 1167 | //Bind the value of that module to the value for this 1168 | //resource ID. 1169 | localRequire([moduleName], load); 1170 | }); 1171 | 1172 | //Use parentName here since the plugin's name is not reliable, 1173 | //could be some weird string with no path that actually wants to 1174 | //reference the parentName's path. 1175 | plugin.load(map.name, localRequire, load, config); 1176 | }), 1177 | ); 1178 | 1179 | context.enable(pluginMap, this); 1180 | this.pluginMaps[pluginMap.id] = pluginMap; 1181 | }, 1182 | 1183 | enable: function () { 1184 | enabledRegistry[this.map.id] = this; 1185 | this.enabled = true; 1186 | 1187 | //Set flag mentioning that the module is enabling, 1188 | //so that immediate calls to the defined callbacks 1189 | //for dependencies do not trigger inadvertent load 1190 | //with the depCount still being zero. 1191 | this.enabling = true; 1192 | 1193 | //Enable each dependency 1194 | each( 1195 | this.depMaps, 1196 | bind(this, function (depMap, i) { 1197 | var id, mod, handler; 1198 | 1199 | if (typeof depMap === 'string') { 1200 | //Dependency needs to be converted to a depMap 1201 | //and wired up to this module. 1202 | depMap = makeModuleMap( 1203 | depMap, 1204 | this.map.isDefine ? this.map : this.map.parentMap, 1205 | false, 1206 | !this.skipMap, 1207 | ); 1208 | this.depMaps[i] = depMap; 1209 | 1210 | handler = getOwn(handlers, depMap.id); 1211 | 1212 | if (handler) { 1213 | this.depExports[i] = handler(this); 1214 | return; 1215 | } 1216 | 1217 | this.depCount += 1; 1218 | 1219 | on( 1220 | depMap, 1221 | 'defined', 1222 | bind(this, function (depExports) { 1223 | if (this.undefed) { 1224 | return; 1225 | } 1226 | this.defineDep(i, depExports); 1227 | this.check(); 1228 | }), 1229 | ); 1230 | 1231 | if (this.errback) { 1232 | on(depMap, 'error', bind(this, this.errback)); 1233 | } else if (this.events.error) { 1234 | // No direct errback on this module, but something 1235 | // else is listening for errors, so be sure to 1236 | // propagate the error correctly. 1237 | on( 1238 | depMap, 1239 | 'error', 1240 | bind(this, function (err) { 1241 | this.emit('error', err); 1242 | }), 1243 | ); 1244 | } 1245 | } 1246 | 1247 | id = depMap.id; 1248 | mod = registry[id]; 1249 | 1250 | //Skip special modules like 'require', 'exports', 'module' 1251 | //Also, don't call enable if it is already enabled, 1252 | //important in circular dependency cases. 1253 | if (!hasProp(handlers, id) && mod && !mod.enabled) { 1254 | context.enable(depMap, this); 1255 | } 1256 | }), 1257 | ); 1258 | 1259 | //Enable each plugin that is used in 1260 | //a dependency 1261 | eachProp( 1262 | this.pluginMaps, 1263 | bind(this, function (pluginMap) { 1264 | var mod = getOwn(registry, pluginMap.id); 1265 | if (mod && !mod.enabled) { 1266 | context.enable(pluginMap, this); 1267 | } 1268 | }), 1269 | ); 1270 | 1271 | this.enabling = false; 1272 | 1273 | this.check(); 1274 | }, 1275 | 1276 | on: function (name, cb) { 1277 | var cbs = this.events[name]; 1278 | if (!cbs) { 1279 | cbs = this.events[name] = []; 1280 | } 1281 | cbs.push(cb); 1282 | }, 1283 | 1284 | emit: function (name, evt) { 1285 | each(this.events[name], function (cb) { 1286 | cb(evt); 1287 | }); 1288 | if (name === 'error') { 1289 | //Now that the error handler was triggered, remove 1290 | //the listeners, since this broken Module instance 1291 | //can stay around for a while in the registry. 1292 | delete this.events[name]; 1293 | } 1294 | }, 1295 | }; 1296 | 1297 | function callGetModule(args) { 1298 | //Skip modules already defined. 1299 | if (!hasProp(defined, args[0])) { 1300 | getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); 1301 | } 1302 | } 1303 | 1304 | function removeListener(node, func, name, ieName) { 1305 | //Favor detachEvent because of IE9 1306 | //issue, see attachEvent/addEventListener comment elsewhere 1307 | //in this file. 1308 | if (node.detachEvent && !isOpera) { 1309 | //Probably IE. If not it will throw an error, which will be 1310 | //useful to know. 1311 | if (ieName) { 1312 | node.detachEvent(ieName, func); 1313 | } 1314 | } else { 1315 | node.removeEventListener(name, func, false); 1316 | } 1317 | } 1318 | 1319 | /** 1320 | * Given an event from a script node, get the requirejs info from it, 1321 | * and then removes the event listeners on the node. 1322 | * @param {Event} evt 1323 | * @returns {Object} 1324 | */ 1325 | function getScriptData(evt) { 1326 | //Using currentTarget instead of target for Firefox 2.0's sake. Not 1327 | //all old browsers will be supported, but this one was easy enough 1328 | //to support and still makes sense. 1329 | var node = evt.currentTarget || evt.srcElement; 1330 | 1331 | //Remove the listeners once here. 1332 | removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); 1333 | removeListener(node, context.onScriptError, 'error'); 1334 | 1335 | return { 1336 | node: node, 1337 | id: node && node.getAttribute('data-requiremodule'), 1338 | }; 1339 | } 1340 | 1341 | function intakeDefines() { 1342 | var args; 1343 | 1344 | //Any defined modules in the global queue, intake them now. 1345 | takeGlobalQueue(); 1346 | 1347 | //Make sure any remaining defQueue items get properly processed. 1348 | while (defQueue.length) { 1349 | args = defQueue.shift(); 1350 | if (args[0] === null) { 1351 | return onError( 1352 | makeError( 1353 | 'mismatch', 1354 | 'Mismatched anonymous define() module: ' + args[args.length - 1], 1355 | ), 1356 | ); 1357 | } else { 1358 | //args are id, deps, factory. Should be normalized by the 1359 | //define() function. 1360 | callGetModule(args); 1361 | } 1362 | } 1363 | context.defQueueMap = {}; 1364 | } 1365 | 1366 | context = { 1367 | config: config, 1368 | contextName: contextName, 1369 | registry: registry, 1370 | defined: defined, 1371 | urlFetched: urlFetched, 1372 | defQueue: defQueue, 1373 | defQueueMap: {}, 1374 | Module: Module, 1375 | makeModuleMap: makeModuleMap, 1376 | nextTick: req.nextTick, 1377 | onError: onError, 1378 | 1379 | /** 1380 | * Set a configuration for the context. 1381 | * @param {Object} cfg config object to integrate. 1382 | */ 1383 | configure: function (cfg) { 1384 | //Make sure the baseUrl ends in a slash. 1385 | if (cfg.baseUrl) { 1386 | if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { 1387 | cfg.baseUrl += '/'; 1388 | } 1389 | } 1390 | 1391 | // Convert old style urlArgs string to a function. 1392 | if (typeof cfg.urlArgs === 'string') { 1393 | var urlArgs = cfg.urlArgs; 1394 | cfg.urlArgs = function (id, url) { 1395 | return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; 1396 | }; 1397 | } 1398 | 1399 | //Save off the paths since they require special processing, 1400 | //they are additive. 1401 | var shim = config.shim, 1402 | objs = { 1403 | paths: true, 1404 | bundles: true, 1405 | config: true, 1406 | map: true, 1407 | }; 1408 | 1409 | eachProp(cfg, function (value, prop) { 1410 | if (objs[prop]) { 1411 | if (!config[prop]) { 1412 | config[prop] = {}; 1413 | } 1414 | mixin(config[prop], value, true, true); 1415 | } else { 1416 | config[prop] = value; 1417 | } 1418 | }); 1419 | 1420 | //Reverse map the bundles 1421 | if (cfg.bundles) { 1422 | eachProp(cfg.bundles, function (value, prop) { 1423 | each(value, function (v) { 1424 | if (v !== prop) { 1425 | bundlesMap[v] = prop; 1426 | } 1427 | }); 1428 | }); 1429 | } 1430 | 1431 | //Merge shim 1432 | if (cfg.shim) { 1433 | eachProp(cfg.shim, function (value, id) { 1434 | //Normalize the structure 1435 | if (isArray(value)) { 1436 | value = { 1437 | deps: value, 1438 | }; 1439 | } 1440 | if ((value.exports || value.init) && !value.exportsFn) { 1441 | value.exportsFn = context.makeShimExports(value); 1442 | } 1443 | shim[id] = value; 1444 | }); 1445 | config.shim = shim; 1446 | } 1447 | 1448 | //Adjust packages if necessary. 1449 | if (cfg.packages) { 1450 | each(cfg.packages, function (pkgObj) { 1451 | var location, name; 1452 | 1453 | pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; 1454 | 1455 | name = pkgObj.name; 1456 | location = pkgObj.location; 1457 | if (location) { 1458 | config.paths[name] = pkgObj.location; 1459 | } 1460 | 1461 | //Save pointer to main module ID for pkg name. 1462 | //Remove leading dot in main, so main paths are normalized, 1463 | //and remove any trailing .js, since different package 1464 | //envs have different conventions: some use a module name, 1465 | //some use a file name. 1466 | config.pkgs[name] = 1467 | pkgObj.name + 1468 | '/' + 1469 | (pkgObj.main || 'main') 1470 | .replace(currDirRegExp, '') 1471 | .replace(jsSuffixRegExp, ''); 1472 | }); 1473 | } 1474 | 1475 | //If there are any "waiting to execute" modules in the registry, 1476 | //update the maps for them, since their info, like URLs to load, 1477 | //may have changed. 1478 | eachProp(registry, function (mod, id) { 1479 | //If module already has init called, since it is too 1480 | //late to modify them, and ignore unnormalized ones 1481 | //since they are transient. 1482 | if (!mod.inited && !mod.map.unnormalized) { 1483 | mod.map = makeModuleMap(id, null, true); 1484 | } 1485 | }); 1486 | 1487 | //If a deps array or a config callback is specified, then call 1488 | //require with those args. This is useful when require is defined as a 1489 | //config object before require.js is loaded. 1490 | if (cfg.deps || cfg.callback) { 1491 | context.require(cfg.deps || [], cfg.callback); 1492 | } 1493 | }, 1494 | 1495 | makeShimExports: function (value) { 1496 | function fn() { 1497 | var ret; 1498 | if (value.init) { 1499 | ret = value.init.apply(global, arguments); 1500 | } 1501 | return ret || (value.exports && getGlobal(value.exports)); 1502 | } 1503 | return fn; 1504 | }, 1505 | 1506 | makeRequire: function (relMap, options) { 1507 | options = options || {}; 1508 | 1509 | function localRequire(deps, callback, errback) { 1510 | var id, map, requireMod; 1511 | 1512 | if (options.enableBuildCallback && callback && isFunction(callback)) { 1513 | callback.__requireJsBuild = true; 1514 | } 1515 | 1516 | if (typeof deps === 'string') { 1517 | if (isFunction(callback)) { 1518 | //Invalid call 1519 | return onError( 1520 | makeError('requireargs', 'Invalid require call'), 1521 | errback, 1522 | ); 1523 | } 1524 | 1525 | //If require|exports|module are requested, get the 1526 | //value for them from the special handlers. Caveat: 1527 | //this only works while module is being defined. 1528 | if (relMap && hasProp(handlers, deps)) { 1529 | return handlers[deps](registry[relMap.id]); 1530 | } 1531 | 1532 | //Synchronous access to one module. If require.get is 1533 | //available (as in the Node adapter), prefer that. 1534 | if (req.get) { 1535 | return req.get(context, deps, relMap, localRequire); 1536 | } 1537 | 1538 | //Normalize module name, if it contains . or .. 1539 | map = makeModuleMap(deps, relMap, false, true); 1540 | id = map.id; 1541 | 1542 | if (!hasProp(defined, id)) { 1543 | return onError( 1544 | makeError( 1545 | 'notloaded', 1546 | 'Module name "' + 1547 | id + 1548 | '" has not been loaded yet for context: ' + 1549 | contextName + 1550 | (relMap ? '' : '. Use require([])'), 1551 | ), 1552 | ); 1553 | } 1554 | return defined[id]; 1555 | } 1556 | 1557 | //Grab defines waiting in the global queue. 1558 | intakeDefines(); 1559 | 1560 | //Mark all the dependencies as needing to be loaded. 1561 | context.nextTick(function () { 1562 | //Some defines could have been added since the 1563 | //require call, collect them. 1564 | intakeDefines(); 1565 | 1566 | requireMod = getModule(makeModuleMap(null, relMap)); 1567 | 1568 | //Store if map config should be applied to this require 1569 | //call for dependencies. 1570 | requireMod.skipMap = options.skipMap; 1571 | 1572 | requireMod.init(deps, callback, errback, { 1573 | enabled: true, 1574 | }); 1575 | 1576 | checkLoaded(); 1577 | }); 1578 | 1579 | return localRequire; 1580 | } 1581 | 1582 | mixin(localRequire, { 1583 | isBrowser: isBrowser, 1584 | 1585 | /** 1586 | * Converts a module name + .extension into an URL path. 1587 | * *Requires* the use of a module name. It does not support using 1588 | * plain URLs like nameToUrl. 1589 | */ 1590 | toUrl: function (moduleNamePlusExt) { 1591 | var ext, 1592 | index = moduleNamePlusExt.lastIndexOf('.'), 1593 | segment = moduleNamePlusExt.split('/')[0], 1594 | isRelative = segment === '.' || segment === '..'; 1595 | 1596 | //Have a file extension alias, and it is not the 1597 | //dots from a relative path. 1598 | if (index !== -1 && (!isRelative || index > 1)) { 1599 | ext = moduleNamePlusExt.substring( 1600 | index, 1601 | moduleNamePlusExt.length, 1602 | ); 1603 | moduleNamePlusExt = moduleNamePlusExt.substring(0, index); 1604 | } 1605 | 1606 | return context.nameToUrl( 1607 | normalize(moduleNamePlusExt, relMap && relMap.id, true), 1608 | ext, 1609 | true, 1610 | ); 1611 | }, 1612 | 1613 | defined: function (id) { 1614 | return hasProp(defined, makeModuleMap(id, relMap, false, true).id); 1615 | }, 1616 | 1617 | specified: function (id) { 1618 | id = makeModuleMap(id, relMap, false, true).id; 1619 | return hasProp(defined, id) || hasProp(registry, id); 1620 | }, 1621 | }); 1622 | 1623 | //Only allow undef on top level require calls 1624 | if (!relMap) { 1625 | localRequire.undef = function (id) { 1626 | //Bind any waiting define() calls to this context, 1627 | //fix for #408 1628 | takeGlobalQueue(); 1629 | 1630 | var map = makeModuleMap(id, relMap, true), 1631 | mod = getOwn(registry, id); 1632 | 1633 | mod.undefed = true; 1634 | removeScript(id); 1635 | 1636 | delete defined[id]; 1637 | delete urlFetched[map.url]; 1638 | delete undefEvents[id]; 1639 | 1640 | //Clean queued defines too. Go backwards 1641 | //in array so that the splices do not 1642 | //mess up the iteration. 1643 | eachReverse(defQueue, function (args, i) { 1644 | if (args[0] === id) { 1645 | defQueue.splice(i, 1); 1646 | } 1647 | }); 1648 | delete context.defQueueMap[id]; 1649 | 1650 | if (mod) { 1651 | //Hold on to listeners in case the 1652 | //module will be attempted to be reloaded 1653 | //using a different config. 1654 | if (mod.events.defined) { 1655 | undefEvents[id] = mod.events; 1656 | } 1657 | 1658 | cleanRegistry(id); 1659 | } 1660 | }; 1661 | } 1662 | 1663 | return localRequire; 1664 | }, 1665 | 1666 | /** 1667 | * Called to enable a module if it is still in the registry 1668 | * awaiting enablement. A second arg, parent, the parent module, 1669 | * is passed in for context, when this method is overridden by 1670 | * the optimizer. Not shown here to keep code compact. 1671 | */ 1672 | enable: function (depMap) { 1673 | var mod = getOwn(registry, depMap.id); 1674 | if (mod) { 1675 | getModule(depMap).enable(); 1676 | } 1677 | }, 1678 | 1679 | /** 1680 | * Internal method used by environment adapters to complete a load event. 1681 | * A load event could be a script load or just a load pass from a synchronous 1682 | * load call. 1683 | * @param {String} moduleName the name of the module to potentially complete. 1684 | */ 1685 | completeLoad: function (moduleName) { 1686 | var found, 1687 | args, 1688 | mod, 1689 | shim = getOwn(config.shim, moduleName) || {}, 1690 | shExports = shim.exports; 1691 | 1692 | takeGlobalQueue(); 1693 | 1694 | while (defQueue.length) { 1695 | args = defQueue.shift(); 1696 | if (args[0] === null) { 1697 | args[0] = moduleName; 1698 | //If already found an anonymous module and bound it 1699 | //to this name, then this is some other anon module 1700 | //waiting for its completeLoad to fire. 1701 | if (found) { 1702 | break; 1703 | } 1704 | found = true; 1705 | } else if (args[0] === moduleName) { 1706 | //Found matching define call for this script! 1707 | found = true; 1708 | } 1709 | 1710 | callGetModule(args); 1711 | } 1712 | context.defQueueMap = {}; 1713 | 1714 | //Do this after the cycle of callGetModule in case the result 1715 | //of those calls/init calls changes the registry. 1716 | mod = getOwn(registry, moduleName); 1717 | 1718 | if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { 1719 | if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { 1720 | if (hasPathFallback(moduleName)) { 1721 | return; 1722 | } else { 1723 | return onError( 1724 | makeError( 1725 | 'nodefine', 1726 | 'No define call for ' + moduleName, 1727 | null, 1728 | [moduleName], 1729 | ), 1730 | ); 1731 | } 1732 | } else { 1733 | //A script that does not call define(), so just simulate 1734 | //the call for it. 1735 | callGetModule([moduleName, shim.deps || [], shim.exportsFn]); 1736 | } 1737 | } 1738 | 1739 | checkLoaded(); 1740 | }, 1741 | 1742 | /** 1743 | * Converts a module name to a file path. Supports cases where 1744 | * moduleName may actually be just an URL. 1745 | * Note that it **does not** call normalize on the moduleName, 1746 | * it is assumed to have already been normalized. This is an 1747 | * internal API, not a public one. Use toUrl for the public API. 1748 | */ 1749 | nameToUrl: function (moduleName, ext, skipExt) { 1750 | var paths, 1751 | syms, 1752 | i, 1753 | parentModule, 1754 | url, 1755 | parentPath, 1756 | bundleId, 1757 | pkgMain = getOwn(config.pkgs, moduleName); 1758 | 1759 | if (pkgMain) { 1760 | moduleName = pkgMain; 1761 | } 1762 | 1763 | bundleId = getOwn(bundlesMap, moduleName); 1764 | 1765 | if (bundleId) { 1766 | return context.nameToUrl(bundleId, ext, skipExt); 1767 | } 1768 | 1769 | //If a colon is in the URL, it indicates a protocol is used and it is just 1770 | //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) 1771 | //or ends with .js, then assume the user meant to use an url and not a module id. 1772 | //The slash is important for protocol-less URLs as well as full paths. 1773 | if (req.jsExtRegExp.test(moduleName)) { 1774 | //Just a plain path, not module name lookup, so just return it. 1775 | //Add extension if it is included. This is a bit wonky, only non-.js things pass 1776 | //an extension, this method probably needs to be reworked. 1777 | url = moduleName + (ext || ''); 1778 | } else { 1779 | //A module that needs to be converted to a path. 1780 | paths = config.paths; 1781 | 1782 | syms = moduleName.split('/'); 1783 | //For each module name segment, see if there is a path 1784 | //registered for it. Start with most specific name 1785 | //and work up from it. 1786 | for (i = syms.length; i > 0; i -= 1) { 1787 | parentModule = syms.slice(0, i).join('/'); 1788 | 1789 | parentPath = getOwn(paths, parentModule); 1790 | if (parentPath) { 1791 | //If an array, it means there are a few choices, 1792 | //Choose the one that is desired 1793 | if (isArray(parentPath)) { 1794 | parentPath = parentPath[0]; 1795 | } 1796 | syms.splice(0, i, parentPath); 1797 | break; 1798 | } 1799 | } 1800 | 1801 | //Join the path parts together, then figure out if baseUrl is needed. 1802 | url = syms.join('/'); 1803 | url += 1804 | ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'); 1805 | url = 1806 | (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) 1807 | ? '' 1808 | : config.baseUrl) + url; 1809 | } 1810 | 1811 | return config.urlArgs && !/^blob\:/.test(url) 1812 | ? url + config.urlArgs(moduleName, url) 1813 | : url; 1814 | }, 1815 | 1816 | //Delegates to req.load. Broken out as a separate function to 1817 | //allow overriding in the optimizer. 1818 | load: function (id, url) { 1819 | req.load(context, id, url); 1820 | }, 1821 | 1822 | /** 1823 | * Executes a module callback function. Broken out as a separate function 1824 | * solely to allow the build system to sequence the files in the built 1825 | * layer in the right sequence. 1826 | * 1827 | * @private 1828 | */ 1829 | execCb: function (name, callback, args, exports) { 1830 | return callback.apply(exports, args); 1831 | }, 1832 | 1833 | /** 1834 | * callback for script loads, used to check status of loading. 1835 | * 1836 | * @param {Event} evt the event from the browser for the script 1837 | * that was loaded. 1838 | */ 1839 | onScriptLoad: function (evt) { 1840 | //Using currentTarget instead of target for Firefox 2.0's sake. Not 1841 | //all old browsers will be supported, but this one was easy enough 1842 | //to support and still makes sense. 1843 | if ( 1844 | evt.type === 'load' || 1845 | readyRegExp.test((evt.currentTarget || evt.srcElement).readyState) 1846 | ) { 1847 | //Reset interactive script so a script node is not held onto for 1848 | //to long. 1849 | interactiveScript = null; 1850 | 1851 | //Pull out the name of the module and the context. 1852 | var data = getScriptData(evt); 1853 | context.completeLoad(data.id); 1854 | } 1855 | }, 1856 | 1857 | /** 1858 | * Callback for script errors. 1859 | */ 1860 | onScriptError: function (evt) { 1861 | var data = getScriptData(evt); 1862 | if (!hasPathFallback(data.id)) { 1863 | var parents = []; 1864 | eachProp(registry, function (value, key) { 1865 | if (key.indexOf('_@r') !== 0) { 1866 | each(value.depMaps, function (depMap) { 1867 | if (depMap.id === data.id) { 1868 | parents.push(key); 1869 | return true; 1870 | } 1871 | }); 1872 | } 1873 | }); 1874 | return onError( 1875 | makeError( 1876 | 'scripterror', 1877 | 'Script error for "' + 1878 | data.id + 1879 | (parents.length ? '", needed by: ' + parents.join(', ') : '"'), 1880 | evt, 1881 | [data.id], 1882 | ), 1883 | ); 1884 | } 1885 | }, 1886 | }; 1887 | 1888 | context.require = context.makeRequire(); 1889 | return context; 1890 | } 1891 | 1892 | /** 1893 | * Main entry point. 1894 | * 1895 | * If the only argument to require is a string, then the module that 1896 | * is represented by that string is fetched for the appropriate context. 1897 | * 1898 | * If the first argument is an array, then it will be treated as an array 1899 | * of dependency string names to fetch. An optional function callback can 1900 | * be specified to execute when all of those dependencies are available. 1901 | * 1902 | * Make a local req variable to help Caja compliance (it assumes things 1903 | * on a require that are not standardized), and to give a short 1904 | * name for minification/local scope use. 1905 | */ 1906 | req = requirejs = function (deps, callback, errback, optional) { 1907 | //Find the right context, use default 1908 | var context, 1909 | config, 1910 | contextName = defContextName; 1911 | 1912 | // Determine if have config object in the call. 1913 | if (!isArray(deps) && typeof deps !== 'string') { 1914 | // deps is a config object 1915 | config = deps; 1916 | if (isArray(callback)) { 1917 | // Adjust args if there are dependencies 1918 | deps = callback; 1919 | callback = errback; 1920 | errback = optional; 1921 | } else { 1922 | deps = []; 1923 | } 1924 | } 1925 | 1926 | if (config && config.context) { 1927 | contextName = config.context; 1928 | } 1929 | 1930 | context = getOwn(contexts, contextName); 1931 | if (!context) { 1932 | context = contexts[contextName] = req.s.newContext(contextName); 1933 | } 1934 | 1935 | if (config) { 1936 | context.configure(config); 1937 | } 1938 | 1939 | return context.require(deps, callback, errback); 1940 | }; 1941 | 1942 | /** 1943 | * Support require.config() to make it easier to cooperate with other 1944 | * AMD loaders on globally agreed names. 1945 | */ 1946 | req.config = function (config) { 1947 | return req(config); 1948 | }; 1949 | 1950 | /** 1951 | * Execute something after the current tick 1952 | * of the event loop. Override for other envs 1953 | * that have a better solution than setTimeout. 1954 | * @param {Function} fn function to execute later. 1955 | */ 1956 | req.nextTick = 1957 | typeof setTimeout !== 'undefined' 1958 | ? function (fn) { 1959 | setTimeout(fn, 4); 1960 | } 1961 | : function (fn) { 1962 | fn(); 1963 | }; 1964 | 1965 | /** 1966 | * Export require as a global, but only if it does not already exist. 1967 | */ 1968 | if (!require) { 1969 | require = req; 1970 | } 1971 | 1972 | req.version = version; 1973 | 1974 | //Used to filter out dependencies that are already paths. 1975 | req.jsExtRegExp = /^\/|:|\?|\.js$/; 1976 | req.isBrowser = isBrowser; 1977 | s = req.s = { 1978 | contexts: contexts, 1979 | newContext: newContext, 1980 | }; 1981 | 1982 | //Create default context. 1983 | req({}); 1984 | 1985 | //Exports some context-sensitive methods on global require. 1986 | each(['toUrl', 'undef', 'defined', 'specified'], function (prop) { 1987 | //Reference from contexts instead of early binding to default context, 1988 | //so that during builds, the latest instance of the default context 1989 | //with its config gets used. 1990 | req[prop] = function () { 1991 | var ctx = contexts[defContextName]; 1992 | return ctx.require[prop].apply(ctx, arguments); 1993 | }; 1994 | }); 1995 | 1996 | if (isBrowser) { 1997 | head = s.head = document.getElementsByTagName('head')[0]; 1998 | //If BASE tag is in play, using appendChild is a problem for IE6. 1999 | //When that browser dies, this can be removed. Details in this jQuery bug: 2000 | //http://dev.jquery.com/ticket/2709 2001 | baseElement = document.getElementsByTagName('base')[0]; 2002 | if (baseElement) { 2003 | head = s.head = baseElement.parentNode; 2004 | } 2005 | } 2006 | 2007 | /** 2008 | * Any errors that require explicitly generates will be passed to this 2009 | * function. Intercept/override it if you want custom error handling. 2010 | * @param {Error} err the error object. 2011 | */ 2012 | req.onError = defaultOnError; 2013 | 2014 | /** 2015 | * Creates the node for the load command. Only used in browser envs. 2016 | */ 2017 | req.createNode = function (config, moduleName, url) { 2018 | var node = config.xhtml 2019 | ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') 2020 | : document.createElement('script'); 2021 | node.type = config.scriptType || 'text/javascript'; 2022 | node.charset = 'utf-8'; 2023 | node.async = true; 2024 | return node; 2025 | }; 2026 | 2027 | /** 2028 | * Does the request to load a module for the browser case. 2029 | * Make this a separate function to allow other environments 2030 | * to override it. 2031 | * 2032 | * @param {Object} context the require context to find state. 2033 | * @param {String} moduleName the name of the module. 2034 | * @param {Object} url the URL to the module. 2035 | */ 2036 | req.load = function (context, moduleName, url) { 2037 | var config = (context && context.config) || {}, 2038 | node; 2039 | if (isBrowser) { 2040 | //In the browser so use a script tag 2041 | node = req.createNode(config, moduleName, url); 2042 | 2043 | node.setAttribute('data-requirecontext', context.contextName); 2044 | node.setAttribute('data-requiremodule', moduleName); 2045 | 2046 | //Set up load listener. Test attachEvent first because IE9 has 2047 | //a subtle issue in its addEventListener and script onload firings 2048 | //that do not match the behavior of all other browsers with 2049 | //addEventListener support, which fire the onload event for a 2050 | //script right after the script execution. See: 2051 | //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution 2052 | //UNFORTUNATELY Opera implements attachEvent but does not follow the script 2053 | //script execution mode. 2054 | if ( 2055 | node.attachEvent && 2056 | //Check if node.attachEvent is artificially added by custom script or 2057 | //natively supported by browser 2058 | //read https://github.com/requirejs/requirejs/issues/187 2059 | //if we can NOT find [native code] then it must NOT natively supported. 2060 | //in IE8, node.attachEvent does not have toString() 2061 | //Note the test for "[native code" with no closing brace, see: 2062 | //https://github.com/requirejs/requirejs/issues/273 2063 | !( 2064 | node.attachEvent.toString && 2065 | node.attachEvent.toString().indexOf('[native code') < 0 2066 | ) && 2067 | !isOpera 2068 | ) { 2069 | //Probably IE. IE (at least 6-8) do not fire 2070 | //script onload right after executing the script, so 2071 | //we cannot tie the anonymous define call to a name. 2072 | //However, IE reports the script as being in 'interactive' 2073 | //readyState at the time of the define call. 2074 | useInteractive = true; 2075 | 2076 | node.attachEvent('onreadystatechange', context.onScriptLoad); 2077 | //It would be great to add an error handler here to catch 2078 | //404s in IE9+. However, onreadystatechange will fire before 2079 | //the error handler, so that does not help. If addEventListener 2080 | //is used, then IE will fire error before load, but we cannot 2081 | //use that pathway given the connect.microsoft.com issue 2082 | //mentioned above about not doing the 'script execute, 2083 | //then fire the script load event listener before execute 2084 | //next script' that other browsers do. 2085 | //Best hope: IE10 fixes the issues, 2086 | //and then destroys all installs of IE 6-9. 2087 | //node.attachEvent('onerror', context.onScriptError); 2088 | } else { 2089 | node.addEventListener('load', context.onScriptLoad, false); 2090 | node.addEventListener('error', context.onScriptError, false); 2091 | } 2092 | node.src = url; 2093 | 2094 | //Calling onNodeCreated after all properties on the node have been 2095 | //set, but before it is placed in the DOM. 2096 | if (config.onNodeCreated) { 2097 | config.onNodeCreated(node, config, moduleName, url); 2098 | } 2099 | 2100 | //For some cache cases in IE 6-8, the script executes before the end 2101 | //of the appendChild execution, so to tie an anonymous define 2102 | //call to the module name (which is stored on the node), hold on 2103 | //to a reference to this node, but clear after the DOM insertion. 2104 | currentlyAddingScript = node; 2105 | if (baseElement) { 2106 | head.insertBefore(node, baseElement); 2107 | } else { 2108 | head.appendChild(node); 2109 | } 2110 | currentlyAddingScript = null; 2111 | 2112 | return node; 2113 | } else if (isWebWorker) { 2114 | try { 2115 | //In a web worker, use importScripts. This is not a very 2116 | //efficient use of importScripts, importScripts will block until 2117 | //its script is downloaded and evaluated. However, if web workers 2118 | //are in play, the expectation is that a build has been done so 2119 | //that only one script needs to be loaded anyway. This may need 2120 | //to be reevaluated if other use cases become common. 2121 | 2122 | // Post a task to the event loop to work around a bug in WebKit 2123 | // where the worker gets garbage-collected after calling 2124 | // importScripts(): https://webkit.org/b/153317 2125 | setTimeout(function () {}, 0); 2126 | importScripts(url); 2127 | 2128 | //Account for anonymous modules 2129 | context.completeLoad(moduleName); 2130 | } catch (e) { 2131 | context.onError( 2132 | makeError( 2133 | 'importscripts', 2134 | 'importScripts failed for ' + moduleName + ' at ' + url, 2135 | e, 2136 | [moduleName], 2137 | ), 2138 | ); 2139 | } 2140 | } 2141 | }; 2142 | 2143 | function getInteractiveScript() { 2144 | if (interactiveScript && interactiveScript.readyState === 'interactive') { 2145 | return interactiveScript; 2146 | } 2147 | 2148 | eachReverse(scripts(), function (script) { 2149 | if (script.readyState === 'interactive') { 2150 | return (interactiveScript = script); 2151 | } 2152 | }); 2153 | return interactiveScript; 2154 | } 2155 | 2156 | //Look for a data-main script attribute, which could also adjust the baseUrl. 2157 | if (isBrowser && !cfg.skipDataMain) { 2158 | //Figure out baseUrl. Get it from the script tag with require.js in it. 2159 | eachReverse(scripts(), function (script) { 2160 | //Set the 'head' where we can append children by 2161 | //using the script's parent. 2162 | if (!head) { 2163 | head = script.parentNode; 2164 | } 2165 | 2166 | //Look for a data-main attribute to set main script for the page 2167 | //to load. If it is there, the path to data main becomes the 2168 | //baseUrl, if it is not already set. 2169 | dataMain = script.getAttribute('data-main'); 2170 | if (dataMain) { 2171 | //Preserve dataMain in case it is a path (i.e. contains '?') 2172 | mainScript = dataMain; 2173 | 2174 | //Set final baseUrl if there is not already an explicit one, 2175 | //but only do so if the data-main value is not a loader plugin 2176 | //module ID. 2177 | if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { 2178 | //Pull off the directory of data-main for use as the 2179 | //baseUrl. 2180 | src = mainScript.split('/'); 2181 | mainScript = src.pop(); 2182 | subPath = src.length ? src.join('/') + '/' : './'; 2183 | 2184 | cfg.baseUrl = subPath; 2185 | } 2186 | 2187 | //Strip off any trailing .js since mainScript is now 2188 | //like a module name. 2189 | mainScript = mainScript.replace(jsSuffixRegExp, ''); 2190 | 2191 | //If mainScript is still a path, fall back to dataMain 2192 | if (req.jsExtRegExp.test(mainScript)) { 2193 | mainScript = dataMain; 2194 | } 2195 | 2196 | //Put the data-main script in the files to load. 2197 | cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; 2198 | 2199 | return true; 2200 | } 2201 | }); 2202 | } 2203 | 2204 | /** 2205 | * The function that handles definitions of modules. Differs from 2206 | * require() in that a string for the module should be the first argument, 2207 | * and the function to execute after dependencies are loaded should 2208 | * return a value to define the module corresponding to the first argument's 2209 | * name. 2210 | */ 2211 | define = function (name, deps, callback) { 2212 | var node, context; 2213 | 2214 | //Allow for anonymous modules 2215 | if (typeof name !== 'string') { 2216 | //Adjust args appropriately 2217 | callback = deps; 2218 | deps = name; 2219 | name = null; 2220 | } 2221 | 2222 | //This module may not have dependencies 2223 | if (!isArray(deps)) { 2224 | callback = deps; 2225 | deps = null; 2226 | } 2227 | 2228 | //If no name, and callback is a function, then figure out if it a 2229 | //CommonJS thing with dependencies. 2230 | if (!deps && isFunction(callback)) { 2231 | deps = []; 2232 | //Remove comments from the callback string, 2233 | //look for require calls, and pull them into the dependencies, 2234 | //but only if there are function args. 2235 | if (callback.length) { 2236 | callback 2237 | .toString() 2238 | .replace(commentRegExp, commentReplace) 2239 | .replace(cjsRequireRegExp, function (match, dep) { 2240 | deps.push(dep); 2241 | }); 2242 | 2243 | //May be a CommonJS thing even without require calls, but still 2244 | //could use exports, and module. Avoid doing exports and module 2245 | //work though if it just needs require. 2246 | //REQUIRES the function to expect the CommonJS variables in the 2247 | //order listed below. 2248 | deps = ( 2249 | callback.length === 1 ? ['require'] : ['require', 'exports', 'module'] 2250 | ).concat(deps); 2251 | } 2252 | } 2253 | 2254 | //If in IE 6-8 and hit an anonymous define() call, do the interactive 2255 | //work. 2256 | if (useInteractive) { 2257 | node = currentlyAddingScript || getInteractiveScript(); 2258 | if (node) { 2259 | if (!name) { 2260 | name = node.getAttribute('data-requiremodule'); 2261 | } 2262 | context = contexts[node.getAttribute('data-requirecontext')]; 2263 | } 2264 | } 2265 | 2266 | //Always save off evaluating the def call until the script onload handler. 2267 | //This allows multiple modules to be in a file without prematurely 2268 | //tracing dependencies, and allows for anonymous module support, 2269 | //where the module name is not known until the script onload event 2270 | //occurs. If no context, use the global queue, and get it processed 2271 | //in the onscript load callback. 2272 | if (context) { 2273 | context.defQueue.push([name, deps, callback]); 2274 | context.defQueueMap[name] = true; 2275 | } else { 2276 | globalDefQueue.push([name, deps, callback]); 2277 | } 2278 | }; 2279 | 2280 | define.amd = { 2281 | jQuery: true, 2282 | }; 2283 | 2284 | /** 2285 | * Executes the text. Normally just uses eval, but can be modified 2286 | * to use a better, environment-specific call. Only used for transpiling 2287 | * loader plugins, not for plain JS modules. 2288 | * @param {String} text the text to execute/evaluate. 2289 | */ 2290 | req.exec = function (text) { 2291 | /*jslint evil: true */ 2292 | return eval(text); 2293 | }; 2294 | 2295 | //Set up with config info. 2296 | req(cfg); 2297 | })(this, typeof setTimeout === 'undefined' ? undefined : setTimeout); 2298 | -------------------------------------------------------------------------------- /doc/api.md: -------------------------------------------------------------------------------- 1 | # 文档 2 | 3 | pubsub是一个小而美的发布订阅者模式库。 4 | 5 | ## PubSub 6 | 7 | 调度中心实例构造函数 8 | 9 | 可以生成调度中心实例,实例上都可以挂载订阅者 10 | 11 | 函数参数和返回值 12 | 13 | - return {object} 调度实例 14 | 15 | 举个例子 16 | 17 | ```js 18 | new PubSub(); // 调度中心实例 19 | ``` 20 | 21 | ## subscribe / sub 22 | 23 | 添加订阅者 24 | 25 | 订阅特定的消息,当消息被 emit 时调用传入的订阅函数 26 | 27 | 函数参数和返回值 28 | 29 | - param {string} channel 订阅的消息名 30 | - param {function} 订阅函数当消息被 emit 时调用该函数 31 | - return {object} 传入的参数所组成的对象 32 | 33 | 举个例子 34 | 35 | ```js 36 | subscribe('hello', (...args) => { 37 | //... 38 | }); 39 | // 下面方式作用相同: 40 | sub('hello', (...args) => { 41 | //... 42 | }); 43 | ``` 44 | 45 | ## unsubscribe / unsub 46 | 47 | 注销订阅者 48 | 49 | 针对特定消息注销指定的订阅函数 50 | 51 | 函数参数和返回值 52 | 53 | - param {string} channel 订阅的消息名 54 | - param {function} 该函数的指针 55 | - return {undefined} 56 | 57 | 举个例子(要包含代码用例) 58 | 59 | ```js 60 | const cb = (...args) => { 61 | //... 62 | }; 63 | subscribe('hello', cb); 64 | 65 | unsubscribe('hello', cb); // 注销了cb 66 | // 下面方式作用相同: 67 | unsub('hello', cb); 68 | ``` 69 | 70 | ## publish / pub 71 | 72 | 发送指定消息 73 | 74 | 发送消息后会调用该消息下挂载的所有订阅函数 75 | 76 | 函数参数和返回值 77 | 78 | - param {string} channel 订阅的消息名 79 | - param {\*} ...args 传递给每个回调函数的参数 80 | - return {undefined} 81 | 82 | 举个例子(要包含代码用例) 83 | 84 | ```js 85 | const cb = (...args) => { 86 | //... 87 | }; 88 | subscribe('hello', cb); 89 | 90 | publish('hello', 1, [2], { foo: 3 }); // 此处执行 cb(1, [2], {foo: 3}) 91 | // 下面方式作用相同: 92 | pub('hello', 1, [2], { foo: 3 }); // 此处执行 cb(1, [2], {foo: 3}) 93 | ``` 94 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export as namespace jsminiPubsub; 2 | 3 | export declare class PubSub { 4 | subscribe(channel: string, callback: Function): object; 5 | unsubscribe(channel: string, callback: Function): void; 6 | publish(channel: string, ...args: Array): void; 7 | sub(channel: string, callback: Function): object; 8 | unsub(channel: string, callback: Function): void; 9 | pub(channel: string, ...args: Array): void; 10 | } 11 | 12 | export function subscribe(channel: string, callback: Function): object; 13 | export function unsubscribe(channel: string, callback: Function): void; 14 | export function publish(channel: string, ...args: Array): void; 15 | export function sub(channel: string, callback: Function): object; 16 | export function unsub(channel: string, callback: Function): void; 17 | export function pub(channel: string, ...args: Array): void; 18 | -------------------------------------------------------------------------------- /jslib.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pubsub", 3 | "npmname": "@jsmini/pubsub", 4 | "umdname": "jsmini_pubsub", 5 | "username": "jsmini", 6 | "type": "js", 7 | "lang": "zh", 8 | "version": "1.3.0" 9 | } 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@jsmini/pubsub", 3 | "version": "0.4.0", 4 | "description": "A small yet beautiful PubSub library, implementing the Publisher-Subscriber pattern.", 5 | "main": "dist/index.js", 6 | "module": "dist/index.esm.js", 7 | "sideEffects": false, 8 | "exports": { 9 | "node": { 10 | "import": "./dist/index.mjs", 11 | "default": "./dist/index.js" 12 | }, 13 | "default": { 14 | "import": "./dist/index.mjs", 15 | "default": "./dist/index.js" 16 | } 17 | }, 18 | "scripts": { 19 | "clean": "rimraf ./dist ./types", 20 | "lint": "eslint -c .eslintrc.cjs 'src/**/*.js'", 21 | "build:self": "rollup -c config/rollup.config.cjs", 22 | "build:esm": "rollup -c config/rollup.config.esm.cjs", 23 | "build:aio": "rollup -c config/rollup.config.aio.cjs", 24 | "build": "npm run clean && npm run build:self && npm run build:esm && npm run build:aio", 25 | "test": "cross-env NODE_ENV=test nyc mocha", 26 | "release": "npm test && npm run build && git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags", 27 | "lint:fix": "eslint --fix -c .eslintrc.cjs 'src/**/*.js' --fix", 28 | "coveralls": "nyc report --reporter=text-lcov | coveralls", 29 | "preinstall": "npx only-allow npm", 30 | "start": "http-server -p 3000 -c-1", 31 | "prepare": "husky install", 32 | "ci": "commit", 33 | "cz": "git-cz" 34 | }, 35 | "author": "yanhaijing", 36 | "license": "MIT", 37 | "repository": { 38 | "type": "git", 39 | "url": "git://github.com/jsmini/pubsub.git" 40 | }, 41 | "bugs": { 42 | "url": "https://github.com/jsmini/pubsub/issues" 43 | }, 44 | "dependencies": { 45 | "@jsmini/event": "^0.8.0", 46 | "@jsmini/is": "^0.10.0" 47 | }, 48 | "files": [ 49 | "/dist", 50 | "/types", 51 | "*.d.ts" 52 | ], 53 | "engines": { 54 | "node": ">=14.0.0", 55 | "npm": ">=6.0.0" 56 | }, 57 | "publishConfig": { 58 | "registry": "https://registry.npmjs.org", 59 | "access": "public" 60 | }, 61 | "config": { 62 | "commitizen": { 63 | "path": "@commitlint/cz-commitlint" 64 | } 65 | }, 66 | "devDependencies": { 67 | "babel-plugin-transform-runtime": "6.23.0", 68 | "cdkit": "1.1.0", 69 | "es5-shim": "^4.6.7", 70 | "eslint": "^8.54.0", 71 | "expect.js": "^0.3.1", 72 | "mocha": "^10.2.0", 73 | "rimraf": "^5.0.5", 74 | "rollup": "^3.29.4", 75 | "@js-lib/cli": "^2.3.2", 76 | "cross-env": "^7.0.3", 77 | "@babel/plugin-transform-runtime": "^7.23.3", 78 | "@babel/preset-env": "^7.23.3", 79 | "@babel/register": "^7.22.15", 80 | "babel-plugin-istanbul": "^6.1.1", 81 | "coveralls": "^3.1.1", 82 | "nyc": "^15.1.0", 83 | "source-map-support": "0.5.9", 84 | "http-server": "^14.1.1", 85 | "@babel/eslint-parser": "^7.23.3", 86 | "eslint-config-prettier": "^9.0.0", 87 | "eslint-plugin-import": "^2.29.0", 88 | "eslint-plugin-prettier": "^5.0.1", 89 | "husky": "^8.0.0", 90 | "lint-staged": "^14.0.1", 91 | "prettier": "3.1.0", 92 | "commitizen": "^4.2.4", 93 | "@commitlint/cli": "^16.3.0", 94 | "@commitlint/config-conventional": "^16.2.4", 95 | "@commitlint/cz-commitlint": "^16.3.0", 96 | "@commitlint/format": "^12.1.1", 97 | "@commitlint/prompt-cli": "^16.3.0", 98 | "@rollup/plugin-babel": "^6.0.4", 99 | "@rollup/plugin-commonjs": "^25.0.7", 100 | "@rollup/plugin-node-resolve": "^15.2.3", 101 | "@rollup/plugin-terser": "^0.4.4" 102 | } 103 | } -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { isObject, isFunction } from '@jsmini/is'; 2 | 3 | import { EventEmitter } from '@jsmini/event'; 4 | 5 | export function PubSub() { 6 | this.ec = new EventEmitter(); 7 | } 8 | 9 | PubSub.prototype.subscribe = function (channel, callback) { 10 | this.ec.addListener(channel, callback); 11 | 12 | return { channel, callback }; 13 | }; 14 | 15 | PubSub.prototype.unsubscribe = function (channel, callback) { 16 | if (isObject(channel) && !isFunction(callback)) { 17 | callback = channel.callback; 18 | channel = channel.channel; 19 | } 20 | 21 | if (isFunction(callback)) { 22 | this.ec.removeListener(channel, callback); 23 | } else { 24 | this.ec.removeAllListeners(channel); 25 | } 26 | }; 27 | 28 | PubSub.prototype.publish = function (channel, ...args) { 29 | this.ec.emit(channel, ...args); 30 | }; 31 | 32 | PubSub.prototype.sub = PubSub.prototype.subscribe; 33 | PubSub.prototype.unsub = PubSub.prototype.unsubscribe; 34 | PubSub.prototype.pub = PubSub.prototype.publish; 35 | 36 | const pb = new PubSub(); 37 | 38 | export const subscribe = function (channel, callback) { 39 | return pb.subscribe(channel, callback); 40 | }; 41 | 42 | export const unsubscribe = function (channel, callback) { 43 | return pb.unsubscribe(channel, callback); 44 | }; 45 | 46 | export const publish = function (channel, ...args) { 47 | return pb.publish(channel, ...args); 48 | }; 49 | 50 | export const sub = subscribe; 51 | 52 | export const unsub = unsubscribe; 53 | 54 | export const pub = publish; 55 | -------------------------------------------------------------------------------- /test/browser/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Mocha 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 30 | 31 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | var expect = require('expect.js'); 2 | 3 | var base = require('../src/index.js'); 4 | 5 | describe('单元测试', function () { 6 | this.timeout(1000); 7 | 8 | describe('触发订阅', () => { 9 | base.sub('hello', (str) => { 10 | it('相等', () => { 11 | expect(str).to.equal('test'); 12 | }); 13 | }); 14 | base.pub('hello', 'test'); 15 | }); 16 | 17 | describe('取消/订阅', () => { 18 | var flag = { num: 0 }; 19 | var cb = (flag) => { 20 | flag.num++; 21 | }; 22 | 23 | base.sub('test', cb); 24 | base.pub('test', flag); 25 | it('正确订阅', () => { 26 | expect(flag.num).to.equal(1); 27 | }); 28 | 29 | base.unsub('test', cb); 30 | base.pub('test', flag); 31 | it('取消订阅', () => { 32 | expect(flag.num).to.equal(1); 33 | }); 34 | }); 35 | 36 | describe('构造函数测试', () => { 37 | var foo = new base.PubSub(); 38 | it('实例构造检测', () => { 39 | expect(foo.pub).to.equal(foo.publish); 40 | expect(foo.unsub).to.equal(foo.unsubscribe); 41 | expect(foo.sub).to.equal(foo.subscribe); 42 | 43 | expect(foo.ec).to.be.an('object'); 44 | }); 45 | }); 46 | }); 47 | --------------------------------------------------------------------------------